詳解在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.導入依賴包
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'>請在微信客戶端打開鏈接</h4></div></div>’;}
在main.js中引用:
import env from './env';//運行環境
微信登錄,通過code換取openid,在起始頁使用該方法:
<script>methods:{ // 微信登陸 wxLogin() { var that = this; axios.get('/common/loginAuth').then(function(res) { console.log('后臺返回的鏈接地址', res.data); window.location.href = res.data;//跳轉后臺返回的鏈接地址}).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;//獲取當前鏈接,拆分當前鏈接 //當前鏈接地址為后臺返回的參數,有拆分得到鏈接中的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] } //向服務端提供授權url參數,并且不需要#后面的部分}).then((res)=>{wx.config({debug: true, // 開啟調試模式,appId: res.appId, // 必填,企業號的唯一標識,此處填寫企業號corpidtimestamp: res.timestamp, // 必填,生成簽名的時間戳nonceStr: res.nonceStr, // 必填,生成簽名的隨機串signature: res.signature,// 必填,簽名,見附錄1jsApiList: [’scanQRCode’] // 必填,需要使用的JS接口列表,所有JS接口列});})
到此這篇關于 詳解在vue使用weixin-js-sdk常見使用方法的文章就介紹到這了,更多相關vue weixin-js-sdk內容請搜索好吧啦網以前的文章或繼續瀏覽下面的相關文章希望大家以后多多支持好吧啦網!
相關文章:
