WeChat小程序如何获取用户的个人信息(头像、昵称、性别与地区)?

随着WeChat小程序新规范的发布,获取用户个人信息需使用wx.getUserProfile接口。本文介绍了如何通过在UI中添加button并绑定getUserProfile方法,以及在小程序后端实现该功能,以获取用户的头像、昵称、性别和地区。

由于WeChat小程序发布了新的规范,获取用户的个人信息将使用新的方法。

“2021年4月13日后发布的新版本小程序,开发者通过组件调用wx.getUserInfo将不再弹出弹窗,直接返回匿名的用户个人信息,获取加密后的openID、unionID数据的能力不做调整;若开发者需要获取用户的个人信息(头像、昵称、性别与地区),可以通过wx.getUserProfile接口进行获取。具体参考公告:https://developers.weixin.qq.com/community/develop/doc/000cacfa20ce88df04cb468bc52801

如何做?

  • 在小程序的UI(.wxml文件)添加一个button(代码如下),让用户授权后才能获得用户的个人信息;这个button绑定了一个方法:getUserProfile,这个方法是我们自定义。
<button bindtap="getUserProfile">获取头像昵称...</button>
  • 在小程序的后端(.js文件)添加 getUserProfile 方法。
  // 获取头像昵称...
  getUserProfile(e) {
    // 推荐使用wx.getUserProfile获取用户信息,开发者每次通过该接口获取用户个人信息均需用户确认
    // 开发者妥善保管用户快速填写的头像昵称,避免重复弹窗
    wx.getUserProfile({
      desc: '用于完善会员资料', // 声明获取用户个人信息后的用途,后续会展示在弹窗中,请谨慎填写
      success: (res) => {
        console.log(res.userInfo);
        app.globalData.wxUserProfile.avatarUrl = res.userInfo.avatarUrl;
        app.globalData.wxUserProfile.city = res.userInfo.city;
        app.globalData.wxUserProfile.country = res.userInfo.country;
        app.globalData.wxUserProfile.gender = res.userInfo.gender;
        app.globalData.wxUserProfile.language = res.userInfo.language;
        app.globalData.wxUserProfile.nickName = res.userInfo.nickName;
        app.globalData.wxUserProfile.province = res.userInfo.province;
      }
    })
  }

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值