头图

Best Practices for User Authorization of WeChat Mini Programs

九旬
中文

Best Practices for User Authorization of WeChat Mini Programs

In the development of WeChat Mini Programs, the page to obtain some user permissions is often used. For example, if you want to log in, you need to get personal information , if you want to face recognition, you need to get camera permission , you need to do location map function , To obtain the user's location permission , you want to save the picture in the user's album, you need to obtain the album permission and so on

WeChat scope process:

请求权限流程

Most functions are unavailable 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 requesting authorization.. If it still refuses, I will give a prompt and let the user go manually. The settings page opens...

Normal logic

But this set may be written like this:

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

It is now 1202 years old, and this set is written down, and it is mixed with business logic. It is really horrible~

I can’t stand it. It took a while to encapsulate a function. Just pass in the specified permission name to detect whether the user has enabled the permission. If it is not enabled, it will prompt. If the prompt is not opened, go to the settings page to open it manually (in short, you must turn on).

Originally I 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: 授权类型
 * }
 */

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");
      },
    });
  });
}

use

JS code reference:

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

wxml code reference:

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

Preview

To this end, I made a Demo, click Demo to preview , you can directly open the preview in the development tool.

Original from the : 16099dc73d4873 blog original link
阅读 4.4k

九旬的博客
关注我,每周输出一篇前端技术文章, 博客地址:[链接]

关注我,每周输出一篇前端技术文章,

893 声望
1.2k 粉丝
0 条评论

关注我,每周输出一篇前端技术文章,

893 声望
1.2k 粉丝
文章目录
宣传栏