前置知识及scope列表:https://developers.weixin.qq.com/miniprogram/dev/framework/open-ability/authorize.html
1.获取用户授权设置
开发者可以使用 wx.getSetting 获取用户当前的授权状态。
打开设置界面
用户可以在小程序设置界面(「右上角」 - 「关于」 - 「右上角」 - 「设置」)中控制对该小程序的授权状态。
开发者可以调用 wx.openSetting 打开设置界面,引导用户开启授权。
wx.openSetting({
success (res) {
console.log(res.authSetting)
// res.authSetting = {
// "scope.userLocationBackground": true,
// "scope.userLocation": true
// }
}
})
2.提前发起授权请求
开发者可以使用 wx.authorize 在调用需授权 API 之前,提前向用户发起授权请求。
// 可以通过 wx.getSetting 先查询一下用户是否授权了 "scope.record" 这个 scope
wx.getSetting({
success(res) {
if (!res.authSetting['scope.userLocationBackground']) {
wx.authorize({
scope: 'scope.userLocationBackground',
success () {
// 用户已经同意小程序使用后台定位功能,后续调用 定位相关 接口不会弹窗询问
}
})
}
}
})