wx.getUserProfile兼容getUserInfo获取用户信息
发布于 3 年前 作者 fhao 2372 次浏览 来自 分享

微信小程序官方于2021年4月13日上线变更getUserInfo接口,该接口不能再获取到用户的头像昵称城市性别信息,需要改造现有项目。

<button wx:if="{{!canIUseGetUserProfile}}" open-type="getUserInfo" bindgetuserinfo="onGetUserInfo"></button>
<button wx:else bindtap="getUserProfile"></button>

Page({
  data: {
    canIUseGetUserProfile: false,
  },
  onLoad: function(options) {
    if (wx.getUserProfile) {
      this.setData({
        canIUseGetUserProfile: true
      })
    }
  },
  onGetUserInfo(e){
    if(e.detail && e.detail.iv){
      let { encryptedData, iv, userInfo } = e.detail
      let userProfile = { encryptedData, iv, userInfo }
      this.updateUserInfo(userProfile)
    }
  },
  getUserProfile(e) {
    // 推荐使用wx.getUserProfile获取用户信息,开发者每次通过该接口获取用户个人信息均需用户确认
    // 开发者妥善保管用户快速填写的头像昵称,避免重复弹窗
    wx.getUserProfile({
      desc: '用于完善会员资料', // 声明获取用户个人信息后的用途,后续会展示在弹窗中,请谨慎填写
      success: (res) => {
        console.log(res)
        let { encryptedData, iv, userInfo } = res
        if (!iv || !encryptedData) {
          console.warn('微信基础库低于2.16.0,wx.getUserProfile获取不到encryptedData和iv等字段')
          iv = ''
          encryptedData = ''
        }
        let userProfile = { encryptedData, iv, userInfo }
        this.updateUserInfo(userProfile)
      }
    })
  },
  updateUserInfo(userProfile) {
    console.log(userProfile)
    // 请求接口保存用户信息
  },
})
回到顶部