微信小程序获取用户信息接口调整目的以及使用方法介绍
微信小程序已经调整了获取用户信息的接口,还不知道的开发者看一下官网给出的理由和方法:javascript
为优化用户体验,使用 wx.getUserInfo 接口直接弹出受权框的开发方式将逐步再也不支持。从2018年4月30日开始,小程序与小游戏的体验版、开发版调用 wx.getUserInfo 接口,将没法弹出受权询问框,默认调用失败。正式版暂不受影响。开发者可以使用如下方式获取或展现用户信息:html
一、使用 button 组件,并将 open-type 指定为 getUserInfo 类型,获取用户基本信息。 详情参考文档: https://developers.weixin.qq.com ... mponent/button.html java
二、使用 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 }) } } }) },
微信小程序获取用户信息接口的调整,有须要的开发者能够参考下app