PrefaceWhen 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 LogicBut 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"); }, }); }); } #useJS 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. SummarizeThis 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:
|
<<: Linux server configuration IP whitelist to prevent remote login and port exposure
>>: mysql8.0.11 winx64 manual installation and configuration tutorial
Table of contents Background of this series Overv...
I used the label tag when I was doing something re...
Table of contents Lifecycle Functions Common life...
Deepin 2014 download and installation For downloa...
Table of contents Overview Front-end knowledge sy...
Through JavaScript, we can prevent hyperlinks fro...
SQL is the main trunk. Why do I understand it thi...
Adding the attribute selected = "selected&quo...
Preface One of the functions of an interceptor is...
This article records the installation graphic tut...
Remote connection to MySQL fails, there may be th...
Table of contents Overview How to share data betw...
Docker error 1. Check the cause docker logs nexus...
There is another tree structure Javascript object...
Preface JavaScript is one of the widely used lang...