微信小程序用户受权之最佳实际

开发微信小程序中,常常会用到获取一些用户权限的页面,比方你要登录,就要获取个人信息、你要做人脸识别,就要获取相机权限、你要做地位地图功能、就要获取用户的地位权限,你要将图片保留在用户的相册,须要获取相册权限等等

微信的 scope 流程:

大多数性能都是没有受权不可用的,个别我会检测是否开启权限,而后如果开启了就持续应用,没开启就给出提醒持续申请受权..如果还是回绝 就给出提醒 而后让用户手动去设置页关上...

失常逻辑

然而这一套写下来可能就是这样的:

wx.getSetting({    success(res)=>{        if (!res.authSetting['scope']) {          console.log('未受权')              wx.authorize({                scope: 'scope',                success() {                    console.log('受权胜利')                },                fail() {                    console.log('受权失败,让用户手动受权')                    wx.showModal({                        title: '舒适提醒',                        content: '未关上xxx权限',                        showCancel: false,                        success(res) {                        if (res.confirm) {                            console.log('用户点击确定')                            wx.openSetting({                                success(res) {                                    console.log(res.authSetting)                                    res.authSetting = {                                    "scope.camera": true,                                    }                                }                            })                        } else if (res.cancel) {                            console.log('用户点击勾销')                        }                        }                  })                }             })        } else {          console.log('已受权')        }    },    fail(err)=>{}})

当初都 1202 年了,这一套写下来,再掺杂着业务逻辑,那真的是惨不忍睹~

我是受不了,花了点工夫封装了个函数,只需传入指定的权限名称,就能检测用户是否开启权限,没有开启,会提醒,提醒还不开就去设置页手动关上(总之必须关上)。

原本想写个代码片段,起初发现工具上在调用 openSetting 时有问题,只好放弃。

代码细节

// 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 (scopeArr.indexOf(authType) == -1) {    return console.error("请输出正确的受权类型");  }  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) {    // 去手动受权    let openSet = await openSettingSync(scope);    if (openSet) {      return true;    } else {      return false;    }  } else {    // 回绝受权    return false;  }};// 判断用户是否开启该受权function getSettingSync(scope) {  return new Promise((resolve, reject) => {    wx.getSetting({      success(res) {        if (!res.authSetting[scope]) {          console.log("未受权");          resolve(false);        } else {          console.log("已受权");          resolve(true);        }      },      fail(err) {        reject();        console.error("wx.getSetting Error", err);      },    });  });}// 申请用户受权function authorizeSync(scope) {  return new Promise((resolve, reject) => {    wx.authorize({      scope: scope,      success() {        resolve(true);        console.log("受权胜利");      },      fail() {        resolve(false);        console.log("受权失败");      },    });  });}// 弹框提醒用户手动受权function showModalSync(scope) {  return new Promise((resolve, reject) => {    wx.showModal({      title: "提醒",      content: `为了更好的用户体验,请您受权 ${scope} 性能`,      confirmText: "去受权",      showCancel: false,      success(res) {        if (res.confirm) {          console.log("点击确认");          resolve(true);        } else if (res.cancel) {          resolve(false);        }      },      fail(err) {        reject();        console.error(err, "wx.showModal Error");      },    });  });}// 调起客户端小程序设置界面,返回用户设置的操作后果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");      },    });  });}

应用

JS 代码参考:

import auth from './../../utils/auth'Page({   data:{     isCameraAuth: false   },   onLoad(){         // 受权代码    auth('camera').then(() => {      console.log('受权胜利')      this.setData({        isCameraAuth: true      }    }).catch((err) => {      console.error('受权失败');    })   }})

wxml 代码参考:

<!-- index.wxml --><view>是否受权:{{isCameraAuth}}</view><camera wx:if="{{isCameraAuth}}" style="width: 100%; height: 300px;"></camera>

预览

为此,我制作了一个 Demo,点击Demo 预览,即可在开发工具中间接关上预览。

来自九旬的原创:博客原文链接