说明:微信授权页面一经用户拒绝过一次后后续就不会再弹出 只能手动点击右上角打开设置去授权,此方法解决了不需要用户手动打开设置授权 只要用户拒绝过授权 下次进来就会以弹窗的形式询问是否需要授权 是的话自动跳转到设置页面
1. 新建公共的js文件 commonAuth.js
let setting = null;
const dealAuth = (authSetting, key, content, callback) => {
if (authSetting?.[key] === true) callback?.(true)
if (authSetting?.[key] === false) {
wx.showModal({
title: '提示',
content,
success(res) {
if (res.confirm) {
wx.openSetting({
withSubscriptions: true,
success(res) {
res.authSetting[key] && callback?.(true)
!res.authSetting[key] && callback?.(false)
},
// fail() { callback?.(false) }
})
} else if (res.cancel) callback?.(false)
}
})
}
if (authSetting?.[key] === undefined) {
wx.authorize({
scope: key,
success() { callback?.(true) },
fail() { callback?.(false) }
})
}
}
module.exports.commonAuth = (key, content, callback) => {
!setting && wx.getSetting({
success(res) {
setting = res
dealAuth(res.authSetting, key, content, callback)
}
})
setting && dealAuth(setting.authSetting, key, content, callback)
}
2. 使用方式
const { commonAuth } = require('@/common/utils/commonAuth')
commonAuth('scope.record', '打开录音授权页面吗?', (result) => {
// result true授权成功 可以使用对应api false拒绝授权
// 授权打开后开始调用相关api
wx.startRecord()
})