小程序 授权

小程序 授权

授权的原因:部分功能需要用户同意后才能使用。

哪些接口需要用户同意呢,需要查看scope列表中的对应关系

scope 列表

scope对应接口描述
scope.userInfo wx.getUserInfo 用户信息
scope.userLocation wx.getLocation, wx.chooseLocation 地理位置
scope.userLocationBackground wx.startLocationUpdateBackground 后台定位
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 camera 组件 摄像头

第一步

wx.getSetting来判断该用户有没有对接口授权,查看哪个接口,就需要wx.getSetting返回值,authsetting的scope值判断,一个scope值对应着一个或多个接口。

wx.getSetting({
  success (res) {
    console.log(res.authSetting) //authSetting是用户授权结果
   }
})

第二步

如果我们从wx.getSetting中发现scope值是false,标识没有授权,我们可以通过wx.authorize吊起对应授权弹框,对那个接口授权,就给wx.authorize传对应scope值。如果authsetting中的scope为true,表示该用户已经对该接口授权,我们就可以直接使用对应的接口了。

// 可以通过 wx.getSetting 先查询一下用户是否授权了 "scope.record" 这个 scope
wx.getSetting({
  success(res) {
    if (!res.authSetting['scope.record']) {
      wx.authorize({
        scope: 'scope.record',
        success () {
          // 用户已经同意小程序使用录音功能,后续调用 wx.startRecord 接口不会弹窗询问
          wx.startRecord()
        }
      })
    }else{
    // consolo.log('已经授权')
    wx.startRecord()
   } } })

注意:

但是scope.userInfo没有办法使用wx.authorize直接吊起授权弹框。必须要用户手动点击按钮唤起授权弹框。

代码格式:

<button open-type="getUserInfo" bindgetuserinfo="user">用户信息</button>

我们可以再响应函数的参数中获取用户信息。e.detail,这个和直接调用wx.getUserInfo获取的内容一样。

  user:function(e){
    // console.log("e",e.detail)
    wx.getSetting({
      success(res) {
        if (res.authSetting['scope.userInfo']) {
          console.log('已经授权')
          wx.getUserInfo({
            success: (res) => {
              console.log("res",res)
            },
          })
        } else {
        }
      }
    })  
  }

补充: bindgetuerinfo官方文档解释

原文地址:https://www.cnblogs.com/baohanblog/p/12484384.html