小程序获取用户信息

作者: wechat 发布时间: 2022-10-12 浏览: 616 次 编辑

相信大家之前也经常使用open-data获取用户的头像和昵称吧,但微信2022年2月21日起就不能用了,这个改编意味着我们要使用新的方法获取信息了。在讨论区引发了很大的讨论,接下来我们一起尝试获取信息的方法。

第一种使用 getUserProfile

我们可以查看一下官方文档 wx.getUserProfile(Object object),获取用户信息。页面产生点击事件(例如 button 上 bindtap 的回调中)后才可调用,每次请求都会弹出授权窗口,用户同意后返回 userInfo。但要注意每次都需要授权一次是不是很麻烦,我们可以将他保存在我们数据库中授权一次日后直接调用。

代码示例

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({
      desc: '用于完善会员资料', // 声明获取用户个人信息后的用途,后续会展示在弹窗中,请谨慎填写
      success: (res) => {
        this.setData({
          userInfo: res.userInfo,
          hasUserInfo: true
        })
      }
    })
  },