微信小程序授权登录实现方案wx.getUserProfile(2022年最新版)

微信授权登录

我们的项目开发有时候用到用户的一些信息,比如头像,昵称等。目前小程序为我们提供好了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如果为空证明没有登录 -->
<button wx-if="{{!userInfo}}" bindtap="login">获取头像昵称</button>
<view wx:else class="userInfo">
 <image src="{{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如果为空证明没有登录 -->
<button wx-if="{{!userInfo}}" bindtap="login">获取头像昵称</button>
<view wx:else class="userInfo">
 <image src="{{userInfo.avatarUrl}}"></image>
 <text>{{userInfo.nickName}}</text>
 <button type="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原文地址:https://blog.csdn.net/qq_23073811/article/details/125832383

%s 个评论

要回复文章请先登录注册