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

微信授权登录

我们的项目开发有时候用到用户的一些信息,比如头像,昵称等。目前小程序为我们提供好了wx.getUserProfile方法以供获取用户信息,它的使用非常简单。

wx.getUserProfile方法获取用户信息

不推荐使用 wx.getUserInfo 获取用户信息,自2021年4月13日起,getUserInfo将不再弹出弹窗,并直接返回匿名的用户个人信息
2022年微信小程序授权登录的最新实现方案wx.getUserProfile_第1张图片
推荐使用 wx.getUserProfile 获取用户信息,开发者每次通过该接口获取用户个人信息均需用户确认。
对应的官方文档:https://developers.weixin.qq.com/miniprogram/dev/api/open-api/user-info/wx.getUserProfile.html
2022年微信小程序授权登录的最新实现方案wx.getUserProfile_第2张图片
简单示例代码
官网的示例代码写得较为复杂,这里我写了一些简单的代码,以便学习。


<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);
            }
        })
    }

})

2022年微信小程序授权登录的最新实现方案wx.getUserProfile_第3张图片
2022年微信小程序授权登录的最新实现方案wx.getUserProfile_第4张图片
2022年微信小程序授权登录的最新实现方案wx.getUserProfile_第5张图片

退出登录

由于上面用的判断是否登录,是用userInfo是否为空判断的,所以我们退出登录只要把userInfo清空就行了,就是这么简单粗暴!
2022年微信小程序授权登录的最新实现方案wx.getUserProfile_第6张图片
2022年微信小程序授权登录的最新实现方案wx.getUserProfile_第7张图片
2022年微信小程序授权登录的最新实现方案wx.getUserProfile_第8张图片

与本地缓存wx.setStorageSync结合使用

如果没有本地缓存,每次打开小程序都需要再授权一次,太麻烦了,而且本地缓存中的数据其他页面也能使用,不用重复获取。

完整代码


<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.login获取。

你可能感兴趣的:(小程序,前端,微信小程序,前端,小程序,javascript)