詳解在vue使用weixin-js-sdk常見使用方法
鏈接:https://qydev.weixin.qq.com/wiki/index.php?title=%E5%BE%AE%E4%BF%A1JS-SDK%E6%8E%A5%E5%8F%A3#.E6.AD.A5.E9.AA.A4.E4.B8.80.EF.BC.9A.E5.BC.95.E5.85.A5JS.E6.96.87.E4.BB.B6
1.導(dǎo)入依賴包
npm install weixin-js-sdk
2.判斷是否是在微信瀏覽器中
env.js
<script>var ua = navigator.userAgent.toLowerCase();var isWeixin = ua.indexOf(’micromessenger’) != -1;var isAndroid = ua.indexOf(’android’) != -1;var isIos = (ua.indexOf(’iphone’) != -1) || (ua.indexOf(’ipad’) != -1);if(!isWeixin) { document.head.innerHTML = ’<title>抱歉,出錯了</title><meta charset='utf-8'><meta name='viewport' content='width=device-width, initial-scale=1, user-scalable=0'><link rel='stylesheet' type='text/css' rel='external nofollow' >’; document.body.innerHTML = ’<div class='weui_msg'><div class='weui_icon_area'><i class='weui_icon_info weui_icon_msg'></i></div><div class='weui_text_area'><h4 class='weui_msg_title'>請?jiān)谖⑿趴蛻舳舜蜷_鏈接</h4></div></div>’;}
在main.js中引用:
import env from './env';//運(yùn)行環(huán)境
微信登錄,通過code換取openid,在起始頁使用該方法:
<script>methods:{ // 微信登陸 wxLogin() { var that = this; axios.get('/common/loginAuth').then(function(res) { console.log('后臺返回的鏈接地址', res.data); window.location.href = res.data;//跳轉(zhuǎn)后臺返回的鏈接地址}).catch(function(error) {}); },//換取用戶信息 postCode(res) { var that = this; axios.post('/common/getUserInfo', { code: res}).then(function(res) { cookie.set('openid', res.data.openid);//code像后臺換取openid并存入}).catch(function(error) { console.log(error);}); }},created() { var r = window.location.href;//獲取當(dāng)前鏈接,拆分當(dāng)前鏈接 //當(dāng)前鏈接地址為后臺返回的參數(shù),有拆分得到鏈接中的code,通過postCode()方法獲取openid,沒有則通過wxLogin()方法開始微信登錄 if (r.indexOf('?') != -1) { r = r.split('?'); r = r[1].split('&'); r = r[0].split('='); r = r[1]; } else { this.wxLogin(); } if (r) { this.postCode(r); } else { this.wxLogin(); } },</script>
3.前端頁面使用
import wx from ’weixin-js-sdk’this.axios({method: ’post’,url: ’url’,data:{ url:location.href.split(’#’)[0] } //向服務(wù)端提供授權(quán)url參數(shù),并且不需要#后面的部分}).then((res)=>{wx.config({debug: true, // 開啟調(diào)試模式,appId: res.appId, // 必填,企業(yè)號的唯一標(biāo)識,此處填寫企業(yè)號corpidtimestamp: res.timestamp, // 必填,生成簽名的時(shí)間戳nonceStr: res.nonceStr, // 必填,生成簽名的隨機(jī)串signature: res.signature,// 必填,簽名,見附錄1jsApiList: [’scanQRCode’] // 必填,需要使用的JS接口列表,所有JS接口列});})
到此這篇關(guān)于 詳解在vue使用weixin-js-sdk常見使用方法的文章就介紹到這了,更多相關(guān)vue weixin-js-sdk內(nèi)容請搜索好吧啦網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持好吧啦網(wǎng)!
相關(guān)文章:
