授权
部分接口需要经过用户授权同意才能调用。我们把这些接口按使用范围分成多个 scope ,用户选择对 scope 来进行授权,当授权给一个 scope 之后,其对应的所有接口都可以直接使用。
此类接口调用时:
如果用户未接受或拒绝过此权限,会弹窗询问用户,用户点击同意后方可调用接口;
如果用户已授权,可以直接调用接口;
如果用户已拒绝授权,则不会出现弹窗,而是直接进入接口 fail 回调。请开发者兼容用户拒绝授权的场景。
小程序用户信息组件示例代码(官方文档)
<!-- 如果只是展示用户头像昵称,可以使用 <open-data /> 组件 -->
<open-data type="userAvatarUrl"></open-data>
<open-data type="userNickName"></open-data>
<!-- 需要使用 button 来授权登录 -->
<button wx:if="{{canIUse}}" open-type="getUserInfo" bindgetuserinfo="bindGetUserInfo">授权登录</button>
<view wx:else>请升级微信版本</view>
Page({
data: {
canIUse: wx.canIUse('button.open-type.getUserInfo')
},
onLoad: function() {
// 查看是否授权
wx.getSetting({
success (res){
if (res.authSetting['scope.userInfo']) {
// 已经授权,可以直接调用 getUserInfo 获取头像昵称
wx.getUserInfo({
success: function(res) {
console.log(res.userInfo)
}
})
}
}
})
},
bindGetUserInfo (e) {
console.log(e.detail.userInfo)
}
})
使用 promise 封装的wx请求
othersRequest(type) {
return new Promise((resolve, reject) => {
wx[type]({
success: (res => {
resolve(res); }),
fail: (res => {
reject(res) }) }) }) },
checkAuthorize() { return request.othersRequest('getSetting').then(res => { if (res.authSetting['scope.userInfo']) { app.globalData.isAuthorization = true; this.getUserInfo(); apiService.wechatLogin(); } else { app.globalData.isAuthorization = false; } }).catch(err => { request.errorHander(err); }) },
getUserInfo() { return request.othersRequest('getUserInfo').then(res => { const userInfo = this.refactorUserInfo(res.userInfo); app.globalData.userInfo = userInfo; this.setUserInfo(userInfo);
}).catch(err => { request.errorHander(err); }) },
wechatLogin() {
return request.othersRequest('login').then(res => { globalData.wxLoginCode = res.code;
})
.catch(err => {
this.errorHander(err); }) },