[Small program] Encapsulation practice of authorization logic [For example to obtain user location, super simple and easy to understand! ! 】

Mini Program obtains user location authorization process

Preface

In the development process of small programs, user authorization is required in many places, and it is necessary to query whether the user is authorized, and there is no authorization to guide the user to authorize. So I encapsulated this process, so you can refer to it and make more comments and make progress together.

flow chart

Sometimes the logic of determining whether the user is authorized is used in many parts of the project, so encapsulation is very necessary. Let's take location authorization as an example to talk about the general process

Many applications will allow the user to authorize the geographic location as soon as they enter, and the user's latitude and longitude can be obtained by calculation to obtain the distance from the user. Below is a simple flowchart

Insert picture description here
Development must first wx.getSettiing()obtain the user's current settings and official documents. If you have the permission to proceed to the next step, if you do not request the user to open the permission again, if you click the user and click No, the authorization fails. If the user agrees, call wx.openSetting()the client applet setting interface, return the operation result set by the user, and the official document. After opening the settings page, if the user returns without opening the authorization, you will get the result of authorization failure. If you open the authorization and return to the previous page, the authorization is successful

Here, we should pay attention to the fact that to obtain geographic authorization, app.jsonadd the following code

"permission": {
    
    
    "scope.userLocation": {
    
    
      "desc": "您的位置信息将用于展示您所在城市的信息"
    }
  }

Main code

Create a new auth.js in the utils folder for authorization operation, and then you can directly pull it in 2 lines in the code!

/**
* 微信授权
*/
const authList = {
    
    
 userInfo: {
    
    
   apiName: ['getUserInfo'],
   authTitle: '需要使用你的用户信息',
   authContent: '需要使用你的用户信息,请确认授权'
 },
 userLocation: {
    
    
   apiName: ['getLocation', 'chooseLocation'],
   authTitle: '请求授权当前位置',
   authContent: '需要获取您的地理位置,请确认授权'
 },
 address: {
    
    
   apiName: ['chooseAddress'],
   authTitle: '需要使用你的通讯地址',
   authContent: '需要使用你的通讯地址,请确认授权'
 },
 invoiceTitle: {
    
    
   apiName: ['chooseInvoiceTitle'],
   authTitle: '需要使用你的发票抬头',
   authContent: '需要使用你的发票抬头,请确认授权'
 },
 invoice: {
    
    
   apiName: ['chooseInvoice'],
   authTitle: '需要获取你的发票',
   authContent: '需要获取你的发票,请确认授权'
 },
 werun: {
    
    
   apiName: ['getWeRunData'],
   authTitle: '需要获取你的微信运动数据',
   authContent: '需要获取你的微信运动数据,请确认授权'
 },
 writePhotosAlbum: {
    
    
   apiName: ['saveImageToPhotosAlbum', 'saveVideoToPhotosAlbum'],
   authTitle: '请求授权相册',
   authContent: '需要使用你的相册,请确认授权'
 },
}
/**
* @description: 返回值中只会出现小程序已经向用户请求过的权限
* @param {String} 权限名称
* @return {Boolean} 是有拥有权限
*/
const getWxSetting = key => {
    
    
 if (typeof key === 'string' && !authList[key]) return false
 return new Promise(function (resolve) {
    
    
   wx.getSetting({
    
    
     success: async res => {
    
    
       var result = res.authSetting
       // 用户拒绝过
       if (result[`scope.${
      
      key}`] === false) {
    
    
         // 引导去授权页
         _showModal(key).then(() => {
    
    
           resolve()
         })
       } else {
    
    
         //  已授权,或者还未授权
         resolve()
       }
     }
   })
 })
}
/**
* @description: 引导去授权设置页面
* @param {String} 权限名称
* @return {Boolean} 是有拥有权限
*/
const _showModal = key => {
    
    
 console.log(authList[key].authContent)
 return new Promise(function (resolve) {
    
    
   wx.showModal({
    
    
     title: authList[key].authTitle,
     content: authList[key].authContent,
     success: function (res) {
    
    
       if (res.confirm) {
    
    
         wx.openSetting({
    
    
           success: async dataAu => {
    
    
             // 异步,进入授权页面授权后返回判断
             if (dataAu.authSetting[`scope.${
      
      key}`] === true) {
    
    
               wx.showToast({
    
    
                 title: '授权成功',
                 icon: 'success',
                 duration: 1000
               })
               resolve()
             } else {
    
    
               wx.showToast({
    
    
                 title: '授权失败',
                 icon: 'none',
                 duration: 1000
               })
             }
           }
         })
         // 用户点击取消
       } else if (res.cancel) {
    
    
         wx.showToast({
    
    
           title: '授权失败',
           icon: 'none',
           duration: 1000
         })
       }
     }
   })
 })
}

module.exports = {
    
    
 getWxSetting
}

The page js introduces auth.js and calls the getWxSetting method to pass in the attribute name corresponding to the authList defined in auth.js

//index.js
//获取应用实例
const app = getApp()
const wxApi = require('../../utils/auth.js')
Page({
    
    
  data: {
    
    
  },
  // 打开地图
  openMap: function() {
    
    
    wxApi.getWxSetting('userLocation').then(()=>{
    
    
        // 已经授权或还未授权,下面的代码也可以根据需求提取到公共文件中
      wx.getLocation({
    
    
        type: 'wgs84',
        success: res => {
    
    
          wx.openLocation({
    
    
            latitude: res.latitude,
            longitude: res.longitude,
          })
        },
        fail: err => {
    
    
          wx.showToast({
    
    
            title: '检查手机定位权限',
            icon: 'none',
            duration: 2000
          })
        }
      })
    })
  },
  // 保存到相册
  writePhotosAlbum: function() {
    
    
    wxApi.getWxSetting('writePhotosAlbum').then(()=>{
    
    
     // 已经授权或还未授权,下面的代码也可以根据需求提取到公共文件中
      wx.downloadFile({
    
    
        url: 'https://imgs.solui.cn/avatar.png',
        success: function(res) {
    
    
            wx.saveImageToPhotosAlbum({
    
    
                filePath: res.tempFilePath,
                success: function(res) {
    
    
                   wx.showToast({
    
    
                     title: '保存成功',
                     icon:'none'
                   })
                },
                fail: function(err) {
    
    
                  wx.showToast({
    
    
                    title: '保存失败',
                    icon:'none'
                  })
                }
            })
        }
      })
    })
  },
  onLoad: function () {
    
    
  
  },
})

Then you can perform authorized operations. The wx.getLocation here can also extract public files, so I won’t repeat them here.

Source address:

https://github.com/sunniejs/weapp-auth-demo

Guess you like

Origin blog.csdn.net/weixin_43352901/article/details/108746145