一、預載入JSSDK
在網頁載入時,預載入JSSDK可以讓網頁更快地響應用戶操作。
(function() { var loadScript = function(url, callback){ var script = document.createElement('script'); script.type = 'text/javascript'; if (script.readyState){ //IE script.onreadystatechange = function(){ if (script.readyState == "loaded" || script.readyState == "complete"){ script.onreadystatechange = null; callback(); } }; } else { //Others script.onload = function(){ callback(); }; } script.src = url; document.getElementsByTagName("head")[0].appendChild(script); }; loadScript('https://res.wx.qq.com/open/js/jweixin-1.6.0.js', function() { // TODO: JSSDK初始化 }); })();
二、使用JSSDK進行微信公眾號分享
通過JSSDK,可以在網頁上設置微信公眾號分享的標題、描述和鏈接。以下為示例代碼:
wx.config({ debug: false, appId: '', timestamp: '', nonceStr: '', signature: '', jsApiList: ['updateAppMessageShareData', 'updateTimelineShareData', 'onMenuShareWeibo'] }); wx.ready(function () { wx.updateAppMessageShareData({ title: '分享標題', desc: '分享描述', link: '分享鏈接', imgUrl: '分享圖標鏈接', success: function () { } }); wx.updateTimelineShareData({ title: '分享標題', link: '分享鏈接', imgUrl: '分享圖標鏈接', success: function () { } }); wx.onMenuShareWeibo({ title: '分享標題', desc: '分享描述', link: '分享鏈接', imgUrl: '分享圖標鏈接', success: function () { } }); });
三、使用JSSDK進行微信支付
通過JSSDK,可以在網頁上進行微信支付。以下為示例代碼:
function onBridgeReady() { WeixinJSBridge.invoke( 'getBrandWCPayRequest', { "appId": "", //公眾號名稱,由商戶傳入 "timeStamp": "", //時間戳,自1970年以來的秒數 "nonceStr": "", //隨機串 "package": "", //商品包信息,由商戶傳入 "signType": "MD5", //微信簽名方式: "paySign": "" //微信簽名 }, function(res){ if(res.err_msg == "get_brand_wcpay_request:ok" ){ // TODO: 支付成功後跳轉到其他頁面 } } ); } if (typeof WeixinJSBridge == "undefined"){ if( document.addEventListener ){ document.addEventListener('WeixinJSBridgeReady', onBridgeReady, false); }else if (document.attachEvent){ document.attachEvent('WeixinJSBridgeReady', onBridgeReady); document.attachEvent('onWeixinJSBridgeReady', onBridgeReady); } }else{ onBridgeReady(); }
四、使用JSSDK獲取用戶地理位置
通過JSSDK,可以獲取用戶的地理位置信息。以下為示例代碼:
wx.config({ debug: false, appId: '', timestamp: '', nonceStr: '', signature: '', jsApiList: ['getLocation'] }); wx.ready(function(){ wx.getLocation({ type: 'gcj02', success: function (res) { var latitude = res.latitude; // 緯度,浮點數,範圍為90 ~ -90 var longitude = res.longitude; // 經度,浮點數,範圍為180 ~ -180。 // TODO: 使用經緯度進行相關操作 }, fail: function (res) { // TODO: 用戶拒絕授權或其他錯誤處理 } }); });
五、使用JSSDK進行掃碼
通過JSSDK,可以在網頁上進行掃碼操作。以下為示例代碼:
wx.config({ debug: false, appId: '', timestamp: '', nonceStr: '', signature: '', jsApiList: ['scanQRCode'] }); wx.ready(function(){ wx.scanQRCode({ needResult: 1, scanType: ["qrCode","barCode"], success: function (res) { var result = res.resultStr; // TODO: 使用掃碼結果進行相關操作 }, fail: function(res){ // TODO: 掃碼失敗處理 } }); });
原創文章,作者:小藍,如若轉載,請註明出處:https://www.506064.com/zh-tw/n/232137.html