簡介
wx.getUserInfo接口獲取用戶信息官方文檔介紹:
https://developers.weixin.qq.com/miniprogram/dev/api/open-api/user-info/wx.getUserInfo.html
在調用wx.getUserInfo接口之前需要用戶授權:
https://developers.weixin.qq.com/miniprogram/dev/framework/open-ability/authorize.html
一旦用戶明確同意或拒絕過授權,其授權關系會記錄在后台,直到用戶主動刪除小程序。
使用 wx.getSetting 獲取用戶當前的授權狀態,官方文檔:
https://developers.weixin.qq.com/miniprogram/dev/api/open-api/setting/wx.getSetting.html
使用wx.getUserInfo接口
app.js文件中添加如下代碼:
App({ //小程序啟動后觸發 onLaunch: function () { // 登錄 wx.login({ success: res => { // 發送 res.code 到后台換取 openId, sessionKey, unionId } }) // 獲取用戶信息 wx.getSetting({ success: res => { if (res.authSetting['scope.userInfo']) { // 已經授權,可以直接調用 getUserInfo 獲取頭像昵稱,不會彈框 wx.getUserInfo({ success: res => { // 可以將 res 發送給后台解碼出 unionId this.globalData.userInfo = res.userInfo // 由於 getUserInfo 是網絡請求,可能會在 Page.onLoad 之后才返回 // 所以此處加入 callback 以防止這種情況 if (this.userInfoReadyCallback) { this.userInfoReadyCallback(res) } } }) } } }) }, globalData: {//設置全局對象 userInfo: null } })
tips:未授權的情況下調用wx.getUserInfo接口,將不再出現授權彈窗,會直接進入 fail 回調,使用<button open-type="getUserInfo"></button>引導用戶主動進行授權操作;在用戶已授權的情況下調用此接口,可成功獲取用戶信息。
官方接口調整說明:https://developers.weixin.qq.com/community/develop/doc/0000a26e1aca6012e896a517556c01
personal.wxml文件中添加如下代碼:
<view class="topleft"> <image class="userinfo-avatar" src='{{userInfo.avatarUrl}}' mode="cover" ></image> <button class="headbutton" wx:if="{{!hasUserInfo && canIUse}}" open-type="getUserInfo" bindgetuserinfo="getUserInfo">點擊登錄</button> <block wx:else> <text class="userinfo-nickname">{{userInfo.nickName}}</text> </block> </view>
personal.js文件中添加如下代碼:
//獲取應用實例 const app = getApp() Page({ /** * 頁面的初始數據 */ data: { userInfo: { avatarUrl:"/images/head.png" }, //用戶信息 hasUserInfo: false, canIUse: wx.canIUse('button.open-type.getUserInfo'), //測試getUserInfo在當前版本是否可用 }, /** * 生命周期函數--監聽頁面加載 */ onLoad: function(options) { //如果全局對象用戶信息為空 if (app.globalData.userInfo) { this.setData({ userInfo: app.globalData.userInfo, //將全局用戶信息賦值給變量 hasUserInfo: true //顯示引導授權按鈕 }) } else if (this.data.canIUse) { //getUserInfo在當前版本可用 // 由於 getUserInfo 是網絡請求,可能會在 Page.onLoad 之后才返回 // 所以此處加入 callback 以防止這種情況 app.userInfoReadyCallback = res => { this.setData({ userInfo: res.userInfo, hasUserInfo: true }) } } else { // 在沒有 open-type=getUserInfo 版本的兼容處理 wx.getUserInfo({ success: res => { app.globalData.userInfo = res.userInfo this.setData({ userInfo: res.userInfo, hasUserInfo: true }) } }) }; }, getUserInfo: function(e) { //點擊取消按鈕 if (e.detail.userInfo == null) { console.log("授權失敗") } else {//點擊允許按鈕 this.setData({ userInfo: e.detail.userInfo, hasUserInfo: true }) } //全局對象用戶信息賦值 app.globalData.userInfo = e.detail.userInfo } })
效果圖:
tips:客戶點擊取消授權按鈕可調用 wx.openSetting 打開設置界面,引導用戶開啟授權。也可以使用 wx.authorize 在調用需授權 API 之前,提前向用戶發起授權請求。
END!