最详细的小程序用户授权教程

一、获取用户授权设置
开发者可以在小程序启动时,使用 wx.getSetting 获取用户当前的授权状态。

// 获取用户信息
    wx.getSetting({
      success: res => {
      console.log(res)
      //如果用户已授权则res.authSetting['scope.userInfo']为true,否则为false。
        if (res.authSetting['scope.userInfo']) {
          // 只有当用户已经授权,才能调用wx.getUserInfo获取头像昵称,不会弹框
          wx.getUserInfo({
            success: res => {
              // 可以将 res 发送给后台解码出 unionId
              this.globalData.userInfo = res.userInfo
              console.log(res.userInfo);
              // 由于 getUserInfo 是网络请求,可能会在 Page.onLoad 之后才返回
              // 所以此处加入 callback 以防止这种情况
              if (this.userInfoReadyCallback) {
                this.userInfoReadyCallback(res)
              }
            }
          })
        }
      }
    })

二、弹出授权框开发版和体验版都不支持使用wx.getUserInfo调用弹窗,官方提供以下两种情况可供参考:
1、使用button组件,使用其open-type属性
官方文档———》组件——》表单组件——》button

<view class="z-index mgb-15">
  <button open-type="getUserInfo" bindgetuserinfo="getUserInfo" class="sqBtn" wx:if="{{showSQBtn}}">授权</button>
  <button bindtap="login">立即登录<button>
  </view>
  // 授权
  getUserInfo(res) {
    console.log(res);
    //用户同意授权
    if (res.detail.errMsg === 'getUserInfo:ok') {
      let userInfo = res.detail.userInfo;
      this.setData({
        showSQBtn: false
      })
      getApp().globalData.userInfo = userInfo;
    } else {
    //用户不同意授权
      this.setData({
        showSQBtn: true
      })
    }
  }

2、也可以不使用wx.getUserInfo来获取用户的信息,即用户在没有授权的情况下,也可以获取用户信息,但获取到的信息只包含用户的基本信息,如:用户头像、昵称、性别、所在地等
官方文档——》组件——》开放能力——》open-data

<open-data type="userAvatarUrl"></open-data>   //获取用户头像
<open-data type="userNickName"></open-data>   //获取用户昵称
<open-data type="userGender" lang="zh_CN"></open-data>  //获取用户性别
  • 1
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值