最近用uniapp开发小程序,整理了一下授权登录代码。如下:
<template>
<view class="container">
<view class="flex justify-center" style="width: 100vw;">
<image src="../../static/login_bg.png" mode="aspectFit"></image>
</view>
<view class="flex justify-center" style="margin-top: 100rpx;">
<view class="" style="width: 80vw;">
<view class="padding-bottom">申请获取以下权限</view>
<text class="text-gray">获得你的公开信息(昵称,头像等)</text>
</view>
</view>
<view class="flex flex-direction align-center padding-tb margin-top-xl">
<view class="cu-btn lg bg-gradual-purple radius" style="width: 80vw;height: 80rpx;" @click="loginBtn">
授权登录
</view>
<view class="cu-btn lg bg-gray radius margin-top" style="width: 80vw;height: 80rpx;" @click="naviToIndex">
暂不登录
</view>
</view>
</view>
</template>
<script>
export default {
data() {
return {
code:null
}
},
methods: {
async loginBtn(){
let that = this
//授权登录获取code
await uni.login({
provider: 'weixin',
onlyAuthorize:true,
success: function (loginRes) {
console.log(loginRes);
that.code = loginRes.code
}
});
// 获取用户信息,传给后台解析
await uni.getUserProfile({
desc: '实现登录功能,区分用户',
success: function (infoRes) {
console.log('获取到的用户信息1111:' + infoRes);
//调用后台接口
that.$api.userLogin({
encryptedData:infoRes.encryptedData,
iv:infoRes.iv,
signature:infoRes.signature,
code:that.code
}).then((res) => {
console.log('网络请求获取token',res)
if(res.data.code == '1000'){
uni.setStorageSync('userLoginStatus',1)
uni.setStorageSync('token',res.data.data)
uni.navigateBack({
delta: 2
});
}else{
uni.showToast({
title: res.data.msg,
icon: 'none'
});
}
});
},fail(err) {
console.log(err);
},complete(ret) {
console.log(ret);
}
});
},
naviToIndex(){
uni.redirectTo({
url:'/pages/index/index'
})
}
}
}
</script>
<style>
page{
background-color: #fff;
}
.container{
background-color: #fff;
}
</style>
自 2022 年 10 月 25 日 24 时后(以下统称 “生效期” ),用户头像昵称获取规则将进行如下调整:
自生效期起,小程序 wx.getUserProfile 接口将被收回:生效期后发布的小程序新版本,通过 wx.getUserProfile 接口获取用户头像将统一返回默认灰色头像,昵称将统一返回 “微信用户”。生效期前发布的小程序版本不受影响,但如果要进行版本更新则需要进行适配。
自生效期起,插件通过 wx.getUserInfo 接口获取用户昵称头像将被收回:生效期后发布的插件新版本,通过 wx.getUserInfo 接口获取用户头像将统一返回默认灰色头像,昵称将统一返回 “微信用户”。生效期前发布的插件版本不受影响,但如果要进行版本更新则需要进行适配。通过 wx.login 与 wx.getUserInfo 接口获取 openId、unionId 能力不受影响。
「头像昵称填写能力」支持获取用户头像昵称:如业务需获取用户头像昵称,可以使用「头像昵称填写能力」(基础库 2.21.2 版本开始支持),具体实践可见下方《最佳实践》。
小程序 wx.getUserProfile 与插件 wx.getUserInfo 接口兼容基础库 2.21.2 以下版本的头像昵称获取需求:上述「头像昵称填写能力」从基础库 2.21.2 版本开始支持(覆盖微信 8.0.16 以上版本)。对于来自更低版本的基础库与微信客户端的访问,小程序通过 wx.getUserProfile 接口将正常返回用户头像昵称,插件通过 wx.getUserInfo 接口将返回用户头像昵称,开发者可继续使用以上能力做向下兼容。
这些年个人信息安全问题越来越被重视,
微信小程序官方对于用户的隐私信息的授权获取方面的api也一直在调整。
从之前的宽松条件,现在逐渐紧缩严格。
作为开发者我们,也必须对项目进行相应的适配升级。
这一变化有利有弊。
比较好的方面是 外包的项目更新项目可以收维护费了;
不好的是如果维护的项目比较多,改起来还是比较耗费时间的。