微信小程序getUserProfile获取虚假用户信息问题及解决请求
微信小程序用户信息获取问题
问题背景
首次开发微信小程序,尝试将westore示例项目中的getUserProfile移植到weapp-weather项目中,调用以下代码后仅获取到虚假用户信息(头像和昵称均为API默认值):
wx.getUserProfile({ desc: '展示用户信息', success: (res) => { console.log('u.js getUserProfile success', this, res) this.userInfo = res.userInfo this.options.onUserInfoLoaded && this.options.onUserInfoLoaded() } })
对应的WXML代码:
<view class="userinfo"> <block wx:if="{{!userInfo.nickName}}"> <button bindtap="getUserProfile">获取头像昵称</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>
另外有一段代码可以正常获取真实用户信息,但不清楚其流程:
WXML:
<text class="title">hello {{name}}</text> <button open-type="getUserInfo" bind:getuserinfo="buttonHandler"> 授权获取个人信息 </button>
JS:
buttonHandler(event) { if (!event.detail.userInfo) return; this.setData({ name: event.detail.userInfo.nickName }); }
解决方案
1. 修正getUserProfile获取虚假信息的问题
微信小程序已调整用户信息获取规则:wx.getUserProfile接口不再返回真实用户头像和昵称,仅返回默认灰色头像与“微信用户”昵称。要获取真实用户信息,需使用头像昵称填写能力,调整代码如下:
- 修改WXML:
<view class="userinfo"> <block wx:if="{{!userInfo.nickName}}"> <button open-type="chooseAvatar" bind:chooseavatar="onChooseAvatar">选择头像</button> <input type="nickname" placeholder="请输入昵称" bindblur="onNicknameInput" /> </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>
- 补充JS逻辑:
// 选择头像回调 onChooseAvatar(e) { const { avatarUrl } = e.detail; this.setData({ 'userInfo.avatarUrl': avatarUrl }); } // 昵称输入回调 onNicknameInput(e) { const nickname = e.detail.value; this.setData({ 'userInfo.nickName': nickname }); this.options.onUserInfoLoaded && this.options.onUserInfoLoaded(); }
这种方式让用户主动上传头像、输入昵称,完全符合当前微信隐私规范。
2. 有效代码的工作原理
这段代码是微信小程序旧版用户信息授权方案,核心逻辑:
- WXML部分:按钮通过
open-type="getUserInfo"声明为用户信息授权按钮,bind:getuserinfo绑定授权完成后的回调函数。 - JS部分:用户点击按钮并同意授权后,微信会将用户信息封装在
event.detail.userInfo中返回;buttonHandler先判断是否获取到有效信息,若成功则通过setData更新页面数据,完成渲染。
注意:该方案属于旧版接口,微信官方已不再推荐使用,仅部分旧版本基础库兼容。
内容的提问来源于stack exchange,提问作者xpt
相关产品推荐
相关产品推荐

