微信小程序获取某一个用户授权的封装写法
发布于 3 年前 作者 ozhu 483 次浏览 来自 分享

参考文章 –https://developers.weixin.qq.com/community/develop/article/doc/00002c39258858bc052d066905f413

个人基于上一篇文章的逻辑和踩坑总结了现版本的获取某一个用户授权的封装写法

这是我发现的坑。。。

用async和await 调用wx.showModal 在调用wx.openSetting无法跳转权限设置页面

提示 errMsg: "openSetting:fail can only be invoked by user TAP gesture."

后来改成promise.then写法就可以了,完整代码如下,有些地方写的不好,欢迎指教

/**
 * 校验微信权限
 * [@param](/user/param) {string} auth 需要授权的api
 * [@returns](/user/returns) {boolean} 是否校验成功
 */
async function checkWXAPIoAuthority(auth){
  const AuthorityMap = new Map([
    ['bluetooth''蓝牙'],
    ['userLocation''用户地理位置'],
    ['userLocationBackground''后台用户位置'],
    ['record''麦克风'],
    ['camera''摄像头'],
    ['writePhotosAlbum''访问相册'],
    ['addPhoneContact''访问联系人'],
    ['addPhoneCalendar''日历'],
    ['werun''运动步数']
  ])
  if(!AuthorityMap.has(auth)) return false
  try {
    let { authSetting } = await wx.getSetting()
    if(authSetting['scope.' + auth]){
      return true
    }else{
      let resAuthorize = {}
      // 这里之所以有个if语句判断 authSetting是否存在该权限字段 
            // 是因为 报错信息:{errMsg: "authorize:fail 系统错误,错误码:-12006,auth deny"}
            // --https://developers.weixin.qq.com/community/develop/doc/0004cae5a34490ac227b55f7251c00?highline=12006
            // 用户首次授权用wx.authorize,非首次授权(用户拒绝了或手动取消后)就用wx.openSetting
            if(!authSetting.hasOwnProperty('scope.' + auth)) {
              try{
                resAuthorize = await wx.authorize({ scope'scope.' + auth })
        }catch(authorizeFail){
          resAuthorize = authorizeFail
        }
      }
      if(resAuthorize?.errMsg && resAuthorize.errMsg.indexOf('ok') !== -1){
        return true
      }else{
        // let operate = await wx.showModal({title: '提示', content: `需要您授权获取${AuthorityMap.get(auth)}权限`})
        // if (operate.confirm) {
        //   console.log('打开setting')     // 打开setting
        //   let setting = await wx.openSetting()
        //   console.log('setting==>', setting)  // undefined
        //   return true
        // } else {
        //   return false
        // }
        return new Promise((resolve, reject) => {
          wx.showModal({
            title'提示',
            content`需要您授权获取${AuthorityMap.get(auth)}权限`,
            success(operate) =>{
              if(operate.confirm){
                wx.openSetting({
                  success:({authSetting})=>{
                    console.log('openSetting', authSetting)
                    if(authSetting && authSetting['scope.' + auth]){
                      resolve(true)
                    } else {
                      resolve(false)
                    }
                  },
                  fail:()=>{
                    resolve(false)
                  }
                })
              } else{
                resolve(false)
              }
            },
            fail:()=>{
              resolve(false)
            }
          })
        })
      }
    }
  }catch(e){
    return false
  }
}

应用:

if(!await checkWXAPIoAuthority('bluetooth')) return

考虑到以后I18国际化,AuthorityMap 还要再做修改

回到顶部