问题出现原因:
安卓端会自动调用微信认证接口,ios需要使用wx.ready()方法后才能被调用。
需要注意的点:
wx.ready()中放入wx.config()不能实现首次使用自动获取微信认证签名,应该是在调用wx.config()结束后调用
实现如下:
创建一个单独的js文件wxAuthConfig.js
// 获取微信签名export async function wxAuthConfig(){ axios({ url: `${_URL}/getWeiXinJSConfig`, async: true, type: 'get', headers: { mobile_login_token: store.state.login.token, 'Content-Type': 'application/json; charset=utf-8' }, params: { // url: encodeURI(location.href) url: encodeURI(window.location.href.split('#')[0]) } }).then(res => { if(res.data.code === 200){ let data = res.data.result.result; wx.config({ debug: true, appId: data.appId, timestamp: data.timestamp, // 必填,生成签名的时间戳 nonceStr: data.noneStr, // 必填,生成签名的随机串 signature: data.signature,// 必填,签名 jsApiList: ['scanQRCode'] // 必填,需要使用的JS接口列表 }); } }).catch(err => { console.log('签名获取失败!') }); // 很重要不能少,如果没有写ready,ios端会出现首次进入不会自动获取签名,需手动刷新 wx.ready(function(data) {})}
在扫码页面中调用:
import {isIOS, wxAuthConfig} from '@/util/wxAuthConfig.js'created(){ wxAuthConfig(); // 获取微信授权}, methods: { // 扫一扫 wxNewMacScan(i) { wx.scanQRCode({ needResult: 1, // 默认为0,扫描结果由微信处理,1则直接返回扫描结果, desc : 'scanQRCode desc', scanType: ["qrCode","barCode"], // 可以指定扫二维码还是一维码,默认二者都有 success: res => { let result = res.resultStr; // 当needResult 为 1 时,扫码返回的结果 let index = result.indexOf(','); i.newMachineInsideBarcode = result.substring(index + 1, result.length) }, }); }, }
这样就可以完美解决了。
有些文章提到是因为url中存在#应该使用encodeURIComponent进行编码,取#号前的地址,把encodeURI替换成encodeURIComponent但是还是没有成功。
// url: encodeURI(location.href)url: encodeURI(window.location.href.split('#')[0])
也有的文章提到在路由守卫router.beforeEach((to, from, next) => {})中提前判断当前设备是ios端还是Android端,如果是ios端,就在path==='/'时获取微信认证签名,并在进入使用扫一扫的页面时就获取微信认证签名。
main.js:
import {isIOS, wxAuthConfig} from '@/util/wxAuthConfig.js'router.beforeEach((to, from, next) => { let tokenData = localStorage.getItem(token); if (to.meta.requireAuth) { // 需要权限,进一步进行判断 if (tokenData) { // 通过vuex state获取当前的token是否存在 if(isIOS){ wxAuthConfig(); } next(); } else { //如果没有权限,重定向到登录页,进行登录 next({ path: '/login', }) } } else { //不需要权限 直接跳转 next(); }});
使用扫一扫页面:
import {isIOS, wxAuthConfig} from '@/util/wxAuthConfig.js'created(){ if(!isIOS()){ wxAuthConfig() }},methods: { wxScan(){ ... }}
这样也可以解决ios首次进入不能调用扫一扫的问题,但解决问题的本质就是在wxAuthConfig中调用wx.ready()。
写在最后:
记得在更新代码后刷新微信缓存,不然可能会遮盖修改好的效果哦!