【BUG】使用uni-app开发微信小程序,获取用户信息&手机号时需要点击两次才能成功

问题描述:

使用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)
					});
				}
				});
			}

}

心得:

就很奇葩的问题!

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值