微信小程序-最新获取用户基本信息方案

如果只是单纯的展示用户信息,那么最简单的方案就是

文档中组件:

<open-data type="groupName" open-gid="xxxxxx"></open-data>
<open-data type="userAvatarUrl"></open-data>
<open-data type="userGender" lang="zh_CN"></open-data>

 如果是需要将用户信息通过接口传递到后台,那么需要强制授权:

小程序目前在测试版和体验版限制通过wx.getUserInfo({})获取弹出授权框。

支持通过按钮点击获取授权的方式:

//注意:wx.authorize({scope: "scope.userInfo"}),无法弹出授权窗口
<button open-type="getUserInfo" bindgetuserinfo="getUserInfo"> 获取头像昵称 </button>

小程序目前不支持,打开时就弹出授权窗,只能使用按钮触发,按钮触发授权方案:

//此处时拒绝授权的警告窗口,如果用户点击拒绝,则会弹出这个窗口,确定按钮再次绑定授权弹窗事件。
<view class="authorize-warning" hidden="{{!isShowAhturoizeWarning}}">
    <view class="box">
      <view class="title">警告</view>
      <view class="content">拒绝授权后,将无法通知您。。。。。点击“取消”拒绝提醒,点击“确定”再次尝试授权?</view>
      <view class="footer">
        <button bindtap="cancelAuthroize">取消</button>
        <button open-type="getUserInfo" bindgetuserinfo="getAuthorize">确定</button>
      </view>
    </view>
  </view> 
 getUserInfo(){//同意授权,获取用户信息,encryptedData是加密字符串,里面包含unionid和openid信息
    wx.getUserInfo({
      withCredentials: true,//此处设为true,才会返回encryptedData等敏感信息
      success: res => {
        // 可以将 res 发送给后台解码出 unionId
        app.globalData.userInfo = res.userInfo;
        app.globalData.encryptedData = res.encryptedData;
        app.globalData.iv = res.iv;
        this.saveUserInfo();
        console.log(res)
      }
    })
  },
getAuthorize(){//弹出授权窗函数
    if(this.data.acceptAuthorize) {//判断是否已经授权过
      // 获取用户信息
      wx.getSetting({
        success: res => {
          if (res.authSetting['scope.userInfo']) {
            // 已经授权,可以直接调用 getUserInfo 获取头像昵称,不会弹框
            this.getUserInfo();
            this.setData({
              isShowAhturoizeWarning: false
            })
          } else {
            this.setData({
              isShowAhturoizeWarning:true
            })
          }
        }
      })
    } else {//如果已经授权过直接登录
      this.saveUserInfo()
    },
  cancelAuthroize(){
    this.setData({
      isShowAhturoizeWarning: false,
      acceptAuthorize:false
    });
    app.globalData.unionid=null;
    this.saveUserInfo();
    
  }
原文地址:https://www.cnblogs.com/HappyYawen/p/9047420.html