微信小程序登录及授权获取手机号

一、遇到的问题
1、获取手机号授权时报错:getPhoneNumber:fail no permission

原因是公众号没有进行企业认证

2、流程
1)登录拿session并保存

    var that = this
    wx.login({
      success: async function (res) {
        const res2 = await loginStart({
          method: "POST",
          query: {
            code:res.code
          },
          headerType: "application/json",
        });
        var sessions = res2.datas.sessionKey
        that.setData({
          sessionkey:sessions
        })
      }})

2)授权拿手机号

  
  async getPhoneNumber(e){
    var phone = this.decryptData(this.data.sessionkey,e.detail.encryptedData,e.detail.iv)
    // 用获取的手机号来进行其他操作
    const res2 = await loginGet({
      method: "get",
      suffix:'?phone='+phone.phoneNumber,
      query: {},
      headerType: "application/json",
    });

    this.setData({
      position:res2.datas. position,
      shopAddr:res2.datas.shopAddr,
      shopName:res2.datas.shopName,
      userId:res2.datas.userId,
      userName:res2.datas.userName
    })
    
  },

3)解码

import CryptoJS from 'crypto-js'
import {Base64} from 'js-base64'

  decryptData(sessionKey, encryptedData, iv) {
    let key = CryptoJS.enc.Base64.parse(sessionKey)
    let ivv = CryptoJS.enc.Base64.parse(iv)
    let decrypt = CryptoJS.AES.decrypt(encryptedData, key,  {
      iv: ivv,
      mode: CryptoJS.mode.CBC,
      padding: CryptoJS.pad.Pkcs7
    })
    return JSON.parse(Base64.decode(CryptoJS.enc.Base64.stringify(decrypt)))
  },
用到的两个包引入
在终端里安装:
npm install crypto-js
npm install js-base64
另外,也可以把参数传给后端解析(sessionKey, encryptedData, iv))

你可能感兴趣的:(小程序,登录,微信小程序,小程序,登录,获取手机号)