/user.wxml
<view class='container'>
<view class='portraitCon'>
<image src='../images/user/bg1.png' mode="widthFix" class='portraitBg'></image>
<view class='portraitGroup'>
<image src='{{avatarUrl}}' class='portrait'></image>
<view class='username'>{{nickname}}</view>
<button wx:if="{{show}}" class='getUserBtn' bindtap="getUserProfile">点击获取头像昵称</button>
</view>
</view>
<view class='settingCon'>
<view class='settingItem'>
{{weather}}
<switch color='#87c6ff' bindchange='switchChange'></switch>
</view>
<view class='settingItem'>
撰写攻略
<navigator url='../blog/blog'>
<image src="../images/arrow.png" mode="aspectFit"></image>
</navigator>
</view>
<view class='settingItem'>
更多信息
<icon type='info' size="20" color='#87c6ff'></icon>
</view>
</view>
</view>
/user.js
Page({
data: {
show: true,
avatarUrl: "../images/portrait.png",
nickname: "yourname",
weather: "获取天气"
},
onLoad: function(options) {
// 确保 wx.getUserProfile 可用
if (wx.getUserProfile) {
this.setData({
canIUseGetUserProfile: true
});
}
},
getUserProfile: function() {
wx.getUserProfile({
desc: '展示用户信息',
success: (res) => {
const { nickName, avatarUrl } = res.userInfo;
console.log('获取用户信息成功:', { nickName, avatarUrl });
this.setData({
nickname: nickName || "未设置昵称",
avatarUrl: avatarUrl,
show: false
});
},
fail: (err) => {
console.error("获取用户信息失败", err);
// 在这里添加一些提示或者处理逻辑,比如显示一个提示消息
wx.showToast({
title: '获取用户信息失败,请重试',
icon: 'none',
duration: 2000
});
}
});
},
switchChange: function(e) {
if (e.detail.value) {
wx.request({
url: 'https://apis.tianapi.com/tianqi/index?key=dfb7db809b2083a6fafaeb11c18e4bed&city=成都&type=1',
success: (res) => {
if (res.data && res.data.result) {
const { area, weather, real, wind } = res.data.result;
this.setData({
weather: `${area} ${weather} ${real} ${wind}`
});
} else {
console.error("Unexpected API response structure", res.data);
this.setData({
weather: "天气信息获取失败"
});
}
},
fail: (err) => {
console.error("API request failed", err);
this.setData({
weather: "天气信息获取失败"
});
}
});
}
},
onReady: function() {},
onShow: function() {},
onHide: function() {},
onUnload: function() {},
onPullDownRefresh: function() {},
onReachBottom: function() {},
onShareAppMessage: function() {}
});
wx.getUserProfile 接口有调整,目前已经不能获取用户微信头像和昵称,默认返回的是灰色头像和“微信用户”,也没有授权弹窗了(除了旧版本微信[基础库版本低于2.27.1]和接口调整生效期前发布的小程序版本外),参考公告:https://developers.weixin.qq.com/community/develop/doc/00022c683e8a80b29bed2142b56c01
当前如果有头像和昵称获取的需要,只能让用户自己填写:https://developers.weixin.qq.com/miniprogram/dev/framework/open-ability/userProfile.html
禁掉获取用户信息的功能都是咸丰年代的事情了
此时,你应该立即查看该接口的文档。然后立刻注意到文档首行红色字体。