探秘小程序,4:授权

1.场景:某些微信的api(比如获取用户信息,全部权限请参看文章结尾)需要获得用户权限才可查询,因此就需要有授权。

2.主要内容:授权相关api只有三个:

  ①wx.getSetting:

  作用:获取用户已经授权权限

  示例:

 1  wx.getSetting({//获取系统设置过的权限
 2       success: (res) => {
 3        console.info('getSetting suc',res);
 4       /*
 5       * res.authSetting = {
 6       *   "scope.userInfo": true,
 7       *   "scope.userLocation": true
 8       * }
 9       */
10       },
11       fail: (res)=>{
12         console.info('getSetting fail', res);
13       }
14     })

  ② wx.openSetting

  作用:打开设置界面,引导用户开启授权。

  示例:

 1   wx.openSetting({//调起客户端小程序设置界面,返回用户设置的操作结果。
 2       success: (res) => {
 3         /*
 4          * res.authSetting = {
 5          *   "scope.userInfo": true,
 6          *   "scope.userLocation": true
 7          * }
 8          */
 9         console.info('openSetting Suc', res);
10       },
11       fail: (res) => {
12         console.info('openSetting fail', res);
13       }
14     })

  ③wx.authorize

  作用:在调用需授权api前,提前请求用户授权

  示例:

 1   wx.getSetting({
 2       success(res){
 3         if(!res.authSetting['scope.record']){
 4           wx.authorize({
 5             scope: 'scope.record',
 6             success(){
 7               wx.startRecord();
 8             }
 9           })
10         }
11       }
12     })

3.相关需授权api:

scope对应接口描述
scope.userInfo【废弃】wx.getUserInfo用户信息
scope.userLocationwx.getLocation, wx.chooseLocation地理位置
scope.addresswx.chooseAddress通讯地址
scope.invoiceTitlewx.chooseInvoiceTitle发票抬头
scope.werunwx.getWeRunData微信运动步数
scope.recordwx.startRecord录音功能
scope.writePhotosAlbumwx.saveImageToPhotosAlbum, wx.saveVideoToPhotosAlbum保存到相册
scope.camera摄像头

4.详情请参考官方文档:https://developers.weixin.qq.com/miniprogram/dev/api/authorize.html