微信小程序獲取用戶信息接口調整目的以及使用方法介紹
微信小程序已經調整了獲取用戶信息的接口,還不知道的開發者看一下官網給出的理由和方法:
為優化用戶體驗,使用 wx.getUserInfo 接口直接彈出授權框的開發方式將逐步不再支持。從2018年4月30日開始,小程序與小游戲的體驗版、開發版調用 wx.getUserInfo 接口,將無法彈出授權詢問框,默認調用失敗。正式版暫不受影響。開發者可使用以下方式獲取或展示用戶信息:
1、使用 button 組件,並將 open-type 指定為 getUserInfo 類型,獲取用戶基本信息。 詳情參考文檔: https://developers.weixin.qq.com ... mponent/button.html
2、使用 open-data 展示用戶基本信息。 詳情參考文檔: https://developers.weixin.qq.com ... nent/open-data.html
微信為什么要調整接口?
開發者可以根據需要來調取用戶信息,而不是用戶首次進入小程序就彈出授權的彈框,這樣對於用戶來說是不友好的。比如可以在用戶點擊登錄的時候再獲取用戶信息,或者提交表單的時候等等,總之可以根據業務邏輯進行開發。
然而對於我們項目的業務邏輯卻是不好的事兒,因為我們需要在一開始就獲取用戶的信息入庫,相信很多人都會有這樣的需求,那就記錄一下我們項目的登錄。
首先自己寫一個彈框,觸發獲取信息的內容,微信小程序原生組件彈框沒有可以編輯的按鈕,所以需要我們自己來寫,如圖:
代碼如下:
<!-- 自定義彈框開始 --> <view wx:if="{{showModel}}" class="model"> <view class="modelTitle"> 獲取微信授權信息 </view> <view class="modelBody">微信登錄需要獲取您的用戶信息,請前往設置</view> <view class="btns"> <button open-type="getUserInfo" class="agree" bindgetuserinfo="agreeGetUser" lang="zh_CN">去設置</button> </view> </view> <view wx:if="{{showModel}}" class="mask"></view> <!-- 自定義彈框結束 -->
判斷是否授權,如果沒有授權,那么需要自定義彈框顯示,點擊“去設置”,然后彈出授權框;如果已經授權,邏輯上就應該不再彈出任何框,這里就需要把用戶首次進入小程序授權的用戶信息存在本地然后那來使用
// 登錄 wx.login({ success: res => { app.globalData.code = res.code //取出本地存儲用戶信息,解決需要每次進入小程序彈框獲取用戶信息 app.globalData.userInfo = wx.getStorageSync('userInfo') //wx.getuserinfo接口不再支持 wx.getSetting({ success: (res) => { //判斷用戶已經授權。不需要彈框 if(!res.authSetting['scope.userInfo']){ that.setData({ showModel: true }) }else{//沒有授權需要彈框 that.setData({ showModel: false }) wx.showLoading({ title: '加載中...' }) that.getOP(app.globalData.userInfo) } }, fail: function () { wx.showToast({ title: '系統提示:網絡錯誤', icon: 'warn', duration: 1500, }) } }) }, fail:function () { wx.showToast({ title:'系統提示:網絡錯誤', icon: 'warn', duration: 1500, }) } }) }, //獲取用戶信息新接口 agreeGetUser:function (e) { //設置用戶信息本地存儲 try { wx.setStorageSync('userInfo', e.detail.userInfo) } catch (e) { wx.showToast({ title: '系統提示:網絡錯誤', icon: 'warn', duration: 1500, }) } wx.showLoading({ title:'加載中...' }) let that = this that.setData({ showModel:false }) that.getOP(e.detail.userInfo) }, getOP: function (res) {//提交用戶信息 獲取用戶id let that = this let userInfo = res app.globalData.userInfo = userInfo wx.request({ url: 'https://xcx.xiancaijun.cn/tigerlogin/tgLogin', method: 'post', data: { "code": app.globalData.code, 'userInfo': userInfo }, success: function (res) { if(res.data.respcode == '0'){ app.globalData.userId = res.data.uid app.globalData.keys = res.data.keys app.globalData.access = res.data.access that.getBook() that.shareInfo() if (that.data.cid) { wx.navigateTo({ url: '/pages/course/course?cid=' + that.data.cid }) } }else if(res.data.respcode == '15'){ wx.hideLoading() wx.showToast({ title:'沒有授權,不能進入小程序', icon:'none', duration:2000 }) } } }) },
微信小程序獲取用戶信息接口的調整,有需要的開發者可以參考下