最新小程序授权+php后端(附demo源码)
参考博客:
1.小程序端
先看说明,原先的授权是通过按钮的开放能力open-type="getUserInfo"进行授权的,而现在的getUserProfile只能通过点击事件进行调用。我们直接通过按钮点击事件触发方法看一下结果。会看到关键信息都返回过来了,和getUserInfo一样所需要的关键变量encryptedData,iv也都在。那么由此可见,后端php代码基本可以不用改了。
我们直接改一下js文件和wxml文件就好。
index.js
//index.js //获取应用实例 const app = getApp() Page({ data: { motto: Hello World, userInfo: {}, hasUserInfo: false, canIUse:false, canIUseGetUserProfile: true }, //事件处理函数 bindViewTap: function () { wx.navigateTo({ url: ../logs/logs }) }, onLoad: function () { if (app.globalData.userInfo) { this.setData({ userInfo: app.globalData.userInfo, hasUserInfo: true }) } else if (this.data.canIUse) { // 由于 getUserInfo 是网络请求,可能会在 Page.onLoad 之后才返回 // 所以此处加入 callback 以防止这种情况 app.userInfoReadyCallback = res => { this.setData({ userInfo: res.userInfo, hasUserInfo: true }) } } else { console.log(1241); // 在没有 open-type=getUserInfo 版本的兼容处理 wx.getUserProfile({ desc: 用于完善会员资料, success: res => { app.globalData.userInfo = res.userInfo this.setData({ userInfo: res.userInfo, hasUserInfo: true }) } }) } }, getUserProfile: function () { wx.getUserProfile({ desc: 用于完善会员资料, success: e => { console.log("授权信息:",e); wx.login({ success(res) { if (res.code) { //发起网络请求 wx.request({ url: http://localhost:8080/tp5/public/wxlogin/Login/login, data: { encryptedData: e.encryptedData, iv: e.iv, code: res.code, }, success(res) { console.log(res.data); } }) } else { console.log(登录失败! + res.errMsg) } } }) app.globalData.userInfo = e.userInfo this.setData({ userInfo: e.userInfo, hasUserInfo: true }) } }) } })
index.wxml
<!--index.wxml--> <view class="container"> <view class="userinfo"> <block wx:if="{ {!hasUserInfo}}"> <button wx:if="{ {canIUseGetUserProfile}}" bindtap="getUserProfile"> 获取头像昵称 </button> <view wx:else> 请使用1.4.4及以上版本基础库 </view> </block> <block wx:else> <image bindtap="bindViewTap" class="userinfo-avatar" src="{ {userInfo.avatarUrl}}" mode="cover"></image> <text class="userinfo-nickname">{ {userInfo.nickName}}</text> </block> </view> <view class="usermotto"> <text class="user-motto">{ {motto}}</text> </view> </view>
我们开始奔放一下,成功。
tips:这里有个注意事项,新的授权登录接口getUserProfile不能获取到openId了。所以如果在操作过程中报错和openId有关,可以改这个地方。将 $save[openId] = &$userinfo[openId];替换成 $save[openId] = null; 如果没报错的话,那就不用管了
上一篇:
uniapp开发微信小程序-2.页面制作
下一篇:
微信小程序云开发配置