功能:不授权不能正常使用程序
通杀版本只需要在调用时传入相应授权码即可实现小程序授权通杀
界面:上一篇帖子 https://blog.csdn.net/aaron9185/article/details/84101455
代码实现
一、在app.js中插入检测授权状态方法 授权成功则继续 不成功跳转到授权页面
//权限询问界面 需传入 授权名称 权限代码
getAuthState: function(stateName, stateKey) {
var that = this
wx.getSetting({
success(res) {
// console.log(stateName)
// console.log(stateKey)
// console.log(res)
if (!res.authSetting[stateKey]) {
console.log('我是授权未成功')
var tempData = stateName + 'and' + stateKey
wx.navigateTo({
url: '../authorize/authorize?tempData=' + tempData
})
} else {
console.log("我是已经授权成功")
}
}
})
},
二、授权页面 在授权页面插入授权事件
// 权限询问
getRecordAuth: function() {
var that = this
console.log('我是授权页面')
// console.log(that.data.stateName)
// console.log(that.data.stateKey)
wx.getSetting({
success(res) {
if (!res.authSetting[that.data.stateKey]) {
wx.authorize({
scope: that.data.stateKey,
success() {
//成功授权 返回上个页面
console.log("授权" + that.data.stateName + '成功')
wx.navigateBack({
delta: 1,
})
},
fail() {
console.log("授权" + that.data.stateName + '失败')
//授权失败后进行提醒 并要求手动授权
that.getAsk(that.data.stateName, that.data.stateKey)
}
})
} else {
console.log("我是已经授权成功")
}
}
})
},
//拒绝授权后再次询问
getAsk: function(stateName, stateKey) {
var that = this
wx.showModal({
title: '',
content: '拒绝' + stateName + '授权后将会影响您的体验!是否进行手动授权!',
showCancel: true,
success: function(res) {
if (res.confirm) {
//点击确认后打开手动设置页面
wx.openSetting({
success: (res) => {
console.log(res.authSetting);
if (!res.authSetting['scope.record']) {
//未设置录音授权
console.log("未设置录音授权");
wx.showModal({
title: '提示',
content: '您未进行' + stateName + '授权,功能将无法使用。',
showCancel: false,
success: function(res) {},
})
} else {
//第二次才成功授权 返回上个页面
console.log("设置录音授权成功");
wx.navigateBack({
delta: 1,
})
}
},
fail: function() {
console.log("授权设置录音失败");
}
})
} else if (res.cancel) {
//点击取消后
}
}
})
},
三、调用 建议在onshow中使用 调用授权是传入相应授权码即可实现授权通杀
const app = getApp()
onShow: function() {
var that = this
//获取授权
var temp = app.getAuthState("录音", "scope.record")
},