# 微信小程序用户授权之最佳实践

开发微信小程序中,经常会用到获取一些用户权限的页面,比如你要登录,就要获取个人信息、你要做人脸识别,就要获取相机权限、你要做位置地图功能、就要获取用户的位置权限...

请求权限流程

大多数功能都是没有授权不可用的,一般我会检测是否开启权限,然后如果开启了就继续使用,没开启就给出提示继续请求授权..如果还是拒绝 就给出提示 然后让用户手动去设置页打开...

# 正常逻辑

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

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)=>{}
})

写一套写下来,在掺杂着业务逻辑,那真的是..要多恶心..有多恶心啊~

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

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

# 封装后

代码参考:

// index.js
import wxAuth from "./../utils/wxAuth";
Page({
  data: {
    isAuth: false,
  },
  onShow: function() {
    wxAuth("camera").then((res) => {
      this.setData({
        isAuth: res,
      });
      console.log("授权结果", res);
    });
  },
});
<!-- index.wxml -->
<view>是否授权:{{isAuth}}</view>
<camera wx:if="{{isAuth}}" style="width: 100%; height: 300px;"></camera>
// utils/wxAuth.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");
      },
    });
  });
}
上次更新: 12/29/2020, 9:48:54 AM