根據微信開發文檔步驟以下:php
1.先登陸微信公衆平臺進入「公衆號設置」的「功能設置」裏填寫「JS接口安全域名」。css
JS接口安全域名設置 mi.com(前面不用帶www/http,域名必須備案過)html
2.引入JS文件
在須要調用JS接口的頁面引入以下JS文件,(支持https):http://res.wx.qq.com/open/js/jweixin-1.0.0.jsjava
3.經過config接口注入權限驗證配置git
wx.config({ debug: true, // 開啓調試模式,調用的全部api的返回值會在客戶端alert出來,若要查看傳入的參數,能夠在pc端打開,參數信息會經過log打出,僅在pc端時纔會打印。 appId: '', // 必填,公衆號的惟一標識 timestamp: , // 必填,生成簽名的時間戳 nonceStr: '', // 必填,生成簽名的隨機串 signature: '',// 必填,簽名,見附錄1 jsApiList: [] // 必填,須要使用的JS接口列表,全部JS接口列表見附錄2 });
注:appId從公衆號裏面獲取,timestamp、nonceStr、signature臨時經過按微信規定的規則發送url獲取
web
4.經過ready接口處理成功驗證ajax
wx.ready(function(){ // config信息驗證後會執行ready方法,全部接口調用都必須在config接口得到結果以後,config是一個客戶端的異步操做,因此若是須要在頁面加載時就調用相關接口,則須把相關接口放在ready函數中調用來確保正確執行。對於用戶觸發時才調用的接口,則能夠直接調用,不須要放在ready函數中。 });
5.經過error接口處理失敗驗證,測試時能夠先不用這個json
wx.error(function(res){ // config信息驗證失敗會執行error函數,如簽名過時致使驗證失敗,具體錯誤信息能夠打開config的debug模式查看,也能夠在返回的res參數中查看,對於SPA能夠在這裏更新簽名。 });
JS-SDK網頁全部接口代碼以下:api
<?php require_once "jssdk.php"; $jssdk = new JSSDK("wx46c6ccb293dfsda5fd", "e5e7ad8f4b068f118939f2cec0bc98394d"); //APPID和SECRET $signPackage = $jssdk->GetSignPackage(); ?> <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>微信JS-SDK Demo</title> <meta name="viewport" content="width=device-width, initial-scale=1, user-scalable=0"> <link rel="stylesheet" href="http://demo.open.weixin.qq.com/jssdk/css/style.css?ts=1420774989"> </head> <body> <div class="wxapi_container"> <div class="wxapi_index_container"> <ul class="label_box lbox_close wxapi_index_list"> <li class="label_item wxapi_index_item"><a class="label_inner" href="#menu-basic">基礎接口</a></li> <li class="label_item wxapi_index_item"><a class="label_inner" href="#menu-share">分享接口</a></li> <li class="label_item wxapi_index_item"><a class="label_inner" href="#menu-image">圖像接口</a></li> <li class="label_item wxapi_index_item"><a class="label_inner" href="#menu-voice">音頻接口</a></li> <li class="label_item wxapi_index_item"><a class="label_inner" href="#menu-smart">智能接口</a></li> <li class="label_item wxapi_index_item"><a class="label_inner" href="#menu-device">設備信息接口</a></li> <li class="label_item wxapi_index_item"><a class="label_inner" href="#menu-location">地理位置接口</a></li> <li class="label_item wxapi_index_item"><a class="label_inner" href="#menu-webview">界面操做接口</a></li> <li class="label_item wxapi_index_item"><a class="label_inner" href="#menu-scan">微信掃一掃接口</a></li> <li class="label_item wxapi_index_item"><a class="label_inner" href="#menu-shopping">微信小店接口</a></li> <li class="label_item wxapi_index_item"><a class="label_inner" href="#menu-card">微信卡券接口</a></li> <li class="label_item wxapi_index_item"><a class="label_inner" href="#menu-pay">微信支付接口</a></li> </ul> </div> <div class="lbox_close wxapi_form"> <h3 id="menu-basic">基礎接口</h3> 判斷當前客戶端是否支持指定JS接口 <button class="btn btn_primary" id="checkJsApi">checkJsApi</button> <h3 id="menu-share">分享接口</h3> 獲取「分享到朋友圈」按鈕點擊狀態及自定義分享內容接口 <button class="btn btn_primary" id="onMenuShareTimeline">onMenuShareTimeline</button> 獲取「分享給朋友」按鈕點擊狀態及自定義分享內容接口 <button class="btn btn_primary" id="onMenuShareAppMessage">onMenuShareAppMessage</button> 獲取「分享到QQ」按鈕點擊狀態及自定義分享內容接口 <button class="btn btn_primary" id="onMenuShareQQ">onMenuShareQQ</button> 獲取「分享到騰訊微博」按鈕點擊狀態及自定義分享內容接口 <button class="btn btn_primary" id="onMenuShareWeibo">onMenuShareWeibo</button> <h3 id="menu-image">圖像接口</h3> 拍照或從手機相冊中選圖接口 <button class="btn btn_primary" id="chooseImage">chooseImage</button> 預覽圖片接口 <button class="btn btn_primary" id="previewImage">previewImage</button> 上傳圖片接口 <button class="btn btn_primary" id="uploadImage">uploadImage</button> 下載圖片接口 <button class="btn btn_primary" id="downloadImage">downloadImage</button> <h3 id="menu-voice">音頻接口</h3> 開始錄音接口 <button class="btn btn_primary" id="startRecord">startRecord</button> 中止錄音接口 <button class="btn btn_primary" id="stopRecord">stopRecord</button> 播放語音接口 <button class="btn btn_primary" id="playVoice">playVoice</button> 暫停播放接口 <button class="btn btn_primary" id="pauseVoice">pauseVoice</button> 中止播放接口 <button class="btn btn_primary" id="stopVoice">stopVoice</button> 上傳語音接口 <button class="btn btn_primary" id="uploadVoice">uploadVoice</button> 下載語音接口 <button class="btn btn_primary" id="downloadVoice">downloadVoice</button> <h3 id="menu-smart">智能接口</h3> 識別音頻並返回識別結果接口 <button class="btn btn_primary" id="translateVoice">translateVoice</button> <h3 id="menu-device">設備信息接口</h3> 獲取網絡狀態接口 <button class="btn btn_primary" id="getNetworkType">getNetworkType</button> <h3 id="menu-location">地理位置接口</h3> 使用微信內置地圖查看位置接口 <button class="btn btn_primary" id="openLocation">openLocation</button> 獲取地理位置接口 <button class="btn btn_primary" id="getLocation">getLocation</button> <h3 id="menu-webview">界面操做接口</h3> 隱藏右上角菜單接口 <button class="btn btn_primary" id="hideOptionMenu">hideOptionMenu</button> 顯示右上角菜單接口 <button class="btn btn_primary" id="showOptionMenu">showOptionMenu</button> 關閉當前網頁窗口接口 <button class="btn btn_primary" id="closeWindow">closeWindow</button> 批量隱藏功能按鈕接口 <button class="btn btn_primary" id="hideMenuItems">hideMenuItems</button> 批量顯示功能按鈕接口 <button class="btn btn_primary" id="showMenuItems">showMenuItems</button> 隱藏全部非基礎按鈕接口 <button class="btn btn_primary" id="hideAllNonBaseMenuItem">hideAllNonBaseMenuItem</button> 顯示全部功能按鈕接口 <button class="btn btn_primary" id="showAllNonBaseMenuItem">showAllNonBaseMenuItem</button> <h3 id="menu-scan">微信掃一掃</h3> 調起微信掃一掃接口 <button class="btn btn_primary" id="scanQRCode0">scanQRCode(微信處理結果)</button> <button class="btn btn_primary" id="scanQRCode1">scanQRCode(直接返回結果)</button> <h3 id="menu-shopping">微信小店接口</h3> 跳轉微信商品頁接口 <button class="btn btn_primary" id="openProductSpecificView">openProductSpecificView</button> <h3 id="menu-card">微信卡券接口</h3> 批量添加卡券接口 <button class="btn btn_primary" id="addCard">addCard</button> 調起適用於門店的卡券列表並獲取用戶選擇列表 <button class="btn btn_primary" id="chooseCard">chooseCard</button> 查看微信卡包中的卡券接口 <button class="btn btn_primary" id="openCard">openCard</button> <h3 id="menu-pay">微信支付接口</h3> 發起一個微信支付請求 <button class="btn btn_primary" id="chooseWXPay">chooseWXPay</button> </div> </div> </body> <!--步驟二:引入JS文件 --> <script src="http://res.wx.qq.com/open/js/jweixin-1.0.0.js"></script> <script> //步驟三:經過config接口注入權限驗證配置 wx.config({ debug: false, appId: '<?php echo $signPackage["appId"];?>', timestamp: <?php echo $signPackage["timestamp"];?>, nonceStr: '<?php echo $signPackage["nonceStr"];?>', signature: '<?php echo $signPackage["signature"];?>', jsApiList: [ 'checkJsApi', 'onMenuShareTimeline', 'onMenuShareAppMessage', 'onMenuShareQQ', 'onMenuShareWeibo', 'hideMenuItems', 'showMenuItems', 'hideAllNonBaseMenuItem', 'showAllNonBaseMenuItem', 'translateVoice', 'startRecord', 'stopRecord', 'onRecordEnd', 'playVoice', 'pauseVoice', 'stopVoice', 'uploadVoice', 'downloadVoice', 'chooseImage', 'previewImage', 'uploadImage', 'downloadImage', 'getNetworkType', 'openLocation', 'getLocation', 'hideOptionMenu', 'showOptionMenu', 'closeWindow', 'scanQRCode', 'chooseWXPay', 'openProductSpecificView', 'addCard', 'chooseCard', 'openCard' ] }); </script> <script> //步驟四:經過ready接口處理成功驗證 wx.ready(function () { // 1 判斷當前版本是否支持指定 JS 接口,支持批量判斷 document.querySelector('#checkJsApi').onclick = function () { wx.checkJsApi({ jsApiList: [ 'getNetworkType', 'previewImage' ], success: function (res) { alert(JSON.stringify(res)); } }); }; // 2. 分享接口 // 2.1 監聽「分享給朋友」,按鈕點擊、自定義分享內容及分享結果接口 document.querySelector('#onMenuShareAppMessage').onclick = function () { wx.onMenuShareAppMessage({ title: '互聯網之子', desc: '在長大的過程當中,我才慢慢發現,我身邊的全部事,別人跟我說的全部事,那些所謂原本如此,註定如此的事,它們其實沒有非得如此,事情是能夠改變的。更重要的是,有些事既然錯了,那就該作出改變。', link: 'http://movie.douban.com/subject/25785114/', imgUrl: 'http://demo.open.weixin.qq.com/jssdk/images/p2166127561.jpg', trigger: function (res) { // 不要嘗試在trigger中使用ajax異步請求修改本次分享的內容,由於客戶端分享操做是一個同步操做,這時候使用ajax的回包會尚未返回 alert('用戶點擊發送給朋友'); }, success: function (res) { alert('已分享'); }, cancel: function (res) { alert('已取消'); }, fail: function (res) { alert(JSON.stringify(res)); } }); alert('已註冊獲取「發送給朋友」狀態事件'); }; // 2.2 監聽「分享到朋友圈」按鈕點擊、自定義分享內容及分享結果接口 document.querySelector('#onMenuShareTimeline').onclick = function () { wx.onMenuShareTimeline({ title: '互聯網之子', link: 'http://movie.douban.com/subject/25785114/', imgUrl: 'http://demo.open.weixin.qq.com/jssdk/images/p2166127561.jpg', trigger: function (res) { // 不要嘗試在trigger中使用ajax異步請求修改本次分享的內容,由於客戶端分享操做是一個同步操做,這時候使用ajax的回包會尚未返回 alert('用戶點擊分享到朋友圈'); }, success: function (res) { alert('已分享'); }, cancel: function (res) { alert('已取消'); }, fail: function (res) { alert(JSON.stringify(res)); } }); alert('已註冊獲取「分享到朋友圈」狀態事件'); }; // 2.3 監聽「分享到QQ」按鈕點擊、自定義分享內容及分享結果接口 document.querySelector('#onMenuShareQQ').onclick = function () { wx.onMenuShareQQ({ title: '互聯網之子', desc: '在長大的過程當中,我才慢慢發現,我身邊的全部事,別人跟我說的全部事,那些所謂原本如此,註定如此的事,它們其實沒有非得如此,事情是能夠改變的。更重要的是,有些事既然錯了,那就該作出改變。', link: 'http://movie.douban.com/subject/25785114/', imgUrl: 'http://img3.douban.com/view/movie_poster_cover/spst/public/p2166127561.jpg', trigger: function (res) { alert('用戶點擊分享到QQ'); }, complete: function (res) { alert(JSON.stringify(res)); }, success: function (res) { alert('已分享'); }, cancel: function (res) { alert('已取消'); }, fail: function (res) { alert(JSON.stringify(res)); } }); alert('已註冊獲取「分享到 QQ」狀態事件'); }; // 2.4 監聽「分享到微博」按鈕點擊、自定義分享內容及分享結果接口 document.querySelector('#onMenuShareWeibo').onclick = function () { wx.onMenuShareWeibo({ title: '互聯網之子', desc: '在長大的過程當中,我才慢慢發現,我身邊的全部事,別人跟我說的全部事,那些所謂原本如此,註定如此的事,它們其實沒有非得如此,事情是能夠改變的。更重要的是,有些事既然錯了,那就該作出改變。', link: 'http://movie.douban.com/subject/25785114/', imgUrl: 'http://img3.douban.com/view/movie_poster_cover/spst/public/p2166127561.jpg', trigger: function (res) { alert('用戶點擊分享到微博'); }, complete: function (res) { alert(JSON.stringify(res)); }, success: function (res) { alert('已分享'); }, cancel: function (res) { alert('已取消'); }, fail: function (res) { alert(JSON.stringify(res)); } }); alert('已註冊獲取「分享到微博」狀態事件'); }; // 3 智能接口 var voice = { localId: '', serverId: '' }; // 3.1 識別音頻並返回識別結果 document.querySelector('#translateVoice').onclick = function () { if (voice.localId == '') { alert('請先使用 startRecord 接口錄製一段聲音'); return; } wx.translateVoice({ localId: voice.localId, complete: function (res) { if (res.hasOwnProperty('translateResult')) { alert('識別結果:' + res.translateResult); } else { alert('沒法識別'); } } }); }; // 4 音頻接口 // 4.2 開始錄音 document.querySelector('#startRecord').onclick = function () { wx.startRecord({ cancel: function () { alert('用戶拒絕受權錄音'); } }); }; // 4.3 中止錄音 document.querySelector('#stopRecord').onclick = function () { wx.stopRecord({ success: function (res) { voice.localId = res.localId; }, fail: function (res) { alert(JSON.stringify(res)); } }); }; // 4.4 監聽錄音自動中止 wx.onVoiceRecordEnd({ complete: function (res) { voice.localId = res.localId; alert('錄音時間已超過一分鐘'); } }); // 4.5 播放音頻 document.querySelector('#playVoice').onclick = function () { if (voice.localId == '') { alert('請先使用 startRecord 接口錄製一段聲音'); return; } wx.playVoice({ localId: voice.localId }); }; // 4.6 暫停播放音頻 document.querySelector('#pauseVoice').onclick = function () { wx.pauseVoice({ localId: voice.localId }); }; // 4.7 中止播放音頻 document.querySelector('#stopVoice').onclick = function () { wx.stopVoice({ localId: voice.localId }); }; // 4.8 監聽錄音播放中止 wx.onVoicePlayEnd({ complete: function (res) { alert('錄音(' + res.localId + ')播放結束'); } }); // 4.8 上傳語音 document.querySelector('#uploadVoice').onclick = function () { if (voice.localId == '') { alert('請先使用 startRecord 接口錄製一段聲音'); return; } wx.uploadVoice({ localId: voice.localId, success: function (res) { alert('上傳語音成功,serverId 爲' + res.serverId); voice.serverId = res.serverId; } }); }; // 4.9 下載語音 document.querySelector('#downloadVoice').onclick = function () { if (voice.serverId == '') { alert('請先使用 uploadVoice 上傳聲音'); return; } wx.downloadVoice({ serverId: voice.serverId, success: function (res) { alert('下載語音成功,localId 爲' + res.localId); voice.localId = res.localId; } }); }; // 5 圖片接口 // 5.1 拍照、本地選圖 var images = { localId: [], serverId: [] }; document.querySelector('#chooseImage').onclick = function () { wx.chooseImage({ success: function (res) { images.localId = res.localIds; alert('已選擇 ' + res.localIds.length + ' 張圖片'); } }); }; // 5.2 圖片預覽 document.querySelector('#previewImage').onclick = function () { wx.previewImage({ current: 'http://img5.douban.com/view/photo/photo/public/p1353993776.jpg', urls: [ 'http://img3.douban.com/view/photo/photo/public/p2152117150.jpg', 'http://img5.douban.com/view/photo/photo/public/p1353993776.jpg', 'http://img3.douban.com/view/photo/photo/public/p2152134700.jpg' ] }); }; // 5.3 上傳圖片 document.querySelector('#uploadImage').onclick = function () { if (images.localId.length == 0) { alert('請先使用 chooseImage 接口選擇圖片'); return; } var i = 0, length = images.localId.length; images.serverId = []; function upload() { wx.uploadImage({ localId: images.localId[i], success: function (res) { i++; alert('已上傳:' + i + '/' + length); images.serverId.push(res.serverId); if (i < length) { upload(); } }, fail: function (res) { alert(JSON.stringify(res)); } }); } upload(); }; // 5.4 下載圖片 document.querySelector('#downloadImage').onclick = function () { if (images.serverId.length === 0) { alert('請先使用 uploadImage 上傳圖片'); return; } var i = 0, length = images.serverId.length; images.localId = []; function download() { wx.downloadImage({ serverId: images.serverId[i], success: function (res) { i++; alert('已下載:' + i + '/' + length); images.localId.push(res.localId); if (i < length) { download(); } } }); } download(); }; // 6 設備信息接口 // 6.1 獲取當前網絡狀態 document.querySelector('#getNetworkType').onclick = function () { wx.getNetworkType({ success: function (res) { alert(res.networkType); }, fail: function (res) { alert(JSON.stringify(res)); } }); }; // 7 地理位置接口 // 7.1 查看地理位置 document.querySelector('#openLocation').onclick = function () { wx.openLocation({ latitude: 23.099994, longitude: 113.324520, name: 'TIT 創意園', address: '廣州市海珠區新港中路 397 號', scale: 14, infoUrl: 'http://weixin.qq.com' }); }; // 7.2 獲取當前地理位置 document.querySelector('#getLocation').onclick = function () { wx.getLocation({ success: function (res) { alert(JSON.stringify(res)); }, cancel: function (res) { alert('用戶拒絕受權獲取地理位置'); }, fail: function (res) { alert(JSON.stringify(res)); } }); }; // 8 界面操做接口 // 8.1 隱藏右上角菜單 document.querySelector('#hideOptionMenu').onclick = function () { wx.hideOptionMenu(); }; // 8.2 顯示右上角菜單 document.querySelector('#showOptionMenu').onclick = function () { wx.showOptionMenu(); }; // 8.3 批量隱藏菜單項 document.querySelector('#hideMenuItems').onclick = function () { wx.hideMenuItems({ menuList: [ 'menuItem:readMode', // 閱讀模式 'menuItem:share:timeline', // 分享到朋友圈 'menuItem:copyUrl' // 複製連接 ], success: function (res) { alert('已隱藏「閱讀模式」,「分享到朋友圈」,「複製連接」等按鈕'); }, fail: function (res) { alert(JSON.stringify(res)); } }); }; // 8.4 批量顯示菜單項 document.querySelector('#showMenuItems').onclick = function () { wx.showMenuItems({ menuList: [ 'menuItem:readMode', // 閱讀模式 'menuItem:share:timeline', // 分享到朋友圈 'menuItem:copyUrl' // 複製連接 ], success: function (res) { alert('已顯示「閱讀模式」,「分享到朋友圈」,「複製連接」等按鈕'); }, fail: function (res) { alert(JSON.stringify(res)); } }); }; // 8.5 隱藏全部非基本菜單項 document.querySelector('#hideAllNonBaseMenuItem').onclick = function () { wx.hideAllNonBaseMenuItem({ success: function () { alert('已隱藏全部非基本菜單項'); } }); }; // 8.6 顯示全部被隱藏的非基本菜單項 document.querySelector('#showAllNonBaseMenuItem').onclick = function () { wx.showAllNonBaseMenuItem({ success: function () { alert('已顯示全部非基本菜單項'); } }); }; // 8.7 關閉當前窗口 document.querySelector('#closeWindow').onclick = function () { wx.closeWindow(); }; // 9 微信原生接口 // 9.1.1 掃描二維碼並返回結果 document.querySelector('#scanQRCode0').onclick = function () { wx.scanQRCode(); }; // 9.1.2 掃描二維碼並返回結果 document.querySelector('#scanQRCode1').onclick = function () { wx.scanQRCode({ needResult: 1, desc: 'scanQRCode desc', success: function (res) { alert(JSON.stringify(res)); } }); }; // 10 微信支付接口 // 10.1 發起一個支付請求 document.querySelector('#chooseWXPay').onclick = function () { // 注意:此 Demo 使用 2.7 版本支付接口實現,建議使用此接口時參考微信支付相關最新文檔。 wx.chooseWXPay({ timestamp: 1414723227, nonceStr: 'noncestr', package: 'addition=action_id%3dgaby1234%26limit_pay%3d&bank_type=WX&body=innertest&fee_type=1&input_charset=GBK¬ify_url=http%3A%2F%2F120.204.206.246%2Fcgi-bin%2Fmmsupport-bin%2Fnotifypay&out_trade_no=1414723227818375338&partner=1900000109&spbill_create_ip=127.0.0.1&total_fee=1&sign=432B647FE95C7BF73BCD177CEECBEF8D', signType: 'SHA1', // 注意:新版支付接口使用 MD5 加密 paySign: 'bd5b1933cda6e9548862944836a9b52e8c9a2b69' }); }; // 11.3 跳轉微信商品頁 document.querySelector('#openProductSpecificView').onclick = function () { wx.openProductSpecificView({ productId: 'pDF3iY_m2M7EQ5EKKKWd95kAxfNw' }); }; // 12 微信卡券接口 // 12.1 添加卡券 document.querySelector('#addCard').onclick = function () { wx.addCard({ cardList: [ { cardId: 'pDF3iY9tv9zCGCj4jTXFOo1DxHdo', cardExt: '{"code": "", "openid": "", "timestamp": "1418301401", "signature":"64e6a7cc85c6e84b726f2d1cbef1b36e9b0f9750"}' }, { cardId: 'pDF3iY9tv9zCGCj4jTXFOo1DxHdo', cardExt: '{"code": "", "openid": "", "timestamp": "1418301401", "signature":"64e6a7cc85c6e84b726f2d1cbef1b36e9b0f9750"}' } ], success: function (res) { alert('已添加卡券:' + JSON.stringify(res.cardList)); } }); }; // 12.2 選擇卡券 document.querySelector('#chooseCard').onclick = function () { wx.chooseCard({ cardSign: '97e9c5e58aab3bdf6fd6150e599d7e5806e5cb91', timestamp: 1417504553, nonceStr: 'k0hGdSXKZEj3Min5', success: function (res) { alert('已選擇卡券:' + JSON.stringify(res.cardList)); } }); }; // 12.3 查看卡券 document.querySelector('#openCard').onclick = function () { alert('您沒有該公衆號的卡券沒法打開卡券。'); wx.openCard({ cardList: [ ] }); }; var shareData = { title: '微信JS-SDK Demo', desc: '微信JS-SDK,幫助第三方爲用戶提供更優質的移動web服務', link: 'http://demo.open.weixin.qq.com/jssdk/', imgUrl: 'http://mmbiz.qpic.cn/mmbiz/icTdbqWNOwNRt8Qia4lv7k3M9J1SKqKCImxJCt7j9rHYicKDI45jRPBxdzdyREWnk0ia0N5TMnMfth7SdxtzMvVgXg/0' }; wx.onMenuShareAppMessage(shareData); wx.onMenuShareTimeline(shareData); }); wx.error(function (res) { alert(res.errMsg); }); </script> </html>
JSSDK類安全
<?php class JSSDK { private $appId; private $appSecret; public function __construct($appId, $appSecret) { $this->appId = $appId; $this->appSecret = $appSecret; } public function getSignPackage() { $jsapiTicket = $this->getJsApiTicket(); // 注意 URL 必定要動態獲取,不能 hardcode. $protocol = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off' || $_SERVER['SERVER_PORT'] == 443) ? "https://" : "http://"; $url = "$protocol$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]"; $timestamp = time(); $nonceStr = $this->createNonceStr(); // 這裏參數的順序要按照 key 值 ASCII 碼升序排序 $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("jsapi_ticket.json")); if ($data->expire_time < time()) { $accessToken = $this->getAccessToken(); // 若是是企業號用如下 URL 獲取 ticket // $url = "https://qyapi.weixin.qq.com/cgi-bin/get_jsapi_ticket?access_token=$accessToken"; $url = "https://api.weixin.qq.com/cgi-bin/ticket/getticket?type=jsapi&access_token=$accessToken"; $res = json_decode($this->httpGet($url)); $ticket = $res->ticket; if ($ticket) { $data->expire_time = time() + 7000; $data->jsapi_ticket = $ticket; $fp = fopen("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("access_token.json")); if ($data->expire_time < time()) { // 若是是企業號用如下URL獲取access_token // $url = "https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid=$this->appId&corpsecret=$this->appSecret"; $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("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_SSL_VERIFYPEER, false); curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false); curl_setopt($curl, CURLOPT_URL, $url); $res = curl_exec($curl); curl_close($curl); return $res; } }