一、 前言
小程序官方文檔,上面說明
wx.getUserInfo(OBJECT) 注意:此接口有調整,使用該接口將不再出現授權彈窗,請使用
<button open-type="getUserInfo"></button>
引導用戶主動進行授權操作。
當用戶未授權過,調用該接口將直接報錯 當用戶授權過,可以使用該接口獲取用戶信息
如上文,之前用戶未授權過時,調用wx.getUserInfo會調出授權框;但現在在用戶未授權過時調用該接口,會直接走fail方法。
所以我們要使用上述button來請求用戶授權。
二、主體
以index頁面作為展示授權按鈕的頁面,並且在app.json中將index作為首頁。在判斷用戶授權之后跳轉到其他頁面。
index.wxml
<button
wx:if="{{canIUse}}"
open-type="getUserInfo"
bindgetuserinfo="bindGetUserInfo"
>授權登錄</button>
<view wx:else>請升級微信版本</view>
index.js
Page({
data: {
//判斷小程序的API,回調,參數,組件等是否在當前版本可用。
canIUse: wx.canIUse('button.open-type.getUserInfo')
},
onLoad: function() {
// 查看是否授權
wx.getSetting({
success: function(res){
if (res.authSetting['scope.userInfo']) {
wx.getUserInfo({
success: function(res) {
console.log(res.userInfo)
//用戶已經授權過
}
})
}
}
})
},
bindGetUserInfo: function(e) {
console.log(e.detail.userInfo)
if (e.detail.userInfo){
//用戶按了允許授權按鈕
} else {
//用戶按了拒絕按鈕
}
}
})