小編給大家分享一下微信小程序中wx.getUserInfo如何引導用戶授權,希望大家閱讀完這篇文章之后都有所收獲,下面讓我們一起去探討吧!
具體如下:
首先,在page外定義一個函數用戶判斷是否為空對象
var isEmptyObject = function (e) {
var temp;
for (temp in e)
return !1;
return !0
}然后,在page中的onload里面調用授權
onLoad: function () {
var that = this;
if (app.globalData.userInfo) {
this.setData({
userInfo: app.globalData.userInfo
})
} else if (this.data.canIUse) {
// 由于 getUserInfo 是網絡請求,可能會在 Page.onLoad 之后才返回
// 所以此處加入 callback 以防止這種情況
app.userInfoReadyCallback = res => {
this.setData({
userInfo: res.userInfo
})
}
} else {
// 在沒有 open-type=getUserInfo 版本的兼容處理
wx.getUserInfo({
success: res => {
app.globalData.userInfo = res.userInfo
this.setData({
userInfo: res.userInfo
})
that.checkSettingStatu();
},
fail: function () {
wx.showModal({
title: '用戶未授權',
content: '如需正常使用該小程序功能,請按確定并在授權管理中選中“用戶信息”,然后點按確定。最后再重新進入小程序即可正常使用。',
showCancel: false,
success: function (resbtn) {
if (resbtn.confirm) {
wx.openSetting({
success: function success(resopen) {
// 獲取用戶數據
that.checkSettingStatu();
}
});
}
}
})
}
})
}
}最后,在page中定義一個 用于檢測 當前授權的狀態
checkSettingStatu: function (cb) {
var that = this;
// 判斷是否是第一次授權,非第一次授權且授權失敗則進行提醒
wx.getSetting({
success: function success(res) {
var authSetting = res.authSetting;
if (isEmptyObject(authSetting)) {
//第一次
} else {
// 沒有授權的提醒
if (authSetting['scope.userInfo'] === false) {
wx.showModal({
title: '用戶未授權',
content: '如需正常使用該小程序功能,請按確定并在授權管理中選中“用戶信息”,然后點按確定。最后再重新進入小程序即可正常使用。',
showCancel: false,
success: function (res) {
if (res.confirm) {
wx.openSetting({
success: function success(res) {
console.log()
}
});
}
}
})
} else if (authSetting['scope.userInfo'] === true) {
//該處用戶獲取用戶的一些授權信息
if (that.data.userInfo) {
var nickname = that.data.userInfo.nickName;
var gender = that.data.userInfo.gender
//性別 0:未知、1:男、2:女
if (gender == 1) {
gender = "True"
} else if (gender == 2) {
gender = "False"
} else {
gender = "True"
}
}
}
}
}
})
}看完了這篇文章,相信你對“微信小程序中wx.getUserInfo如何引導用戶授權”有了一定的了解,如果想了解更多相關知識,歡迎關注億速云行業資訊頻道,感謝各位的閱讀!
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。