微信小程序更新接口wx.getUserProfile后获取用户昵称变成[微信用户]的解决方法
今天在小程序调试时,突然发现获取到的用户昵称变成“微信用户”和头像也非用户微信头像了,原因是微信小程序更新了接口wx.getUserProfile之后导致的,参考文档:微信小程序更新接口wx.getUserProfile涉及小程序登录/用户信息相关接口调整说明
原公告中提到
回收wx.getUserInfo接口可获取用户个人信息能力,4月13日后发布的新版本小程序,开发者调用wx.getUserInfo或<button open-type="getUserInfo"/>将不再弹出弹窗,直接返回匿名的用户个人信息,获取加密后的openID、unionID数据的能力不做调整,即wx.getUserInfo接口的返回参数不变。
wx.getUserProfile 接口调用方式
wx.getUserProfile 不能在onShow或者onLoad里面调用,可以在点击事件 catchtap 或者 button 的 bindtap 调用发起授权弹窗,获取用户资料。
wx.getUserProfile 示例代码
wxml 参考
<view class="container">
<view class="userinfo">
<block wx:if="{{!hasUserInfo}}">
<button wx:if="{{canIUseGetUserProfile}}" bindtap="getUserProfile"> 获取头像昵称 </button>
<button wx:else open-type="getUserInfo" bindgetuserinfo="getUserInfo"> 获取头像昵称 </button>
</block>
<block wx:else>
<image bindtap="bindViewTap" class="userinfo-avatar" src="{{userInfo.avatarUrl}}" mode="cover"></image>
<text class="userinfo-nickname">{{userInfo.nickName}}</text>
</block>
</view>
</view>
js 示例代码
Page({
data: {
userInfo: {},
hasUserInfo: false,
canIUseGetUserProfile: false,
},
onLoad() {
if (wx.getUserProfile) {
this.setData({
canIUseGetUserProfile: true
})
}
},
getUserProfile(e) {
// 推荐使用wx.getUserProfile获取用户信息,开发者每次通过该接口获取用户个人信息均需用户确认
// 开发者妥善保管用户快速填写的头像昵称,避免重复弹窗
wx.getUserProfile({
desc: '用于完善会员资料', // 声明获取用户个人信息后的用途,后续会展示在弹窗中,请谨慎填写
success: (res) => {
this.setData({
userInfo: res.userInfo,
hasUserInfo: true
})
}
})
},
getUserInfo(e) {
// 不推荐使用getUserInfo获取用户信息,预计自2021年4月13日起,getUserInfo将不再弹出弹窗,并直接返回匿名的用户个人信息
this.setData({
userInfo: e.detail.userInfo,
hasUserInfo: true
})
},
})
wx.getUserProfile 相关参考文档
微信小程序更新接口wx.getUserProfile涉及小程序登录/用户信息相关接口调整说明
微信小程序更新接口wx.getUserProfile相关解读
微信小程序更新接口wx.getUserProfile后获取用户昵称变成[微信用户]的解决方法
微信小程序更新接口wx.getUserProfile后不返回scope.userInfo权限
微信小程序更新接口wx.getUserProfile后获取用户资料及授权登陆判断的方案