微信分享,獲取分享點選事件,登入後才可以分享
阿新 • • 發佈:2018-11-29
1.登入微信公眾平臺
2.獲取開發者ID(AppID),開發者密碼(AppSecret)
3.配置js安全域名,下載.txt檔案放到專案跟目錄
4.控制器
<?php namespace M\Controller; use Think\Controller; class RedpacketController extends Controller { private $AppID; private $AppSecret; private $uid; public function _initialize() { $this->AppID = "abc11abcdef11111aa";//開發者ID(AppID) $this->AppSecret = "07jhdsklfjsdkfjsdeourwoe";//開發者密碼(AppSecret) $this->uid = 1000; //使用者ID,這裡寫的是固定的 } //微信分享 public function sharetest() { $uid = 1000; //////////////獲取微信分享配置資訊開始/////////////// $confdata = $this->getconfig(); $confdata = json_encode($confdata); /////////////獲取配置資訊結束////////////////////// $this->assign('confdata',$confdata); $this->assign('uid',$this->uid); $this->display(); } //獲取配置 private function getconfig() { $ticketres = $this->getSignname(); $nonceStr = $this->createNonceStr(); $protocol = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off' || $_SERVER['SERVER_PORT'] == 443) ? "https://" : "http://"; $rooturl = "$protocol$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]"; $jsapi_ticket = $ticketres['ticket']; $timestamp = $ticketres['timeval']; $appid = $ticketres['appid']; $str = "jsapi_ticket=".$jsapi_ticket."&noncestr=".$nonceStr."×tamp=".$timestamp."&url=".$rooturl; $signname = sha1($str); $share = array( 'title' => "匯商所微信分享頭部說明", 'desc' =>"客服熱線:400-606-8685(工作日 9:00-18:00)", 'img' => "NewStyle/newmobile/img/invite/register.png", ); $resarr = array( "timestamp"=>$timestamp, "signname" =>$signname, "nonceStr" =>$nonceStr, "appid" =>$appid, "title" =>$share['title'], "shareurl" =>"https://www.huishangsuo.com/m/Login/register", "img" =>C('APP_HOST').$share['img'], "desc" =>$share['desc'], ); return $resarr; } private function createNonceStr($length = 16) { $chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"; $str = ""; for ($i = 0; $i < $length; $i++) { $str .= substr($chars, mt_rand(0, strlen($chars) - 1), 1); } return $str; } //獲取簽名 public function getSignname(){ $accesstoken = $this->getAccessToken(); $filename = 'App/Library/Vendor/Wechat/signname'; $timeinfo = 'App/Library/Vendor/Wechat/time'; if(!file_exists($filename) || (file_exists($filename) && (time()-filemtime($filename)) > 7000)){//有效期2個小時 $url = 'https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token='.$accesstoken.'&type=jsapi'; $content = $this->request($url); $content = json_decode($content,true); $signname = $content['ticket']; $timeval = time(); file_put_contents($timeinfo, $timeval); file_put_contents($filename, $signname); }else{ $timeval = file_get_contents($timeinfo); $signname = file_get_contents($filename); } return array("ticket"=>$signname,"timeval"=>$timeval,"appid"=>$this->AppID); } //獲取access_token public function getAccessToken(){ //判斷的生成的access_token值是否過期 $filename = 'App/Library/Vendor/Wechat/accesstoken'; if(!file_exists($filename) || (file_exists($filename) && (time()-filemtime($filename)) > 7000)){//token有效期2個小時 $url = 'https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid='.$this->AppID.'&secret='.$this->AppSecret; $content = $this->request($url); $content = json_decode($content,true); $access_token = $content['access_token']; file_put_contents($filename, $access_token); }else{ $access_token = file_get_contents($filename); } return $access_token; } //傳送請求 public function request($url,$https=true,$method='get',$data=null){ //初始化url $ch = curl_init($url); //設定相關的引數 //字串不直接輸出,進行一個變數的儲存 curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); //判斷是否為https請求 if($https === true){ curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false); } //判斷是否為post請求 if($method == 'post'){ curl_setopt($ch, CURLOPT_POST, true); curl_setopt($ch, CURLOPT_POSTFIELDS, $data); } //傳送請求 $str = curl_exec($ch); //關閉連線 curl_close($ch); //返回請求到的結果 return $str; } }
5.html
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width,initial-scale=1,minimum-scale=1,maximum-scale=1,user-scalable=no" /> <title>微信分享</title> </head> <script src="__ROOT__/NewStyle/newmobile/js/jquery-1.9.1.min.js"></script> <script src="/NewStyle/newmobile/js/chatdemo.js"> </script> <script src="/NewStyle/newmobile/js/weixin.js"> </script> <body> </body> <script type="text/javascript"> $(function(){ //載入微信分享配置 var uid = "{$uid}"; //資料存到本地 sessionStorage.u_uid = uid; alerts(); }) function alerts(){ var confdata = {$confdata}; getconfig(confdata); } </script>
6.js
從https://res.wx.qq.com/open/js/jweixin-1.0.0.js下載微信的js後格式化,改名weixin.js,點選分享選擇分享給朋友會觸發function t(n, i, t),在function t(n, i, t)中增加判斷。
weixin.js
! function(e, n) { "function" == typeof define && (define.amd || define.cmd) ? define(function() { return n(e) }) : n(e, !0) } (this, function(e, n) { function i(n, i, t) { e.WeixinJSBridge ? WeixinJSBridge.invoke(n, o(i), function(e) { c(n, e, t) }) : d(n, t) } function t(n, i, t) { e.WeixinJSBridge ? WeixinJSBridge.on(n, function(e) { if(sessionStorage.u_uid == 0){ //提示使用者登入 var str = "<div>"; str += "<div style='line-height: .68rem;' id='u_con_withdraw'>確認登入</div>"; str += "<div style='line-height: 1.6rem;' id='u_con_tip'>登入後才可以分享</div>"; str += "<div class='bot'><p class='quxiao'>取消</p><p onclick='tiplogin()'>去登入</p></div>"; str += "</div>"; $(".tixian").html(str); $(".tixian").css("display","flex"); $(".quxiao").click(function(){ $(".tixian").css("display","none"); }) //返回false,程式碼就不會繼續執行了 return false; } t && t.trigger && t.trigger(e), c(n, e, i) }) : t ? d(n, t) : d(n, i) } function o(e) { return e = e || {}, e.appId = L.appId, e.verifyAppId = L.appId, e.verifySignType = "sha1", e.verifyTimestamp = L.timestamp + "", e.verifyNonceStr = L.nonceStr, e.verifySignature = L.signature, e } function r(e) { return { timeStamp: e.timestamp + "", nonceStr: e.nonceStr, package: e.package, paySign: e.paySign, signType: e.signType || "SHA1" } } function c(e, n, i) { delete n.err_code, delete n.err_desc, delete n.err_detail; var t = n.errMsg; t || (t = n.err_msg, delete n.err_msg, t = a(e, t), n.errMsg = t), (i = i || {})._complete && (i._complete(n), delete i._complete), t = n.errMsg || "", L.debug && !i.isInnerInvoke && alert(JSON.stringify(n)); var o = t.indexOf(":"); switch (t.substring(o + 1)) { case "ok": i.success && i.success(n); break; case "cancel": i.cancel && i.cancel(n); break; default: i.fail && i.fail(n) } i.complete && i.complete(n) } function a(e, n) { var i = e, t = g[i]; t && (i = t); var o = "ok"; if (n) { var r = n.indexOf(":"); "confirm" == (o = n.substring(r + 1)) && (o = "ok"), "failed" == o && (o = "fail"), -1 != o.indexOf("failed_") && (o = o.substring(7)), -1 != o.indexOf("fail_") && (o = o.substring(5)), "access denied" != (o = (o = o.replace(/_/g, " ")).toLowerCase()) && "no permission to execute" != o || (o = "permission denied"), "config" == i && "function not exist" == o && (o = "ok"), "" == o && (o = "fail") } return n = i + ":" + o } function s(e) { if (e) { for (var n = 0, i = e.length; n < i; ++n) { var t = e[n], o = m[t]; o && (e[n] = o) } return e } } function d(e, n) { if (! (!L.debug || n && n.isInnerInvoke)) { var i = g[e]; i && (e = i), n && n._complete && delete n._complete, console.log('"' + e + '",', n || "") } } function l(e) { 0 != A.preVerifyState && (v || w || L.debug || M < "6.0.2" || A.systemType < 0 || V || (V = !0, A.appId = L.appId, A.initTime = b.initEndTime - b.initStartTime, A.preVerifyTime = b.preVerifyEndTime - b.preVerifyStartTime, C.getNetworkType({ isInnerInvoke: !0, success: function(e) { A.networkType = e.networkType; var n = "http://open.weixin.qq.com/sdk/report?v=" + A.version + "&o=" + A.preVerifyState + "&s=" + A.systemType + "&c=" + A.clientVersion + "&a=" + A.appId + "&n=" + A.networkType + "&i=" + A.initTime + "&p=" + A.preVerifyTime + "&u=" + A.url; (new Image).src = n } }))) } function u() { return (new Date).getTime() } function p(n) { I && (e.WeixinJSBridge ? n() : h.addEventListener && h.addEventListener("WeixinJSBridgeReady", n, !1)) } function f() { C.invoke || (C.invoke = function(n, i, t) { e.WeixinJSBridge && WeixinJSBridge.invoke(n, o(i), t) }, C.on = function(n, i) { e.WeixinJSBridge && WeixinJSBridge.on(n, i) }) } if (!e.jWeixin) { var m = { config: "preVerifyJSAPI", onMenuShareTimeline: "menu:share:timeline", onMenuShareAppMessage: "menu:share:appmessage", onMenuShareQQ: "menu:share:qq", onMenuShareWeibo: "menu:share:weiboApp", onMenuShareQZone: "menu:share:QZone", previewImage: "imagePreview", getLocation: "geoLocation", openProductSpecificView: "openProductViewWithPid", addCard: "batchAddCard", openCard: "batchViewCard", chooseWXPay: "getBrandWCPayRequest" }, g = function() { var e = {}; for (var n in m) e[m[n]] = n; return e } (), h = e.document, y = h.title, S = navigator.userAgent.toLowerCase(), _ = navigator.platform.toLowerCase(), v = !(!_.match("mac") && !_.match("win")), w = -1 != S.indexOf("wxdebugger"), I = -1 != S.indexOf("micromessenger"), T = -1 != S.indexOf("android"), k = -1 != S.indexOf("iphone") || -1 != S.indexOf("ipad"), M = function() { var e = S.match(/micromessenger\/(\d+\.\d+\.\d+)/) || S.match(/micromessenger\/(\d+\.\d+)/); return e ? e[1] : "" } (), V = !1, x = !1, b = { initStartTime: u(), initEndTime: 0, preVerifyStartTime: 0, preVerifyEndTime: 0 }, A = { version: 1, appId: "", initTime: 0, preVerifyTime: 0, networkType: "", preVerifyState: 1, systemType: k ? 1 : T ? 2 : -1, clientVersion: M, url: encodeURIComponent(location.href) }, L = {}, P = { _completes: [] }, W = { state: 0, data: {} }; p(function() { b.initEndTime = u() }); var C = { config: function(e) { L = e, d("config", e); var n = !1 !== L.check; p(function() { if (n) i(m.config, { verifyJsApiList: s(L.jsApiList) }, function() { P._complete = function(e) { b.preVerifyEndTime = u(), W.state = 1, W.data = e }, P.success = function(e) { A.preVerifyState = 0 }, P.fail = function(e) { P._fail ? P._fail(e) : W.state = -1 }; var e = P._completes; return e.push(function() { l() }), P.complete = function(n) { for (var i = 0, t = e.length; i < t; ++i) e[i](); P._completes = [] }, P } ()), b.preVerifyStartTime = u(); else { W.state = 1; for (var e = P._completes, t = 0, o = e.length; t < o; ++t) e[t](); P._completes = [] } }), L.beta && f() }, ready: function(e) { 0 != W.state ? e() : (P._completes.push(e), !I && L.debug && e()) }, error: function(e) { M < "6.0.2" || x || (x = !0, -1 == W.state ? e(W.data) : P._fail = e) }, checkJsApi: function(e) { var n = function(e) { var n = e.checkResult; for (var i in n) { var t = g[i]; t && (n[t] = n[i], delete n[i]) } return e }; i("checkJsApi", { jsApiList: s(e.jsApiList) }, (e._complete = function(e) { if (T) { var i = e.checkResult; i && (e.checkResult = JSON.parse(i)) } e = n(e) }, e)) }, onMenuShareTimeline: function(e) { t(m.onMenuShareTimeline, { complete: function() { i("shareTimeline", { title: e.title || y, desc: e.title || y, img_url: e.imgUrl || "", link: e.link || location.href, type: e.type || "link", data_url: e.dataUrl || "" }, e) } }, e) }, onMenuShareAppMessage: function(e) { t(m.onMenuShareAppMessage, { complete: function(n) { "favorite" === n.scene ? i("sendAppMessage", { title: e.title || y, desc: e.desc || "", link: e.link || location.href, img_url: e.imgUrl || "", type: e.type || "link", data_url: e.dataUrl || "" }) : i("sendAppMessage", { title: e.title || y, desc: e.desc || "", link: e.link || location.href, img_url: e.imgUrl || "", type: e.type || "link", data_url: e.dataUrl || "" }, e) } }, e) }, onMenuShareQQ: function(e) { t(m.onMenuShareQQ, { complete: function() { i("shareQQ", { title: e.title || y, desc: e.desc || "", img_url: e.imgUrl || "", link: e.link || location.href }, e) } }, e) }, onMenuShareWeibo: function(e) { t(m.onMenuShareWeibo, { complete: function() { i("shareWeiboApp", { title: e.title || y, desc: e.desc || "", img_url: e.imgUrl || "", link: e.link || location.href }, e) } }, e) }, onMenuShareQZone: function(e) { t(m.onMenuShareQZone, { complete: function() { i("shareQZone", { title: e.title || y, desc: e.desc || "", img_url: e.imgUrl || "", link: e.link || location.href }, e) } }, e) }, startRecord: function(e) { i("startRecord", {}, e) }, stopRecord: function(e) { i("stopRecord", {}, e) }, onVoiceRecordEnd: function(e) { t("onVoiceRecordEnd", e) }, playVoice: function(e) { i("playVoice", { localId: e.localId }, e) }, pauseVoice: function(e) { i("pauseVoice", { localId: e.localId }, e) }, stopVoice: function(e) { i("stopVoice", { localId: e.localId }, e) }, onVoicePlayEnd: function(e) { t("onVoicePlayEnd", e) }, uploadVoice: function(e) { i("uploadVoice", { localId: e.localId, isShowProgressTips: 0 == e.isShowProgressTips ? 0 : 1 }, e) }, downloadVoice: function(e) { i("downloadVoice", { serverId: e.serverId, isShowProgressTips: 0 == e.isShowProgressTips ? 0 : 1 }, e) }, translateVoice: function(e) { i("translateVoice", { localId: e.localId, isShowProgressTips: 0 == e.isShowProgressTips ? 0 : 1 }, e) }, chooseImage: function(e) { i("chooseImage", { scene: "1|2", count: e.count || 9, sizeType: e.sizeType || ["original", "compressed"], sourceType: e.sourceType || ["album", "camera"] }, (e._complete = function(e) { if (T) { var n = e.localIds; try { n && (e.localIds = JSON.parse(n)) } catch(e) {} } }, e)) }, previewImage: function(e) { i(m.previewImage, { current: e.current, urls: e.urls }, e) }, uploadImage: function(e) { i("uploadImage", { localId: e.localId, isShowProgressTips: 0 == e.isShowProgressTips ? 0 : 1 }, e) }, downloadImage: function(e) { i("downloadImage", { serverId: e.serverId, isShowProgressTips: 0 == e.isShowProgressTips ? 0 : 1 }, e) }, getNetworkType: function(e) { var n = function(e) { var n = e.errMsg; e.errMsg = "getNetworkType:ok"; var i = e.subtype; if (delete e.subtype, i) e.networkType = i; else { var t = n.indexOf(":"), o = n.substring(t + 1); switch (o) { case "wifi": case "edge": case "wwan": e.networkType = o; break; default: e.errMsg = "getNetworkType:fail" } } return e }; i("getNetworkType", {}, (e._complete = function(e) { e = n(e) }, e)) }, openLocation: function(e) { i("openLocation", { latitude: e.latitude, longitude: e.longitude, name: e.name || "", address: e.address || "", scale: e.scale || 28, infoUrl: e.infoUrl || "" }, e) }, getLocation: function(e) { e = e || {}, i(m.getLocation, { type: e.type || "wgs84" }, (e._complete = function(e) { delete e.type }, e)) }, hideOptionMenu: function(e) { i("hideOptionMenu", {}, e) }, showOptionMenu: function(e) { i("showOptionMenu", {}, e) }, closeWindow: function(e) { i("closeWindow", {}, e = e || {}) }, hideMenuItems: function(e) { i("hideMenuItems", { menuList: e.menuList }, e) }, showMenuItems: function(e) { i("showMenuItems", { menuList: e.menuList }, e) }, hideAllNonBaseMenuItem: function(e) { i("hideAllNonBaseMenuItem", {}, e) }, showAllNonBaseMenuItem: function(e) { i("showAllNonBaseMenuItem", {}, e) }, scanQRCode: function(e) { i("scanQRCode", { needResult: (e = e || {}).needResult || 0, scanType: e.scanType || ["qrCode", "barCode"] }, (e._complete = function(e) { if (k) { var n = e.resultStr; if (n) { var i = JSON.parse(n); e.resultStr = i && i.scan_code && i.scan_code.scan_result } } }, e)) }, openProductSpecificView: function(e) { i(m.openProductSpecificView, { pid: e.productId, view_type: e.viewType || 0, ext_info: e.extInfo }, e) }, addCard: function(e) { for (var n = e.cardList, t = [], o = 0, r = n.length; o < r; ++o) { var c = n[o], a = { card_id: c.cardId, card_ext: c.cardExt }; t.push(a) } i(m.addCard, { card_list: t }, (e._complete = function(e) { var n = e.card_list; if (n) { for (var i = 0, t = (n = JSON.parse(n)).length; i < t; ++i) { var o = n[i]; o.cardId = o.card_id, o.cardExt = o.card_ext, o.isSuccess = !!o.is_succ, delete o.card_id, delete o.card_ext, delete o.is_succ } e.cardList = n, delete e.card_list } }, e)) }, chooseCard: function(e) { i("chooseCard", { app_id: L.appId, location_id: e.shopId || "", sign_type: e.signType || "SHA1", card_id: e.cardId || "", card_type: e.cardType || "", card_sign: e.cardSign, time_stamp: e.timestamp + "", nonce_str: e.nonceStr }, (e._complete = function(e) { e.cardList = e.choose_card_info, delete e.choose_card_info }, e)) }, openCard: function(e) { for (var n = e.cardList, t = [], o = 0, r = n.length; o < r; ++o) { var c = n[o], a = { card_id: c.cardId, code: c.code }; t.push(a) } i(m.openCard, { card_list: t }, e) }, chooseWXPay: function(e) { i(m.chooseWXPay, r(e), e) } }; return n && (e.wx = e.jWeixin = C), C } });
chatdemo.js
function getconfig(confdata) {
wx.config({
debug: false,
appId: confdata.appid,
timestamp:confdata.timestamp,
nonceStr: confdata.nonceStr,
signature: confdata.signname,
jsApiList: [
'onMenuShareTimeline',
'onMenuShareAppMessage',
'onMenuShareQQ',
'onMenuShareWeibo',
'onMenuShareQZone',
]
});
wx.ready(function () {
// 1 判斷當前版本是否支援指定 JS 介面,支援批量判斷
wx.checkJsApi({
jsApiList: ['onMenuShareTimeline','onMenuShareAppMessage','onMenuShareQQ','onMenuShareWeibo','onMenuShareQZone'], // 需要檢測的JS介面列表,所有JS介面列表見附錄2,
fail: function (res) {
alert(JSON.stringify(res));
}
});
//分享給朋友
wx.onMenuShareAppMessage({
title: confdata.title, // 分享標題
desc: confdata.desc, // 分享描述
link: confdata.shareurl, // 分享連結,該連結域名或路徑必須與當前頁面對應的公眾號JS安全域名一致
imgUrl: confdata.img, // 分享圖示
type: 'link',
dataUrl: '', // 如果type是music或video,則要提供資料鏈接,預設為空
success: function () {
// alert('已分享');
},
fail: function () {
alert('已取消');
}
});
//分享到朋友圈
wx.onMenuShareTimeline({
title: confdata.title, // 分享標題
link: confdata.shareurl, // 分享連結,該連結域名或路徑必須與當前頁面對應的公眾號JS安全域名一致
imgUrl: confdata.img, // 分享圖示
success: function () {
// 介面呼叫成功時執行的回撥函式。
// alert('已分享');
},
fail: function () {
// 介面呼叫失敗時執行的回撥函式
alert('已取消');
}
});
//分享到QQ
wx.onMenuShareQQ({
title: confdata.title, // 分享標題
desc: confdata.desc, // 分享描述
link: confdata.shareurl, // 分享連結,該連結域名或路徑必須與當前頁面對應的公眾號JS安全域名一致
imgUrl: confdata.img, // 分享圖示
success: function () {
// alert('已分享');
},
cancel: function () {
alert('已取消');
}
});
//分享到騰訊微博
wx.onMenuShareWeibo({
title: confdata.title, // 分享標題
desc: confdata.desc, // 分享描述
link: confdata.shareurl, // 分享連結,該連結域名或路徑必須與當前頁面對應的公眾號JS安全域名一致
imgUrl: confdata.img, // 分享圖示
success: function () {
// alert('已分享');
},
cancel: function () {
alert('已取消');
}
});
//分享到QQ空間
wx.onMenuShareQZone({
title: confdata.title, // 分享標題
link: confdata.shareurl, // 分享連結,該連結域名或路徑必須與當前頁面對應的公眾號JS安全域名一致
imgUrl: confdata.img, // 分享圖示
success: function () {
// alert('已分享');
},
cancel: function () {
alert('已取消');
}
});
wx.error(function (res) {
alert(res.errMsg);
});
})
}