Mini-Program Avatar and Nickname Retrieval
·
2 min read
Recently, while working on mini-programs, I discovered changes in how WeChat mini-programs retrieve user avatars and nicknames. Of course, the official documentation can easily mislead people. Here I’ll mark the current solution.
The current solution is as follows:
wx.getUserProfile - Server-side Decryption to Get User Information
Note: wx.getUserProfile no longer shows authorization popup, but will normally retrieve encrypted_data/code/iv information. The userinfo in the message body is only for compatibility with older versions, do not use it.
Mini-program Side Support for User Modifying Avatar/Nickname Information
1. Avatar Retrieval
Use <button open-type="chooseAvatar">
to let users actively select avatars:
<!-- wxml -->
<button class="avatar-wrapper" open-type="chooseAvatar" bind:chooseavatar="onChooseAvatar">
<image class="avatar" src="{{avatarUrl || '/images/default-avatar.png'}}"></image>
</button>
// js
Page({
data: {
avatarUrl: ''
},
onChooseAvatar(e) {
const { avatarUrl } = e.detail
this.setData({
avatarUrl: avatarUrl
})
// Optional: upload to server
this.uploadAvatar(avatarUrl)
},
uploadAvatar(tempFilePath) {
wx.uploadFile({
url: 'https://your-server.com/upload',
filePath: tempFilePath,
name: 'avatar',
success: (res) => {
console.log('Avatar upload successful', res)
}
})
}
})
2. Nickname Retrieval
Use <input type="nickname">
to let users input nicknames:
<!-- wxml -->
<form bindsubmit="onSubmit">
<input
type="nickname"
class="weui-input"
placeholder="Please enter nickname"
value="{{nickname}}"
bindinput="onNicknameInput"
/>
<button formType="submit">Save</button>
</form>
// js
Page({
data: {
nickname: ''
},
onNicknameInput(e) {
this.setData({
nickname: e.detail.value
})
},
onSubmit(e) {
const { nickname } = e.detail.value
if (!nickname.trim()) {
wx.showToast({
title: 'Please enter nickname',
icon: 'none'
})
return
}
this.saveUserInfo(nickname)
},
saveUserInfo(nickname) {
// Save to local storage or server
wx.setStorageSync('nickname', nickname)
wx.showToast({
title: 'Save successful'
})
}
})
Final Thoughts
WeChat mini-program documentation is still as terrible as ever. We can only be disgusted while using it. Take care.