登錄及獲取微信用戶信息
-
調(diào)用wx.login()獲取登錄憑證code,再調(diào)用后端接口換取用戶登錄態(tài)信息(openid, session_key)
此時(shí)獲得的登錄狀態(tài)具有時(shí)效性献幔,可以調(diào)用
wx.checkSession()
檢查是否過(guò)期,若過(guò)期蜡感,則需要重新調(diào)用wx.login()
執(zhí)行登錄流程 -
使用wx.getSetting()獲取用戶授權(quán)列表
- 若已授權(quán):調(diào)用wx.getUserInfo()獲取用戶信息
- 若未授權(quán):彈出模態(tài)框展示一個(gè) 微信授權(quán)登錄 按鈕提示用戶點(diǎn)擊登錄
- 同意授權(quán):用戶授權(quán)后可通過(guò)綁定的方法獲取用戶信息
- 拒絕授權(quán):則無(wú)法獲取用戶信息,若必須微信授權(quán)登錄才可用犀斋,可以以恰當(dāng)?shù)姆绞浇o出說(shuō)明情连,如使用
wx.openSetting()
引導(dǎo)用戶手動(dòng)打開(kāi)授權(quán)開(kāi)關(guān)
將獲取到的用戶信息和第1部中得到的code使用服務(wù)端提供的接口更新用戶信息叽粹,如1中的示例
授權(quán)綁定微信手機(jī)號(hào)
- 顯示授權(quán)綁定微信手機(jī)號(hào)的按鈕(必須用戶手動(dòng)點(diǎn)擊)
- 用戶同意授權(quán)后却舀,調(diào)用成功回調(diào)處理后續(xù)操作
相應(yīng)接口代碼示例
-
用戶授權(quán)列表:wx.getSetting()
wx.getSetting({ success (res) { console.log(res.authSetting) // res.authSetting = { // "scope.userInfo": true, // true已授權(quán) false未授權(quán) // "scope.userLocation": true // ... // } } })
-
wx.checkSession({ success () { //session_key 未過(guò)期,并且在本生命周期一直有效 }, fail () { // session_key 已經(jīng)失效辆脸,需要重新執(zhí)行登錄流程 wx.login() //重新登錄 } })
-
調(diào)用
wx.login()
進(jìn)行登錄并獲取cookieswx.login({ success: function(res) { // 得到了code if (res.code) { wx.request({ url: api.user.authLogin(res.code) // 后端提供的驗(yàn)證登錄接口 success: function(response) { // 驗(yàn)證成功螃诅,保存cookies, 封裝在全局統(tǒng)一的請(qǐng)求方法中状囱,如get, post wx.setStorage({ key: 'cookies', data: response.data.res.cookies }) wx.getUserInfo({ withCredentials: true, success: function(res) { // 取得用戶微信信息,調(diào)用后端接口更新用戶信息 const userInfo = res.userInfo const encryptedData = res.encryptedData const iv = res.iv const params = { nick_name: userInfo.nickName, gender: userInfo.gender, province: userInfo.province, city: userInfo.city, country: userInfo.country, avatar_url: userInfo.avatarUrl, encrypted_data: encryptedData, encrypt_iv: iv } server.get(api.user.updateBaseInfo(), params, () => { // 成功保存用戶信息 }) } }) } }) } } })
-
微信授權(quán)登錄
<button open-type="getUserInfo" bindgetuserinfo="onGetUserInfo">微信登錄</button>
methods = { onGetUserInfo: this.handleGetUserInfo } // 同意授權(quán) handleGetUserInfo(e) { wx.getUserInfo() }
-
授權(quán)獲取微信綁定的手機(jī)號(hào)
<button open-type="getPhoneNumber" bindgetphonenumber="onGetPhoneNumber"> 綁定微信手機(jī)號(hào) </button>
methods = { onGetPhoneNumber: this.handleGetPhoneNumber } /** * 同意授權(quán)獲取手機(jī)號(hào) * @desc 獲取到 encryptedData,iv信息搀崭,需要服務(wù)端解密才能獲取到真正的手機(jī)號(hào) */ handleGetPhoneNumber(e) { if (e.detail.iv) { server.post(api.user.bindWXPhoneNumber(), { encrypted_data: e.detail.encryptedData, encrypt_iv: e.detail.iv }, data => { wx.showToast({ title: '綁定成功' }) // do something }, error => { wx.showModal({ title: '綁定失敗', content: '[服務(wù)端返回的錯(cuò)誤信息]', showCancel: false, success: res => { if (res.confirm) { // 用戶確認(rèn)后 // do something } } }) }) } else { // 用戶拒絕授權(quán) // do something } }