Best practices for WeChat applet user authorization
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 flow:
Most of the 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. If it is not enabled, I will give a prompt to continue to request authorization.. If you still refuse, give a prompt and ask the user to manually set the page to open…
Normal logic
But the set might look something like this:
wx.getSetting({ success(res)=>{ if (! Res.authSetting ['scope']) {console.log(' Unauthorized ') wx.authorize({scope: 'scope', success() {console.log(' authorization succeeded ')}, fail() {console.log(' authorization failed, let user manually authorize ') wx. ShowModal ({title: 'heartsnote ', content: 'XXX permissions not open ', showCancel: false, Success (res) {if (res.confirm) {console.log(' User click OK ') wx.openSetting({success(res) {console.log(res.authSetting)). res.authSetting = { "scope.camera": True,}}})} else if (res) cancel) {the console. The log (' user click cancel ')}}}}})} else {the console. The log (' authorized ')}}, fail(err)=>{} })
It’s now 1202 years old, and when it’s written down, mixed with business logic, it’s really horrible to see
I can’t stand it, spend some time to encapsulate a function, just pass in the specified permissions name, can detect whether the user is open permissions, not open, will prompt, prompt still not open Settings page manually (in short, must open).
I wanted to write a snippet of code, but I had trouble getting Openensetting out of the tool.
Details of the code
// utils/auth.js /** * @param { * authType: *} */ 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 (scopear.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); If (showModalmes) {// manually grant let openSet = await openSettingSync(scope); if (openSet) { return true; } else { return false; }} else {// deny return false; }}; 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); }}); }); } function authorizeSync(scope) {return new Promise((resolve, reject) => {wx.authorize({scope: authorizeSync) {return new Promise((resolve, reject)) => {wx.authorize({scope: authorizeSync); scope, success() { resolve(true); Console. log(" Authorization succeeded "); }, fail() { resolve(false); Console. log(" Authorization failed "); }}); }); } function showModalSync(scope) {return new Promise((resolve, reject) => {wx.showModal({title: "Prompt ", content: 'For better user experience, please authorize the ${scope} function', confirmText:" to authorize ", showCancel: False, success(res) {if (res.confirm) {console.log(" Click Confirm "); resolve(true); } else if (res.cancel) { resolve(false); } }, fail(err) { reject(); console.error(err, "wx.showModal Error"); }}); }); } // Turn up the client applet setup interface, 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(){// CameraAuth (' CameraAuth '). Then (() => {console.log(' CameraAuth succeeded ') this.setData({isCameraAuth: True}}). The catch ((err) = > {console. Error (' authorization failure); })}})
WXML code reference:
<! {{isCameraAuth}}</view> <camera wx:if="{{isCameraAuth}}" style="width: 100%; height: 300px;" ></camera>
preview
To this end, I made a Demo, click the preview Demo, you can directly open the preview in the development tool.
Original from the nineties:
Blog text link