微信小程序之受权 wx.authorize

1、 wx.authorize(Object object)

提早向用户发起受权请求。调用后会马上弹窗询问用户是否赞成受权小程序使用某项功能或获取用户的某些数据,但不会实际调用对应接口。若是用户以前已经赞成受权,则不会出现弹窗,直接返回成功。html

  • 用户能够受权的
    scope 包括:
scope 对应接口 描述
scope.userInfo wx.getUserInfo 用户信息
scope.userLocation wx.getLocation, wx.chooseLocation, wx.openLocation 地理位置
scope.address wx.chooseAddress 通信地址
scope.invoiceTitle wx.chooseInvoiceTitle 发票抬头
scope.invoice wx.chooseInvoice 获取发票
scope.werun wx.getWeRunData 微信运动步数
scope.record wx.startRecord 录音功能
scope.writePhotosAlbum wx.saveImageToPhotosAlbum, wx.saveVideoToPhotosAlbum 保存到相册
scope.camera 组件 摄像头

注意:上述接口中,wx.authorize({scope: "scope.userInfo"}),没法弹出受权窗口,使用 button 组件,并将 open-type 指定为 getUserInfo 类型,获取用户基本信息。https://developers.weixin.qq.com/community/develop/doc/0000a26e1aca6012e896a517556c01小程序

2、 wx.authorize 用法

wx.getSetting({
  success (res) {
    console.log(res.authSetting)
  }
})

若是用户已经受权过 地理位置,上面代码则会返回:"scope.userInfo": trueapi

  • 向用户发起受权请求
// 能够经过 wx.getSetting 先查询一下用户是否受权了 "scope.record" 这个 scope

wx.getSetting({
  success(res) {
    if (!res.authSetting['scope.record']) {
      wx.authorize({
        scope: 'scope.record',
        success () {
          // 用户已经赞成小程序使用录音功能,后续调用 wx.startRecord 接口不会弹窗询问
          wx.startRecord()
        }
      })
    }
  }
})

3、 注意

  • 微信中使用 wx.getUserInfo 接口直接弹出受权框的开发方式将逐步再也不支持。
  • 因此在用户未受权的状况下,在 onload 函数中使用 wx.getUserInfo 是默认失败的, 以下:
onLoad: function (options) { 
    // 只有在用户已经受权后,才能在 onload 函数中获取到用户信息
    // 因此,下面经过 wx.getSetting 检查用户是否已经受权,
    // 若是没有受权,则中止执行
    // 若是已经受权,则继续执行success 
    wx.getSetting({
      success (res){
        if (res.authSetting['scope.userInfo']) {
          // 已经受权,能够直接调用 getUserInfo 获取头像昵称
          wx.getUserInfo({
            success: function(res) { 
              console.log(res.userInfo)
            }
          })
        }
      }
    })
},
  • 建议使用 button 组件,并将 open-type 指定为 getUserInfo 类型,经过点击事件获取用户基本信息。微信

  • 代码以下:ide

wxml:函数

<button open-type="getUserInfo" bindgetuserinfo='getUser'>获取用户信息(受权登陆)</button>

js:this

getUser(e) { 
    console.log(e)
    wx.getUserInfo({
        success: (res) => {
            console.log(res)
            this.setData({
                userInfo: res.userInfo
            });
        }
    })
}
相关文章
相关标签/搜索