开启掘金成长之旅!这是我参与「掘金日新计划 · 12 月更文挑战」的第2天,点击查看活动详情
自 2022 年 10 月 25 日 24 时后(以下统称 “生效期” ),用户头像昵称获取规则将进行如下调整: 自生效期起,小程序 wx.getUserProfile 接口将被收回:生效期后发布的小程序新版本,通过 wx.getUserProfile 接口获取用户头像将统一返回默认灰色头像,昵称将统一返回 “微信用户”。生效期前发布的小程序版本不受影响,但如果要进行版本更新则需要进行适配。
背景
开发过微信小程序对接过微信小程序获取用户信息接口的开发者应该都清楚,小程序官方文档修改获取用户信息能力的方法是改了又改,这一次看到文档说明又有改动,将无法通过wx.getUesrProfile接口获取到当前小程序用户的昵称和头像了,想要获取头像昵称只能通过新的接口来获取。
使用方法
头像获取需要将button组件open-type 的值设置为 chooseAvatar,这样用户在点击获取头像时可以通过bindchooseavatar事件来获取到头像的临时路径。
昵称获取需要在input组件type值设置为nickname,当用户在此 input 进行输入时,键盘上方会展示微信昵称。
<view class="tl-card-1">
<view class="tl-height-100 border-bottom tl-font-32-333">
头像
<button class="tl-p-r tl-img-60" open-type="chooseAvatar" @chooseavatar="onChooseAvatar">
<image class="tl-img-60" :src="avatarUrl"></image>
</button>
</view>
<view class="tl-line-2"></view>
<view class="tl-height-100 tl-font-32-333">
昵称
<input type="nickname" maxlength="16" minlength="1" v-model="nickName" class="tl-p-r2" placeholder="请输入昵称" />
</view>
</view>
onChooseAvatar(e) {
this.avatarUrl = e.detail.avatarUrl
console.log('e.detail', e.detail.avatarUrl)
this.uploadFile();
},
这里是将微信头像获取临时路径,如果需要将获取到的图片保存到服务器上,还需要自己写一个上传文件和保存用户信息的方法。
uploadFile() {
uni.uploadFile({
url: this.action,//后台接口
filePath: this.avatarUrl,// 上传图片 url
name:'file',
header: {
'content-type': 'multipart/form-data',
'token': this.header.token
}, // header 值
success: res => {
let obj = JSON.parse(res.data)
this.avatarUrl = obj.data
},
fail: e => {
this.$refs.uToast.show({
title: `上传失败`
});
}
});
},