Best practices for user authorization of wechat applets

Development WeChat small program, often used for some user permissions page, for example, if you want to login, is about to get personal information, face recognition, you need to do is get the camera permissions, location map function, you need to do to get the position of the user permissions, you want to save images in the user’s photo album, need to get photo album permissions, and so on

Wechat scope process:

Most functions are not available without authorization. Generally, I will check whether the permission is enabled, and then continue to use it if it is enabled, and continue to request authorization if it is not enabled. If still refuse to give a prompt and then ask the user to go to the Settings page manually open…

Normal logic

But the set might look something like this when written down:

wx.getSetting({
    success(res)=>{
        if(! res.authSetting['scope']) {
          console.log('Unauthorized')
              wx.authorize({
                scope: 'scope'.success() {
                    console.log('Authorization successful')},fail() {
                    console.log('Authorization failed, let user manually authorize')
                    wx.showModal({
                        title: 'Warm reminder'.content: 'XXX permission not enabled'.showCancel: false.success(res) {
                        if (res.confirm) {
                            console.log('User hits OK')
                            wx.openSetting({
                                success(res) {
                                    console.log(res.authSetting)
                                    res.authSetting = {
                                    "scope.camera": true,}}})}else if (res.cancel) {
                            console.log('User hit Cancel'}}})}})}else {
          console.log('Authorized')
        }
    },
    fail(err)=>{}
})
Copy the code

It’s 1202, and it’s awful to write that down, mixed with business logic

It took me some time to package a function that simply passes in the specified permission name to detect whether the user has enabled the permission. If not, it will prompt the user to manually open the Settings page (it must be opened anyway).

I wanted to write a code snippet, but later I found that the tool had problems calling openSetting, so I had to give up.

Details of the code

// utils/auth.js

/ * * *@param {* authType: Authorization type *}* /

module.exports = async function wxAuth(authType) {
  // scopeArr ref: https://developers.weixin.qq.com/miniprogram/dev/framework/open-ability/authorize.html
  let scopeArr = [
    "userInfo"."userLocation"."userLocationBackground"."address"."invoiceTitle"."invoice"."werun"."record"."writePhotosAlbum"."camera",];if (scopeArr.indexOf(authType) == -1) {
    return console.error("Please enter the correct authorization type");
  }
  let scope = "scope." + authType;
  let isUserSet = await getSettingSync(scope);
  if (isUserSet) return true;
  let isAuthorize = await authorizeSync(scope);
  if (isAuthorize) return true;
  let showModalMes = await showModalSync(scope);
  // The dialog box prompts you to authorize
  if (showModalMes) {
    // Go to manual authorization
    let openSet = await openSettingSync(scope);
    if (openSet) {
      return true;
    } else {
      return false; }}else {
    // Deny authorization
    return false; }};// Check whether the user is authorized
function getSettingSync(scope) {
  return new Promise((resolve, reject) = > {
    wx.getSetting({
      success(res) {
        if(! res.authSetting[scope]) {console.log("Not authorized");
          resolve(false);
        } else {
          console.log("Authorized");
          resolve(true); }},fail(err) {
        reject();
        console.error("wx.getSetting Error", err); }}); }); }// Request user authorization
function authorizeSync(scope) {
  return new Promise((resolve, reject) = > {
    wx.authorize({
      scope: scope,
      success() {
        resolve(true);
        console.log("Authorization successful");
      },
      fail() {
        resolve(false);
        console.log("Authorization failed"); }}); }); }// A dialog box is displayed asking you to authorize users manually
function showModalSync(scope) {
  return new Promise((resolve, reject) = > {
    wx.showModal({
      title: "Tip".content: 'For better user experience, please authorize${scope}Function `.confirmText: "De-authorize".showCancel: false.success(res) {
        if (res.confirm) {
          console.log("Click OK");
          resolve(true);
        } else if (res.cancel) {
          resolve(false); }},fail(err) {
        reject();
        console.error(err, "wx.showModal Error"); }}); }); }// Bring up the client applet setting interface and return the operation result set by the user
function openSettingSync(scope) {
  return new Promise((resolve, reject) = > {
    wx.openSetting({
      success(res) {
        console.log(res.authSetting);
        if (res.authSetting[scope]) {
          resolve(true);
        } else {
          resolve(false); }},fail(err) {
        reject();
        console.error(err, "wx.openSetting Error"); }}); }); }Copy the code

use

JS code reference:

import auth from '. /.. /.. /utils/auth'
Page({
   data: {isCameraAuth: false
   },
   onLoad(){
         // Authorization code
    auth('camera').then(() = > {
      console.log('Authorization successful')
      this.setData({
        isCameraAuth: true
      }
    }).catch((err) = > {
      console.error('Authorization failed'); })}})Copy the code

WXML code reference:

<! -- index.wxml -->
<view>Authorized: {{isCameraAuth}}</view>
<camera wx:if="{{isCameraAuth}}" style="width: 100%; height: 300px;"></camera>
Copy the code

preview

To do this, I made a Demo and clicked Demo Preview to open the preview directly in the development tools.

Original from Ninety: links to original blog posts