目录 微信授权登录 wx.getUserProfile方法获取用户信息 退出登录 与本地缓存wx.setStorageSync结合使用 总结 补充:wx.getUserProfile已被回收 微信授权登录 我们的项目开发有时候用到用户的一些
目录
- 微信授权登录
- wx.getUserProfile方法获取用户信息
- 退出登录
- 与本地缓存wx.setStorageSync结合使用
- 总结
- 补充:wx.getUserProfile已被回收
微信授权登录
我们的项目开发有时候用到用户的一些信息,比如头像,昵称等。目前小程序为我们提供好了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 字段,只包含头像昵称,所以需要其他信息的需要结合云开发云函数使用
补充:wx.getUserProfile已被回收
wx真的是说改就改,之前就已经改过好几次了

调整原因:

获取用户头像昵称,可以使用「头像昵称填写能力」(基础库 2.21.2 版本开始支持,覆盖iOS与安卓微信 8.0.16 以上版本)
到此这篇关于微信小程序授权登录的最新实现方案的文章就介绍到这了,更多相关微信小程序授权登录内容请搜索易盾网络以前的文章或继续浏览下面的相关文章希望大家以后多多支持易盾网络!
