小程序的第一次授權發(fā)生在 app.js 的 onLaunch 方法 中
App({
onLaunch: function () {
//調用API從本地緩存中獲取數據
var logs = wx.getStorageSync('logs') || []
logs.unshift(Date.now())
wx.setStorageSync('logs', logs)
},
getUserInfo: function (cb) {
var that = this
if (this.globalData.userInfo) {
typeof cb == "function" && cb(this.globalData.userInfo)
} else {
//調用登錄接口
wx.login({
success: function (loginCode) {
// 這里會跳出彈框,獲取用戶信息
wx.getUserInfo({
success: function (res) {// 第一次允許授權
that.globalData.userInfo = res.userInfo // 獲取用戶信息贱除,賦給全局變量
typeof cb == "function" && cb(that.globalData.userInfo)
},
fail: function (res) {// 第一次拒絕授權
}
})
}
})
}
},
globalData: {
userInfo: null
}
})
如果拒絕授權,就獲取不到userInfo跪腹,但是之后有需要使用userInfo中的信息,這時候就需要 wx.openSetting() 再次喚醒用戶授權
wx.openSetting({// 調起用戶設置
success: function (res) {
res.authSetting = {
"scope.userInfo": true,
"scope.userLocation": true
}
if (res.authSetting["scope.userInfo"]) {// 第二次同意授權
wx.getUserInfo({
success: function (res) {
// 保存用戶信息
that.globalData.userInfo = res.userInfo
}
})
} else {// 第二次拒絕授權
// 進行處理
}
},
fail: function (res) {
}
})