1.思路
微信小程序用微信授权登录的思路:官方在线文档
1.前端调用调uni.login() 获取临时登录凭证code ,并将获取的用户信息和code回传到后端;
2.后端调用 auth.code2Session 接口,换取 用户唯一标识 OpenID 、 用户在微信开放平台帐号下的唯一标识UnionID(若当前小程序已绑定到微信开放平台帐号) 和 会话密钥 session_key,然后后端根据openID和unionID生成特有的用户信息。
2.方法
因原有的方法获取的用户信息为灰度信息,及用户的信息包括头像、用户名等都不是用户的真实信息,getUserInfo改成getUserProfile接口。
<button v-if="canIUseGetUserProfile" @tap="getUserProfile" class="imgBox">
<image class="ImgL" src="/static/icon/wechat.png" mode="aspectFit">
</button>
<button v-else open-type="getUserInfo" @getuserinfo="getUserInfo" class="imgBox">
<image class="ImgL" src="/static/icon/wechat.png" mode="aspectFit">
</button>
data() {
return {
// 微信获取头像能力
canIUseGetUserProfile: false,
// 是否弹窗提示授权获取用户头像,防止频繁获取影响用户体验
isGetUserProfile: false,
};
},
onLoad() {
// 判断此用户微信登录是否成功过
if (uni.getStorageSync("isGetUserProfile") == true) {
this.isGetUserProfile = true
}
// #ifdef MP-WEIXIN
if (uni.getUserProfile) {
if (this.isGetUserProfile == true) {
this.canIUseGetUserProfile = false
} else {
this.canIUseGetUserProfile = true
}
}
// #endif
},
// #ifdef MP-WEIXIN
getUserProfile(e) {
if (this.isGetUserProfile == false) {
console.log("用于完善会员资料")
uni.getUserProfile({
desc: '用于完善会员资料', // 声明获取用户个人信息后的用途,后续会展示在弹窗中,请谨慎填写
success: (res) => {
console.log(res.userInfo) //用户基本信息(头像、个性签名等)
this.userInfo = res.userInfo
this.wxSilentLogin() // 具体登录操作,参照uni.login
}
})
}
},
// #endif