在登录页面onload先进行wx.login获取code。(重要,不要点击按钮时获取,会发生解密手机号失败,原因为sessionKey过期或者不一致导致解密失败)
流程为:在onload获取code以及sessionkey(重要),点击获取按钮时,先判断sessionkey有没有过期,如果过期,则需要重新获取code
以下为代码实现
<button open-type="getPhoneNumber" lang="zh_CN" @getphonenumber="bingGetPhoneNumber">微信用户一键登录</button>
onLoad(){
this.getWxLogin()
},
async getWxLogin(){
wx.showLoading({
title: '请稍后',
mask:true
})
let res=await wx.login()
//根据后台接口通过code获取openid以及sessionkey
let ress=await getRequest(`/mpBattreyMini/code/${res.code}`)
this.openid=ress.openid
this.sessionKey=ress.sessionKey
wx.hideLoading()
},
//先检测sessionkey有没有过期,如果过期则重新获取
async bingGetPhoneNumber(e){
const that=this
wx.checkSession({
success:function(){
that.handelBingGetPhoneNumber(e)
},
fail:async function(){
that.getWxLogin()
that.handelBingGetPhoneNumber(e)
}
})
},
//传后台接口参数,进行登录、获取手机号
async handelBingGetPhoneNumber(e){
let params={
ivData:e.detail.iv,
mobile:e.detail.encryptedData
}
params.openId=this.openid
params.sessionKey=this.sessionKey
let resss=await postRequest('/mpBattreyMini/login',params)
if(resss.code===0){
wx.showToast({
title: '登录成功!', // 标题
icon: 'success', // 图标类型,默认success
})
}
},
GG思密达