為優化用戶體驗,使用 wx.getUserInfo 接口直接彈出授權框的開發方式將逐步不再支持。從2018年4月30日開始,小程序與小游戲的體驗版、開發版調用 wx.getUserInfo 接口,將無法彈出授權詢問框,默認調用失敗。會直接進入 fail 回調,在用戶已授權的情況下調用此接口,可成功獲取用戶信息。
開發者可使用以下方式獲取或展示用戶信息:
1,請使用 <button open-type="getUserInfo"></button> 引導用戶主動進行授權操作。
- 新建login模板文件,在login.wxml添加如下代碼:
<button open-type="getUserInfo" bindgetuserinfo="bindGetUserInfo">授權登錄</button>
- 在login.js文件中添加bindGetUserInfo點擊事件:
bindGetUserInfo: function(e){ //此處授權得到userInfo console.log(e.detail.userInfo); //接下來寫業務代碼 app.globalData.userInfo = e.detail.userInfo; //最后,記得返回剛才的頁面 wx.navigateBack({ delta: 1 }) }
2,調用接口函數wx.getUserInfo時:
1)當用戶未授權過,調用該接口將直接報錯,會直接進入 fail 回調
2)當用戶授權過,可以使用該接口獲取用戶信息
wx.getUserInfo({ withCredentials: true, success: function (res) { //此處為獲取微信信息后的業務方法,存入緩存 wx.setStorageSync("userInfo", res.userInfo); }, fail: function () { //獲取用戶信息失敗后。請跳轉授權頁面 wx.showModal({ title: '提醒', content: '尚未進行授權,請點擊確定跳轉到授權頁面進行授權。', success: function (res) { if (res.confirm) { //跳轉到授權界面 wx.navigateTo({ url: '/pages/login/login', }) } } }) } })
微信小程序案例:
我和怪獸有個合影