注:開發文檔地址:https://developers.weixin.qq.com/doc/offiaccount/OA_Web_Apps/JS-SDK.html
准備工作:
1.先登錄微信公眾平台進入“公眾號設置”的“功能設置”里填寫“JS接口安全域名”。
2.需要用到wx模塊 引入 <script src="https://res.wx.qq.com/open/js/jweixin-1.6.0.js"></script> 文件
代碼:
前端
第一步需要進行配置
這里需要請求后端,實現后端生成簽名填的參數 和 config驗證的參數要一致
<?php /*******************/ include_once('./common/jssdk.php'); $jsapi = new JSSDK(appid,appsecret); $res = $jsapi->getSignPackage(); //獲取js的token ?>
wx.config({ debug: false, // 開啟調試模式,調用的所有api的返回值會在客戶端alert出來,若要查看傳入的參數,可以在pc端打開,參數信息會通過log打出,僅在pc端時才會打印。 appId: '', // 必填,公眾號的唯一標識 timestamp: <?php echo $res['timestamp']; ?>, // 必填,生成簽名的時間戳 nonceStr:'<?php echo $res["nonceStr"]; ?>', // 必填,生成簽名的隨機串 signature: '<?php echo $res["signature"]; ?>',// 必填,簽名 jsApiList: [ 'updateAppMessageShareData', 'onMenuShareTimeline', 'onMenuShareAppMessage' ] // 必填,需要使用的JS接口列表 });
第二步:config驗證成功后
wx.ready(function () { //需在用戶可能點擊分享按鈕前就先調用 var url = ''; //分享到朋友圈 wx.onMenuShareTimeline({ title: '分享標題', desc: '分享描述', link: url, // 分享的url imgUrl: 'https://t.0797hr.com/static/top.jpg', // 分享的圖標url trigger: function (res) { // alert(res) /////注意蘋果手機分享的時候要去掉alert事件,不然會出現莫名的彈框 }, success: function (res) { myresult(res); }, cancel: function (res) { }, fail: function (res) { } }); //分享給朋友 wx.onMenuShareAppMessage({ title: '分享標題', desc: '分享描述', link: url, //分享的url imgUrl: 'https://t.0797hr.com/static/top.jpg', // 圖標url trigger: function (res) { }, success: function (res) {
//分享成功后執行 myresult(res); }, cancel: function (res) { alert(2); }, fail: function (res) { alert(3); } }); });
wx.error(function(res){
alert(res);
// config信息驗證失敗會執行error函數,如簽名過期導致驗證失敗,具體錯誤信息可以打開config的debug模式查看,也可以在返回的res參數中查看,對於SPA可以在這里更新簽名。
});
后端:api_ticket有時間,請求次數限制,需要在后端抓取后緩存下來(最容易出現問題是在合成簽名) 接口簽名驗證工具:http://mp.weixin.qq.com/debug/cgi-bin/sandbox?t=jsapisign
class JSSDK { private $appId; private $appSecret; public function __construct($appId, $appSecret) { $this->appId = $appId; $this->appSecret = $appSecret; } public function getSignPackage() { $jsapiTicket = $this->getJsApiTicket(); $url = "https://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]"; $timestamp = time(); $nonceStr = $this->createNonceStr(); // 這里參數的順序要按照 key 值 ASCII 碼升序排序 // $string = "noncestr=$nonceStr&jsapi_ticket=$jsapiTicket×tamp=$timestamp&url=$url"; 這個順序是在1.6.0文檔找的但是不對 $string = "jsapi_ticket=$jsapiTicket&noncestr=$nonceStr×tamp=$timestamp&url=$url"; $signature = sha1($string); $signPackage = array( "appId" => $this->appId, "nonceStr" => $nonceStr, "timestamp" => $timestamp, "url" => $url, "signature" => $signature, "rawString" => $string ); return $signPackage; } 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; } private function getJsApiTicket() { // jsapi_ticket 應該全局存儲與更新,以下代碼以寫入到文件中做示例 $data = json_decode(file_get_contents("./log/jsapi_ticket.json")); if ($data->expire_time < time()) { $accessToken = $this->getAccessToken(); $url = "https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token=$accessToken&type=jsapi"; $res = json_decode($this->httpGet($url)); $ticket = $res->ticket; if ($ticket) { @$data->expire_time = time() + 7000; $data->jsapi_ticket = $ticket; $fp = fopen("./log/jsapi_ticket.json", "w"); fwrite($fp, json_encode($data)); fclose($fp); } } else { $ticket = $data->jsapi_ticket; } return $ticket; } private function getAccessToken() { // access_token 應該全局存儲與更新,以下代碼以寫入到文件中做示例 $data = json_decode(file_get_contents("./log/access_token.json")); if ($data->expire_time < time()) { $url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid={$this->appId}&secret={$this->appSecret}"; $res = json_decode($this->httpGet($url)); $access_token = $res->access_token; if ($access_token) { @$data->expire_time = time() + 7000; $data->access_token = $access_token; $fp = fopen("./log/access_token.json", "w"); fwrite($fp, json_encode($data)); fclose($fp); } } else { $access_token = $data->access_token; } return $access_token; } private function httpGet($url) { $curl = curl_init(); curl_setopt($curl, CURLOPT_RETURNTRANSFER, true); curl_setopt($curl, CURLOPT_TIMEOUT, 500); curl_setopt($curl, CURLOPT_URL, $url); $res = curl_exec($curl); curl_close($curl); return $res; } }