[WeChat applet] Permission interface combing and code implementation

1. Permission interface description

The official permissions indicate that
  some interfaces need to be authorized by the user before they can be called. We divide these interfaces into multiple scopes according to the scope of use. The user chooses to authorize the scope. After authorizing a scope, all the corresponding interfaces can be used directly.

When this type of interface is called:

  • If the user has not accepted or rejected this permission, a pop-up window will pop up to ask the user, and the user can only call the interface after clicking agree;
  • If the user is authorized, the interface can be called directly;
  • If the user has rejected the authorization, no pop-up window will appear, but directly enter the interface fail callback. Developers are required to be compatible with scenarios where users refuse authorization.

Get User Authorization Settings
Developers can use wx.getSetting to get the user's current authorization status.

Open the setting interface
The user can control the authorization status of the applet in the applet setting interface ("upper right corner" - "about" - "upper right corner" - "settings").

Developers can call wx.openSetting to open the setting interface and guide users to enable authorization.

Initiating authorization requests in advance
Developers can use wx.authorize to initiate authorization requests to users in advance before calling APIs that require authorization.

scope list
scope Corresponding interface description scope.userInfo wx.getUserInfo User information scope.userLocation wx.getLocation Geographic location scope.werun wx.getWeRunData Wechat exercise steps scope.writePhotosAlbum wx.saveImageToPhotosAlbum Save to album scope.WxFriendInteraction Corresponds to wx.getFriendCloudStorage in the open data domain , wx.getGroupCloudStorage , wx.getGroupInfo , wx.getPotentialFriendList , wx.getUserCloudStorageKeys , wx.getUserInfo , GameServerManager.getFriendsStateData interface, and wx.getUserInteractiveStorage interface in the main domain.  Whether to authorize the use of your WeChat friend information

Validity period of authorization
Once the user explicitly agrees or rejects the authorization, the authorization relationship will be recorded in the background until the user actively deletes the applet.

Best practice
When really needing to use the authorization interface, initiate an authorization application to the user, and clearly explain the reason for using this function in the authorization application.

Precautions
wx.authorize({scope: “scope.userInfo”}), the authorization window will not pop up, please use wx.createUserInfoButton
when you need to authorize scope.userLocation, you must configure the geographic location usage description.

2. Introduction to the specific authority interface

2.1 wx.authorize()

Official description wx.authorizeinsert image description here
insert image description here
insert image description here

2.2 wx.openSetting()

Official description wx.openSetting()
insert image description here
insert image description here
insert image description here
insert image description here

3. How to apply for permission

  • Obtain the corresponding permissions and information through the open-type method of the button.
  • Apply for the corresponding permissions through the two interfaces of wx.authorize() and wx.openSetting().
    Special attention is: when you need to authorize scope.userLocation and scope.userLocationBackground, you must configure the geographical location usage description

Apply for permission through button

It is relatively simple for developers to obtain permissions through buttons. Developers only need to bind the corresponding callback function. The success or failure of permission application can be handled in the callback function.
In fact, we can regard the method of applying for permission through the button as a common information acquisition interface, but this interface must be called through the button component.

Apply for permission through wx.authorize()

It is cumbersome to apply for permission through wx.authorize(). Because it has many states, it can be roughly divided into:

  • If the user has not accepted or rejected this permission, a pop-up window will pop up to ask the user, and the user can only call the interface after clicking agree;
  • If the user is authorized, the interface can be called directly;
  • If the user has rejected the authorization, no pop-up window will appear, but directly enter the interface fail callback. Developers are required to be compatible with scenarios where users refuse authorization

For these three states, developers handle them differently.

  • If the user has not accepted or rejected this permission, a pop-up window will pop up to ask the user, and the user clicks to agree—the corresponding interface can be called.

  • If the user has not accepted or rejected this permission, a pop-up window will pop up to ask the user, and the user clicks Deny to open the settings page.

  • If the user is authorized - the corresponding interface can be called.

  • User has denied authorization - Opens the settings page.

    2/4 of the above situations require developers to combine wx.openSetting() to help users perform secondary authorization.
    It is this openSetting process of opening the settings page that makes developers crazy.
    Starting from version 2.3.0, the user can jump to open the settings page only after the user clicks.
    That is to say, openSetting can only be called through the callback function of button component and click (bindtap).
    However, when we apply for permission, we cannot guarantee that the user will agree to it when applying for the first time, so it must be used in conjunction with openSetting.
    Then it is not awkward for us to add a button in every place where openSetting is called.
    At present, our best solution is to combine wx.authorize() and wx.openSetting() and put them in a bindtap/catchtap (or other gesture event) callback function.
    Next, we will focus on integrating the permission processing in this way.

