部分接口在调用的时候会询问用户是否同意获得xxx权限
这种接口在未用户授权或授权列表中没有它时, 会出授权弹框
- 如果用户已授权,可以直接调用接口, 不再出现弹窗
- 如果用户已拒绝授权,则短期内不会出现弹窗
0.主要权限包括:
scope | 对应接口 | 描述 |
---|---|---|
scope.userInfo | wx.getUserInfo | 用户信息 |
scope.userLocation | wx.getLocation, wx.chooseLocation, wx.openLocation | 地理位置 |
scope.address | wx.chooseAddress | 通讯地址 |
scope.invoiceTitle | wx.chooseInvoiceTitle | 发票抬头 |
scope.werun | wx.getWeRunData | 微信运动步数 |
scope.record | wx.startRecord | 录音功能 |
scope.writePhotosAlbum | wx.saveImageToPhotosAlbum, wx.saveVideoToPhotosAlbum | 保存到相册 |
scope.camera | <camera /> | 摄像头 |
1.获取用户当前的授权状态:
wx.getSetting({
success: (res) => {
res.authSetting = {
"scope.userInfo": true, // 这一项允许
"scope.userLocation": true // 这一项允许
}
}
})
2.打开授权设置界面:
wx.openSetting({
success: (res) => {
res.authSetting = {
"scope.userInfo": true,
"scope.userLocation": true
}
}
})
3.在调用需授权 API 之前,提前向用户发起授权请求:
// 可以通过 wx.getSetting 先查询一下用户是否授权了 "scope.record" 这个 scope
wx.getSetting({
success(res) {
if (!res.authSetting['scope.record']) { // 如果record未授权
wx.authorize({ // 主动发起授权请求
scope: 'scope.record',
success() {
wx.startRecord()
}
})
}
}
})
注意:scope 为 "scope.userInfo" 时,无法弹出授权窗口
4.获取用户信息(特殊权限接口)
wx.getUserInfo(); 接口有调整,使用该接口将 不再出现 授权弹窗
可使用 <button open-type="getUserInfo"></button> 引导用户主动进行授权操作, 如:
<button open-type="getUserInfo" bindgetuserinfo="bindGetUserInfo">授权登录</button>
从bindgetuserinfo的事件对象中可以获取用户信息: e.detail.userInfo
还可更便捷获取用户头像和昵称:
<open-data type="userAvatarUrl"></open-data> // 获取头像
<open-data type="userNickName"></open-data> // 获取昵称
加载当前页面时, 也可以做一下授权判断:
onLoad: function() {
// 查看是否授权
wx.getSetting({
success: function(res){
if (res.authSetting['scope.userInfo']) {
// 已经授权,可以直接调用 getUserInfo 获取头像昵称
wx.getUserInfo({
success: function(res) {
console.log(res.userInfo) // 等同于e.detail.userInfo
}
})
}
}
})
},
bindGetUserInfo: function (e) {
console.log(e.detail.userInfo) // 等同于res.userInfo
}