微信授权登录
我们的项目开发有时候用到用户的一些信息,比如头像,昵称等。目前小程序为我们提供好了
wx.getUserProfile
方法以供获取用户信息,它的使用非常简单。
wx.getUserProfile方法获取用户信息
不推荐使用
wx.getUserInfo
获取用户信息,自2021年4月13日起,
getUserInfo
将不再弹出弹窗,并直接返回匿名的用户个人信息
推荐使用
wx.getUserProfile
获取用户信息,开发者每次通过该接口获取用户个人信息均需用户确认。
对应的官方文档:https://developers.weixin.qq.com/miniprogram/dev/api/open-api/user-info/wx.getUserProfile.html
简单示例代码:
官网的示例代码写得较为复杂,这里我写了一些简单的代码,以便学习。
<!-- userInfo如果为空证明没有登录 --><buttonwx-if="{{!userInfo}}"bindtap="login">获取头像昵称</button><viewwx:elseclass="userInfo"><imagesrc="{{userInfo.avatarUrl}}"></image><text>{{userInfo.nickName}}</text></view>
.userInfo{display: flex;flex-direction: column;align-items: center;}.userInfo image{width: 200rpx;height: 200rpx;border-radius: 200rpx;}
Page({data:{userInfo:'',//用于存放获取的用户信息},login(){
wx.getUserProfile({desc:'必须授权才能继续使用',// 必填 声明获取用户个人信息后的用途,后续会展示在弹窗中success:(res)=>{
console.log('授权成功', res);this.setData({userInfo:res.userInfo
})},fail:(err)=>{
console.log('授权失败', err);}})}})
退出登录
由于上面用的判断是否登录,是用userInfo是否为空判断的,所以我们退出登录只要把userInfo清空就行了,就是这么简单粗暴!
与本地缓存wx.setStorageSync结合使用
如果没有本地缓存,每次打开小程序都需要再授权一次,太麻烦了,而且本地缓存中的数据其他页面也能使用,不用重复获取。
完整代码:
<!-- userInfo如果为空证明没有登录 --><buttonwx-if="{{!userInfo}}"bindtap="login">获取头像昵称</button><viewwx:elseclass="userInfo"><imagesrc="{{userInfo.avatarUrl}}"></image><text>{{userInfo.nickName}}</text><buttontype="warn"bindtap="loginOut">退出登录</button></view>
Page({data:{userInfo:'',//用于存放获取的用户信息},onLoad(){let user = wx.getStorageSync('user')this.setData({userInfo: user
})},// 授权登录login(){
wx.getUserProfile({desc:'必须授权才能继续使用',// 必填 声明获取用户个人信息后的用途,后续会展示在弹窗中success:(res)=>{
console.log('授权成功', res);
wx.setStorageSync('user',res.userInfo)this.setData({userInfo:res.userInfo
})},fail:(err)=>{
console.log('授权失败', err);}})},// 退出登录loginOut(){this.setData({userInfo:''})// 清空缓存
wx.setStorageSync('user',null)}})
总结
wx.getUserProfile
用于授权登录,获取用户信息,但它返回的加密数据中不包含
openId
和
unionId
字段,只包含头像昵称,所以需要其他信息的需要结合云开发云函数使用
版权归原作者 coderYYY 所有, 如有侵权,请联系我们删除。