4. Permission application integration code

4.1 Reference tool class code

The following is the integrated tool class code, which we temporarily named authorizer.js, which can be copied and used directly.


const authsName = {
    
    
  "scope.userInfo": "用户信息",// 请用button获取该信息
  "scope.userLocation": "地理位置",
  "scope.userLocationBackground": "后台定位",
  "scope.address": "通讯地址",
  "scope.invoiceTitle": "发票抬头",
  "scope.invoice": "获取发票",
  "scope.werun": "微信运动步数",
  "scope.record": "录音功能",
  "scope.writePhotosAlbum": "保存到相册",
  "scope.camera": "摄像头",
}


var scope = null;
var success = null;
var fail = null;
var denyBack = null;
var deniedFun = null;

/**
 * 申请某个权限
 * _scope 权限名称
 * _success 成功回调
 * _fail 失败回调
 * _denyBack 申请权限时用户 拒绝 后的回调
 * _deniedFun 之前申请过该权限但被拒绝了,该情况下调用此函数
 */
function authorize(_scope, _success, _fail, _denyBack, _deniedFun) {
    
    

  resetData();

  scope = _scope;
  success = _success;
  fail = _fail;
  denyBack = _denyBack;
  deniedFun = _deniedFun;

  if (!scope) {
    
    
    return;
  }

  // 判断权限状态
  wx.getSetting({
    
    

    success: function(res) {
    
    

      let currentScope = res.authSetting[scope];

      if (currentScope == undefined || currentScope == null) {
    
    

        // 之前没有申请或该权限
        wx.authorize({
    
    
          scope: scope,
          success: function(res) {
    
    

            authSuccess(res);
          },

          fail: function(err) {
    
    

            authDeny();
          }
        });

      } else if (currentScope == false) {
    
    

        // 之前申请过该权限但被拒绝了, 如果配置 deniedFun 函数,则有执行 deniedFun 方法,
        // 由调用者决定改中情况下如何处理。
        if (authDenied()) {
    
    
          return;
        }

        // 如果没有配置 deniedFun 函数,走默认逻辑,打开设置界面
        wx.showModal({
    
    
          title: '权限申请',
          content: '点击 “确定” 按钮,打开 “' + authsName[scope] + '” 的权限设置界面',
          cancelText: '取消',
          confirmText: '确定',
          success(res) {
    
    
            if (res.confirm) {
    
    

              wx.openSetting({
    
    
                success: function(res) {
    
    

                  let cScope = res.authSetting[scope];
                  if (cScope) {
    
    

                    authSuccess();
                  } else {
    
    

                    authFail();
                  }
                },

                fail: function(res) {
    
    

                  authFail();
                }
              });
            }
          }
        });

      } else {
    
    

        // 已经获得该权限
        authSuccess();
      }
    },

    fail: function() {
    
    

      authFail();
    }
  });
}



/**
 * 权限申请成功
 */
function authSuccess(res) {
    
    

  if (success && typeof success == 'function') {
    
    
    success(res);
  }

  resetData();
}

/**
 * 权限申请失败
 */
function authFail() {
    
    

  if (fail && typeof fail == 'function') {
    
    
    fail();
  }

  resetData();
}

/**
 * 拒绝使用该权限
 */
function authDeny() {
    
    

  if (denyBack && typeof denyBack == 'function') {
    
    
    denyBack();
  }

  resetData();
}


/**
 * 之前申请过该权限但被拒绝了
 */
function authDenied() {
    
    

  if (deniedFun && typeof deniedFun == 'function') {
    
    
    deniedFun();
    resetData();
    return true;
  } else {
    
    
    return false;
  }
}

