前言
開發一個微信小程式項目,首要問題就是使用者的登入授權流程問題,結合今年9月份小程式實施的新的審查來說。首次登入微信小程式的使用者,如果要擷取使用者的個人資訊,需要使用者點選button來做授權登入,授權登入成功之後,就可以擷取使用者的一些基本資訊,再緊接着跟背景進行互動擷取使用者的openID、unionid、token等為以後接口互動打下基礎。使用者首次授權成功後,再次進入小程式可以在小程式的app.js走自動授權流程。
需求和代碼
使用者進入頁面後,在需要授權的地方寫button
<button class="goUserInfo" open-type="getUserInfo" bindgetuserinfo="bindGetUserInfo">
使用者需求是不想再做彈窗提醒授權,是以button按鈕無法安放,是以我把它做成透明按鈕遮擋在頁面上,使用者如果沒有授權則button按鈕存在,點選頁面任意位置,拉起小程式授權彈窗,如果使用者已授權則去掉button。
//授權個人資訊
bindGetUserInfo(res) {
if (res.detail.userInfo) {
wx.showLoading({
title: '加載中...',
mask: true,
});
//使用者同意授權
app.globalData.userInfo = res.detail.userInfo;
//第一步手動授權登入
wx.login({
success: ress => {
//第二步擷取openid和uid
wx.request({
url: '', //請求位址
data: {
code: ress.code,
...
//請求資料
},
method: 'POST',
dataType: 'json',
responseType: 'text',
success: ({
data
}) => {
//對獲得的資訊進行存取
app.globalData.openId = data.data.openid
wx.setStorageSync('openId', data.data.openid)
app.globalData.unionid = data.data.unionid
//第三步根據需求繼續擷取使用者相應的資訊
this.getUser(參數)
},
});
},
});
} else {
wx.showToast({
title: '您拒絕了授權',
icon: 'none',
duration: 2000
});
}
},
自動授權流程app.js
// 登入
wx.login({
success: res => {
// 發送 res.code 到背景換取 openId, sessionKey, unionId
let code = res.code;
this.globalData.code = code;
// 擷取使用者資訊
wx.getSetting({
success: res => {
if (res.authSetting['scope.userInfo']) {
//本地存儲方法結合頁面透明button按鈕的顯現
wx.setStorageSync(參數, false);
// 已經授權,可以直接調用 getUserInfo 擷取頭像昵稱
wx.getUserInfo({
success: res => {
// 可以将 res 發送給背景解碼出 unionId
this.globalData.userInfo = res.userInfo
wx.request({
url: '',
data: {
code,
...
//傳送相應的資訊
},
method: 'POST',
dataType: 'json',
responseType: 'text',
success: ({
data
}) => {
this.globalData.openId = data.data.openid
wx.setStorageSync('openId', data.data.openid)
this.globalData.unionid = data.data.unionid
//第三步繼續擷取使用者的相應資訊
this.getUser(參數)
},
fail: err => {
console.log('微信 request 接口報錯', err);
}
});
// 由于 getUserInfo 是網絡請求,可能會在 Page.onLoad 之後才傳回
// 是以此處加入 callback 以防止這種情況
if (this.userInfoReadyCallback) {
this.userInfoReadyCallback(res);
}
},
fail: err => {
console.log('微信 getUserInfo 接口報錯', err)
}
})
} else {
//結合透明button的顯現
wx.setStorageSync(參數, true);
}
},
fail: err => {
console.log('微信 getSetting 接口報錯', err)
}
})
},
fail: err => {
console.log('微信 login 接口報錯', err);
}
})