问题描述:
使用uni-app开发微信小程序,需要授权获取用户信息或者手机号。但是每次刚进去点第一次时报错,Illegal Buffer 解密失败。我是直接在前端解密的。获取手机号的代码我是参考的下面的链接:https://www.cnblogs.com/liessay/p/14131518.html
但是有个问题就是第一次点击总是提示失败,需要点击第二次才能正确解密。
解决方案:
网上搜索的答案是需要先login。但是我这里确实是先调用的 uni.login。实际上需要在页面加载的时候就先额外调用一次 uni.login方法。
具体的代码片段,供参考:
mounted() {
// 这里先调用一遍,看起来没啥用
this.prelogin();
},
methods: {
prelogin (res) {
const _that=this;
uni.login({
provider: 'weixin',
success: function (res2) {
_that.Code = res2.code;
}
});
},
getPhoneNumber (res) {
const _that=this;
let appid = _that.$base.appId;
let secret = _that.$base.appSecret;
uni.login({
provider: 'weixin',
success: function (res2) {
_that.Code = res2.code;
// 请求腾讯的接口换密文,这里$getData是我自己封装的,你可以用uni原生的写
_that.$getData.GetWXappid({
url:'https://api.weixin.qq.com/sns/jscode2session?appid=' + appid + '&secret=' + secret +'&js_code=' +res2.code + '&grant_type=authorization_code',
}).then((res4 = {}) => {
const res3=JSON.parse(res4.message);
_that.openid = res3.openid
_that.session_key = res3.session_key
console.log(`hhh`,appid, _that.session_key,res.detail.encryptedData, res.detail.iv);
//解密encryptedData,可获取用户openId
let pc = new WXBizDataCrypt(appid, _that.session_key);
//解密encryptedData,可获取用户openId
let data = pc.decryptData(res.detail.encryptedData, res.detail.iv);
// data.phoneNumber 就是手机号哦
}).catch((err) => {
console.log('请求失败:',err)
});
}
});
}
}
心得:
就很奇葩的问题!