/**
 * 重置参数
 */
function resetData() {
    
    

  scope = null;
  success = null;
  fail = null;
  denyBack = null;
  deniedFun = null;
}


module.exports = {
    
    
  authorize: authorize,
}

The wxml code of the tool class
:

 <view bindtap="authApply">权限申请</view>

js code:

/**
 * 权限申请--微信步数
 */
authApply(e) {
    
    
  authorizer.authorize("scope.werun", function(res) {
    
    
    console.log('success', res);
    wx.getWeRunData({
    
    success: function(res){
    
    
      console.log('WeRunData', res)
    }});
  }, function(err) {
    
    
    console.log('denyback', err);
  }, function(err) {
    
    
    console.log('deniedBack', err);
  });
},

4.2 Actual code implementation

data:{
    
    
authScope:"scope.werun",//要申请的权限
    },
  /**
   * 申请权限
   * _scope 权限名称
   * _authSuccess 成功回调
   * _authFail 失败回调
   * _authDeny 申请权限时用户 拒绝 后的回调
   * _authDenied 之前申请过该权限但被拒绝了,该情况下调用此函数
   */

 //授权成功
  authSuccess(){
    
    
      let that = this
      console.log("授权成功")
      that.setData({
    
    
          hasWerun:true
      })
      that.getUserRun()
  },

  //授权失败
  authFail(){
    
    
      console.log("授权失败")
      wx.showToast({
    
    
          title: '授权失败',
          icon: 'none',
          duration: 1000
      })
  },
  //拒绝授权
authDeny(){
    
    
      console.log("authorize调用失败,引导重新吊起")
      wx.showToast({
    
    
          title: '您未授权微信运动 请点击右上角设置 进入列表手动授权',
          icon: 'none',
          duration: 3000
      })
  }, 
  //已被拒绝授权过的权限,重新吊起
authDenied(){
    
    
      console.log("currentScope == false 已被拒绝授权过的权限,引导重新吊起")
      wx.showToast({
    
    
          title: '您未授权微信运动 请点击右上角设置 进入列表重新授权',
          icon: 'none',
          duration: 3000
      })
  },

  authApply:function(){
    
    
      let that = this
      let scope = that.data.authScope
      if (!scope) {
    
    
        return;
      }
      // 判断权限状态
      wx.getSetting({
    
    
        success: function(res) {
    
    
          console.log("当前权限列表")
          console.log(res)
          let currentScope = res.authSetting[scope];
          if (currentScope == undefined || currentScope == null) {
    
    
            // 之前没有申请或该权限
            console.log("之前没有申请或该权限")
            wx.authorize({
    
    
              scope: scope,
              success: function() {
    
    
                that.authSuccess();
              },
              fail: function(err) {
    
    
                that.authDeny();
              }
            });
          } else if (currentScope == false) {
    
    
            // 之前申请过该权限但被拒绝了
              that.authDenied()
              return;
          } else {
    
    
            // 已经获得该权限
            that.authSuccess();
          }
        },
        fail: function() {
    
    
          that.authFail();
        }
      });
  },
  //设置按钮绑定权限列表  
  getOpenSetting: function () {
    
    
      let that = this
      wx.openSetting({
    
    
      success(res) {
    
    
          if (res.authSetting[that.data.authScope]) {
    
    
          // 用户在设置页面开启权限后,重新授权成功
          // 可以调用相应的 API 接口
          that.setData({
    
    
              hasWerun:true
          })
          console.log("openSetting已获取到授权")
          that.authSuccess()
          } else {
    
    
          // 用户在设置页面未开启权限,授权失败
          that.authFail()
          }
      },
      fail() {
    
    
          console.log("openSetting拉起失败")
          // 调用 wx.openSetting 接口失败
          that.authFail()
      }
      })
  }, 

wxml

 <text class="info-text" bindtap="getOpenSetting">权限</text>

Summarize

There are two ways to apply for the permission of the WeChat applet;
analyze several situations that occur in this way of wx.authorize and the corresponding processing;
sort out a general method used by wx.authorize, and this method must be in a gesture In the callback function of the event.

Guess you like

Origin blog.csdn.net/qq_40421671/article/details/130249620