WeChat Mini Program User Authorization Best Practices Guide

WeChat Mini Program User Authorization Best Practices Guide

Preface

When developing WeChat applets, you often need to use pages that require some user permissions. For example, if you want to log in, you need to obtain personal information; if you want to do face recognition, you need to obtain camera permissions; if you want to do location map functions, you need to obtain the user's location permissions; if you want to save pictures in the user's album, you need to obtain album permissions, etc.

WeChat scope process:

Most functions are unavailable without authorization. I usually check whether the permission is enabled, and if it is enabled, I will continue to use it. If it is not enabled, I will give a prompt to continue to request authorization. If it is still rejected, I will give a prompt and let the user manually go to the settings page to turn it on...

#Normal Logic

But this might look 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 the user manually authorize')
                    wx.showModal({
                        title: 'Warm Tips',
                        content: 'xxx permission is not enabled',
                        showCancel: false,
                        success(res) {
                        if (res.confirm) {
                            console.log('User clicks OK')
                            wx.openSetting({
                                success(res) {
                                    console.log(res.authSetting)
                                    res.authSetting = {
                                    "scope.camera": true,
                                    }
                                }
                            })
                        } else if (res.cancel) {
                            console.log('User clicks cancel')
                        }
                        }
                  })
                }
             })
        } else {
          console.log('Authorized')
        }
    },
    fail(err)=>{}
})

It's 2012 now. If this is written down and mixed with business logic, it will be terrible.

I couldn't stand it, so I spent some time encapsulating a function. Just pass in the specified permission name to detect whether the user has enabled the permission. If it is not enabled, there will be a prompt. If it is still not enabled, go to the settings page to manually enable it (in short, it must be enabled).

I originally wanted to write a code snippet, but later found that there was a problem when calling openSetting on the tool, so I had to give up.

#Code details

// 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);
  // Pop-up window prompting authorization if (showModalMes) {
    // Go for manual authorization let openSet = await openSettingSync(scope);
    if (openSet) {
      return true;
    } else {
      return false;
    }
  } else {
    // Reject authorization return false;
  }
};

// Determine whether the user has enabled the authorization function getSettingSync(scope) {
  return new Promise((resolve, reject) => {
    wx.getSetting({
      success(res) {
        if (!res.authSetting[scope]) {
          console.log("Unauthorized");
          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");
      },
    });
  });
}
// Pop-up window prompts user to manually authorize function showModalSync(scope) {
  return new Promise((resolve, reject) => {
    wx.showModal({
      title: "Tips",
      content: `For a better user experience, please authorize the ${scope} function`,
      confirmText: "Go to Authorization",
      showCancel: false,
      success(res) {
        if (res.confirm) {
          console.log("Click to confirm");
          resolve(true);
        } else if (res.cancel) {
          resolve(false);
        }
      },
      fail(err) {
        reject();
        console.error(err, "wx.showModal Error");
      },
    });
  });
}
// Call up the client applet settings 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");
      },
    });
  });
}

#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');
    })
   }
})

wxml code reference:

<!-- index.wxml -->
<view>Is it authorized: {{isCameraAuth}}</view>
<camera wx:if="{{isCameraAuth}}" style="width: 100%; height: 300px;"></camera>

#Preview

For this purpose, I made a Demo. Click Demo preview to open the preview directly in the development tool.

Summarize

This concludes this article on the best practices for WeChat Mini Program user authorization. For more relevant WeChat Mini Program user authorization content, please search 123WORDPRESS.COM’s previous articles or continue to browse the following related articles. I hope everyone will support 123WORDPRESS.COM in the future!

You may also be interested in:
  • WeChat applet authorization to obtain user details openid example detailed explanation
  • How to obtain the mobile phone number through user authorization in WeChat Mini Program (getPhoneNumber)
  • WeChat applet user authorization, and how to determine whether the login has expired
  • WeChat applet obtains mobile phone number to authorize user login function
  • WeChat Mini Program user authorization, location authorization, and obtaining WeChat-bound mobile phone numbers
  • WeChat Mini Program determines whether the user needs to authorize the acquisition of personal information again
  • When WeChat Mini Program user authorization pop-up window refuses, guide the user to re-authorize
  • WeChat Mini Program - How to obtain the user's geographic location name (without user authorization)
  • How to obtain user authorization again in WeChat Mini Program
  • Detailed explanation of WeChat applet development user authorization login

<<:  Linux server configuration IP whitelist to prevent remote login and port exposure

>>:  mysql8.0.11 winx64 manual installation and configuration tutorial

Recommend

Tutorial on installing Odoo14 from source code on Ubuntu 18.04

Table of contents Background of this series Overv...

Analysis and solutions to problems encountered in the use of label tags

I used the label tag when I was doing something re...

Detailed explanation of Vue life cycle functions

Table of contents Lifecycle Functions Common life...

How to install mysql database in deepin 2014 system

Deepin 2014 download and installation For downloa...

How to prevent hyperlink redirection using JavaScript (multiple ways of writing)

Through JavaScript, we can prevent hyperlinks fro...

Explanation of the usage scenarios of sql and various nosql databases

SQL is the main trunk. Why do I understand it thi...

Html Select uses the selected attribute to set the default selection

Adding the attribute selected = "selected&quo...

Mybatis implements SQL query interception and modification details

Preface One of the functions of an interceptor is...

Solution to Navicat Premier remote connection to MySQL error 10038

Remote connection to MySQL fails, there may be th...

In-depth understanding of the role of Vuex

Table of contents Overview How to share data betw...

Analysis of the cause of docker error Exited (1) 4 minutes ago

Docker error 1. Check the cause docker logs nexus...

Vue virtual Dom to real Dom conversion

There is another tree structure Javascript object...

JavaScript type detection method example tutorial

Preface JavaScript is one of the widely used lang...