以前小程序通过uni.getUserInfo可以直接拿到微信用户的头像和昵称,不过现在更改了。
自 2022 年 10 月 25 日 24 时后(以下统称 “生效期” ),用户头像昵称获取规则将进行如下调整:
1.小程序手机号授权登录
主要用到了button的open-type="getPhoneNumber" 获取手机号code 让后在调用uni.login获取登录所需要的code这样登录部分基本完成。
<template>
<view>
<view class="indexx">
<image src="../../static/login.png" mode="" class="images"></image>
</view>
<button class="btns" open-type="getPhoneNumber" @getphonenumber="getphonenumber">
<view class="">
微信手机号授权登录
</view>
</button>
</view>
</template>
<script>
import { getlogin } from '@/common/http.api.js'; //登录接口
export default {
data() {
return {
code:'',
nicknames:'',
avastars:'',
genders:'',
};
},
onLoad() {
},
methods: {
getphonenumber(e) {
let that = this
that.code = e.detail.code //获取code给后端后端拿code换手机号
uni.getUserInfo({
provider: 'weixin',
success: function (infoRes) {
that.nicknames = infoRes.userInfo.nickName
that.avastars = infoRes.userInfo.avatarUrl
that.log()
}
});
},
log(){
let that = this
uni.login({
provider: 'weixin',
success: function (loginRes) {
let params = {
phoneCode:that.code,
code:loginRes.code, //获取code给后端后端拿code获取token
nickName:that.nicknames,
headImg:that.avastars,
}
getlogin(params).then(res=>{
uni.setStorageSync('token',res.token)
uni.navigateBack()
})
}
});
},
},
}
</script>
2.小程序获取头像昵称
获取头像还是使用了 button的open-type="chooseAvatar" 直接拿到微信用户的头像。
<button :plain="true" class="btn_ads" open-type="chooseAvatar" @chooseavatar='chooseavatar'></button>
chooseavatar(e) {
let that = this
uni.uploadFile({
url:'', // 后台上传接口
filePath: e.detail.avatarUrl, // 上传图片 url
name: 'file',
header: {
'Content-Type': 'multipart/form-data',
'Authorization':uni.getStorageSync('token')
},
success(res) {
let img = JSON.parse(res.data).url
that.userInfo.headImg = img //赋值
}
});
}
获取微信昵称 用到input type='nickname'
<input v-model="userInfo.nickName" type="nickname" placeholder="请输入昵称" @change="getNickname"/>
getNickname(e){
this.userInfo.nickName = e.detail.value
},