获取微信头像以及昵称

216 阅读1分钟

一、前提

自2022年10月25日后,小程序 wx.getUserProfile 接口 被收回,通过 wx.getUserInfo 接口获取用户头像将统一返回默认灰色头像,昵称将统一返回 “微信用户”。 image.png

二、解决

获取头像以及上传头像

button组件 open-type="chooseAvatar",当用户选择需要使用的头像之后,可以通过 @chooseavatar 事件回调获取到头像信息的临时路径。

<!-- #ifdef MP-WEIXIN -->
    <button class="button_tui" open-type="chooseAvatar" @chooseavatar="onChooseAvatar">
            <text class="text">注册</text>
    </button>
<!-- #endif -->

<!-- #ifdef APP-NVUE || H5 -->
    <view class="button_tui" @tap="doLogin()">
	<text class="text">注册</text>
	</view>
 <!-- #endif -->
 
 //-----------------------------------------------------------------------------
 	onChooseAvatar(e) {
const tempFilePath = e.detail.avatarUrl
const maxSizeInBytes = 5 * 1024 * 1024
//两个if判断是项目中需要可以去除
if (this.getJTest()) {
if (this.getJCode() && this.getJPass()) {
uni.getFileInfo({
    filePath: tempFilePath,
    success: res => {
    const fileSize = res.size
    if (fileSize > maxSizeInBytes) {
        uni.showToast({
           icon: 'none',
           title: '请上传小于5MB的图片'
        })
     return
    }
    this.avatarUrl = tempFilePath
    //上传到项目中
    uni.uploadFile({
        url: this.$store.getters.businessServerURL + '/cms/oss/uploadConsAvatarUrl', //后端接口url
        filePath: this.avatarUrl,
        name: 'file',
        // header: {
        // Authorization: `Bearer ${this.$store.getters.access_token}`
        // },
        success: res => {
            let fileRes = JSON.parse(res.data)
            console.log("获取地址", fileRes.code)
            if (fileRes.code == 0) {
            this.denlu();//调用注册的接口
        } else {
            uni.showToast({
                 icon: 'none',
                title: '注册失败,请稍后重试',
            })
            return
            }
        }
    })
}
})
}
}
},