小程式授權功能
阿新 • • 發佈:2018-11-28
小程式登陸和使用授權
不想重新寫頁面引導使用者授權,因為官方說明
scope 為 “scope.userInfo” 時,無法彈出授權視窗,請使用
理一下思路:
1. 登陸操作,獲取使用者openid
2. 查詢是否授權
3. 已經授權,直接獲取使用者資訊
4. 未授權,引導使用者授權
5. 授權成功,重新登陸
6. 授權失敗,提示使用者
1.登陸
這一步目的是為了獲取使用者的openid
//1.登陸獲取使用者openid
wx.login({
success: function(resdata) {
if (resdata.code) {
wx.request({
url: appConfig.config.getOpenId,
data: {
//somedata
},
success: function(res) {
//do something
}
})
} else {
that.openAlert();
}
},
fail: function(res) {
that.openAlert();
}
});
2.檢視是否授權
//2. 檢視是否授權
wx.getSetting({
success: function (res) {
if (res.authSetting['scope.userInfo']) {
//授權了
} else {
//未授權
}
}
})
3.已經授權,獲取使用者資訊
//3. 已經授權,獲取使用者資訊
wx.getUserInfo({
success: function(res) {
that.globalData.userInfo = res.userInfo
console.log(res.userInfo)
}
})
4.未授權,引導使用者授權
//4.未授權,引導使用者授權
wx.showModal({
title: '使用者未授權',
content: '如需正常使用小程式功能,請進行使用者授權。',
showCancel: true,
success: function(res) {
if (res.confirm) {
console.log("使用者確認授權")
} else {
console.log("使用者取消授權")
}
}
})
5.授權成功
//5.授權成功
if (wx.openSetting) {
wx.openSetting({
success: function(res) {
//重新登陸
}
})
}
6.因外部原因授權失敗
//6.因外部原因授權失敗
else {
wx.showModal({
title: '授權提示',
content: '小程式需要您的微信授權才能使用哦~ 錯過授權頁面的處理方法:刪除小程式->重新搜尋進入->點選授權按鈕'
})
}