首先我们要知道为什么要授权?
因为部分接口需要经过用户授权同意才能调用。我们把这些接口按使用范围分成多个 scope ,用户选择对 scope 来进行授权,当授权给一个 scope 之后,其对应的所有接口都可以直接使用。如果拒绝同意授权,那么该接口就不能使用。
所以我们开发者要注意对用户拒绝授权的情况进行处理。
详细的scope值讲解和授权信息请看官网:
https://developers.weixin.qq.com/miniprogram/dev/framework/open-ability/authorize.html
1、授权步骤解析
1、我们先使用 wx.getSetting()
这个微信api来判断获取用户的当前授权状态设置,判断将要让用户授权的权限是否已经授权过了,如果没有授权过,再发起授权请求。 wx.getSetting()
返回值中只会出现小程序已经向用户请求过的权限。
2、使用wx.authorize()
发起授权请求。
注意:wx.authorize({scope: “scope.userInfo”}),不会弹出授权窗口,请使用< button open-type="getUserInfo" bind:getuserinfo=”方法名”/>
。
意思就是说如果授权用户的用户信息那么只能通过button组件来实现,不能直接使用微信api的wx.authorize({scope: “scope.userInfo”})发起。除此之外的其他授权则可以使用微信wx.authorize({scope: "scope值"})
发起授权弹框请求。
3、拿到授权信息之后要做什么业务就继续。
下面我们以授权用户信息来举例(其他授权类似,少了一个特别注意点就是不必须使用button按钮,能直接调用api接口发起授权):
需要给个button按钮组件(或优化成其他样式)提示用户点击进行授权。bind:getuserinfo事件的执行方法中会接收实参event,event.detail.userInfo就是用户授权后的用户信息了,如果用户拒绝授权,那么就是event.detail.userInfo==undefined。
button组件的配置项详细解析:
https://developers.weixin.qq.com/miniprogram/dev/component/button.html
2、授权用户信息代码详解
1、提供按钮式发起授权用户信息登录的提示
<v-button open-type="getUserInfo" bind:getuserinfo="onGetUserInfo">
授权登录
</v-button>
2、点击上面的授权登录按钮后弹出授权框,点击拒绝或者允许都能拿到实参event对象中的detail.userInfo值进行判断用户是否允许授权了
onGetUserInfo(event) {
const userInfo = event.detail.userInfo
if (userInfo) {
//同意授权,业务代码
// 基本业务代码:登录系统;刷新系统用户信息
}else{
// 拒绝授权,业务代码
}
}
下面我们以授权用户地址来举例:不需要像上面的用户信息授权那样要通过button组件来发起授权了,而是可以绑定在任意标签上然后通过调用wx.authorize({scope: "scope值"})
发起授权弹框请求。
3、授权用户地址代码详解
1、组件上绑定点击事件发起授权地址
<view class="address-detail" bind:tap="onChooseAddress">
<view class="address-box">
<view class="name">
点击填写收货地址
</view>
</view>
</view>
2、业务代码
// 选择收货地址
onChooseAddress() {
this._getSetting().then((res) => {
// 如果还没有授权地址,那么发起授权
if (!res.authSetting['scope.address']) {
wx.authorize({
scope: 'scope.address',
success: () => {
// 授权地址后,就可以选择地址了
this.chooseAddress().then((res) => {
}).catch( (err) => { console.log(err) })
},
fail: res => { //这里是用户拒绝授权后的回调
console.log('取消授权')
}
})
} else { // 已经授权了那么就可以调用
this.chooseAddress().then((res) => {
// 选择到地址信息后的就可以进行进一步业务代码书写了,比如缓存地址
}).catch( (err) => { console.log(err) })
}
})
},
// 打开设置界面,判断获取用户的当前授权状态设置
_getSetting() {
return new Promise((resolve, reject) => {
wx.getSetting({
success: res => {
resolve(res)
}
})
})
},
//微信选址接口
chooseAddress() {
return new Promise((resolve, reject) => {
wx.chooseAddress({
success(res) {
resolve(res)
},
fail: res => {
reject(res)
}
})
})
}