小程序登录获取手机号

在登录页面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思密达

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值