在getUserProfile方法中获取到的信息还是虚拟的,是因为在模拟测试的原因吗,头像和微信名称获取不到当前账号的信息。
wxml文件:
<view class="container">
<block wx:if="{{isLoggedIn}}">
<view class="user-info">
<image src="{{userInfo.avatar_url}}" class="avatar"></image>
<text class="nickname">{{userInfo.nickname}}</text>
<text class="user-id">我的ID: {{userInfo.id}}</text>
</view>
<view class="partner-info" wx:if="{{partnerInfo}}">
<text class="section-title">我的伴侣</text>
<view class="partner-detail">
<image src="{{partnerInfo.avatar_url}}" class="partner-avatar"></image>
<text class="partner-name">{{partnerInfo.nickname}}</text>
</view>
</view>
<view class="action-buttons">
<button class="btn" wx:if="{{!partnerInfo}}" bindtap="bindPartner">绑定伴侣</button>
<button class="btn logout" bindtap="logout">退出登录</button>
</view>
</block>
<block wx:else>
<view class="login-container">
<image src="/images/logo.png" class="logo" mode="aspectFit"></image>
<text class="welcome-text">欢迎使用愿望池</text>
<button
wx:if="{{canIUseGetUserProfile}}"
class="btn login"
bindtap="getUserProfile"
>微信登录</button>
<button
wx:else
class="btn login"
open-type="getUserInfo"
bindgetuserinfo="onGetUserInfo"
>微信登录</button>
</view>
</block>
</view>
js文件:
const app = getApp();
const baseUrl = 'http://172.222.3.74:8083';
// 封装请求方法
const request = {
post: (url, data, token = '') => {
return new Promise((resolve, reject) => {
wx.request({
url: `${baseUrl}${url}`,
method: 'POST',
header: token ? { 'Authorization': `Bearer ${token}` } : {},
data,
success: (res) => resolve(res),
fail: (err) => reject(err)
});
});
},
get: (url, token) => {
return new Promise((resolve, reject) => {
wx.request({
url: `${baseUrl}${url}`,
header: { 'Authorization': `Bearer ${token}` },
success: (res) => resolve(res),
fail: (err) => reject(err)
});
});
},
put: (url, data, token) => {
return new Promise((resolve, reject) => {
wx.request({
url: `${baseUrl}${url}`,
method: 'PUT',
header: { 'Authorization': `Bearer ${token}` },
data,
success: (res) => resolve(res),
fail: (err) => reject(err)
});
});
}
};
Page({
data: {
isLoggedIn: false,
userInfo: null,
partnerInfo: null,
token: ''
},
onLoad: function() {
this.checkLoginStatus();
},
// 检查登录状态
checkLoginStatus: async function() {
const token = wx.getStorageSync('token');
const userInfo = wx.getStorageSync('userInfo');
//判断token和userInfo是否已经获取到
if (token && userInfo) {
this.setData({
isLoggedIn: true,
userInfo,
token
});
await this.getPartnerInfo();
return;
}
// 检查是否支持 getUserProfile
if (wx.getUserProfile) {
this.setData({
canIUseGetUserProfile: true
});
}
},
// 使用 getUserProfile 获取用户信息
getUserProfile: function() {
wx.getUserProfile({
desc: '用于完善会员资料',
lang: 'zh_CN',
success: async (userInfoResult) => {
try {
// 获取 code
const loginResult = await wx.login();
if (!loginResult.code) {
throw new Error('获取用户code失败');
}
console.log("用户信息:", userInfoResult);
// 调用服务端获取 token 接口
const codeRes = await request.post('/users/developer/code', {
code: loginResult.code
});
if (codeRes.statusCode !== 200 || !codeRes.data.token) {
throw new Error('获取token失败');
}
const token = codeRes.data.token;
// 获取手机号加密值
const phoneRes = await wx.getPhoneNumber({
success: (phoneInfo) => phoneInfo,
fail: () => { throw new Error('获取手机号失败'); }
});
// 调用服务端登录接口
const loginRes = await request.post('/users/developer/login', {
token,
userInfo: {
nickName: userInfoResult.userInfo.nickName,
avatarUrl: userInfoResult.userInfo.avatarUrl,
gender: userInfoResult.userInfo.gender,
country: userInfoResult.userInfo.country,
province: userInfoResult.userInfo.province,
city: userInfoResult.userInfo.city,
language: userInfoResult.userInfo.language
},
rawData: userInfoResult.rawData,
signature: userInfoResult.signature,
encryptedData: userInfoResult.encryptedData,
iv: userInfoResult.iv,
phoneEncryptedData: phoneRes.encryptedData,
phoneIv: phoneRes.iv
});
if (loginRes.statusCode === 200 && loginRes.data) {
this.handleLoginSuccess({
token: loginRes.data.token,
userInfo: loginRes.data.userInfo
});
} else {
throw new Error('登录失败');
}
} catch (error) {
console.error('登录失败:', error);
wx.showToast({
title: error.message || '登录失败',
icon: 'none'
});
}
},
fail: (error) => {
console.error('获取用户信息失败:', error);
wx.showToast({
title: '获取用户信息失败',
icon: 'none'
});
}
});
},
// 处理用户信息授权(兼容旧版本)
onGetUserInfo: function(e) {
if (e.detail.userInfo) {
this.login(e.detail.userInfo);
} else {
wx.showToast({
title: '需要授权才能使用',
icon: 'none'
});
}
},
// 登录流程
login: async function(userInfo) {
try {
const { code } = await wx.login();
if (!code) {
throw new Error('获取用户code失败');
}
const loginRes = await request.post('/users/developer/login', {
code,
userInfo
});
if (loginRes.statusCode === 200 && loginRes.data) {
this.handleLoginSuccess({
token: loginRes.data.token,
userInfo: loginRes.data.userInfo
});
} else {
throw new Error('登录失败');
}
} catch (error) {
console.error('登录失败:', error);
wx.showToast({
title: error.message || '登录失败',
icon: 'none'
});
}
},
// 处理登录成功
handleLoginSuccess: function(data) {
wx.setStorageSync('token', data.token);
wx.setStorageSync('userInfo', data.userInfo);
this.setData({
isLoggedIn: true,
userInfo: data.userInfo,
token: data.token
});
this.getPartnerInfo();
},
// 获取伴侣信息
getPartnerInfo: async function() {
if (!this.data.userInfo?.partnerId) return;
try {
const res = await request.get(
`/users/${this.data.userInfo.partner_id}`,
this.data.token
);
this.setData({ partnerInfo: res.data });
} catch (error) {
console.error('获取伴侣信息失败:', error);
}
},
// 退出登录
logout: function() {
wx.removeStorageSync('token');
wx.removeStorageSync('userInfo');
this.setData({
isLoggedIn: false,
userInfo: null,
partnerInfo: null,
token: ''
});
},
// 绑定伴侣
bindPartner: async function() {
try {
const res = await new Promise((resolve) => {
wx.showModal({
title: '绑定伴侣',
content: '请输入伴侣ID',
editable: true,
success: (res) => resolve(res)
});
});
if (!res.confirm || !res.content) return;
const updateRes = await request.put(
`/users/${this.data.userInfo.id}`,
{ partner_id: res.content },
this.data.token
);
if (updateRes.data) {
wx.showToast({ title: '绑定成功', icon: 'success' });
this.setData({ userInfo: updateRes.data });
wx.setStorageSync('userInfo', updateRes.data);
await this.getPartnerInfo();
} else {
throw new Error('绑定失败');
}
} catch (error) {
console.error('绑定伴侣失败:', error);
wx.showToast({
title: error.message || '绑定失败',
icon: 'none'
});
}
}
});
刺激不,小程序一年不开发,包你懵逼。一个用户头像昵称改了一百八十遍api,然后隐私协议+弹窗又搞了一百八十遍,后面订单又要求上传订单页面路径,用个定位要申请,申请完了还要写到隐私协议,这些都不致命,致命的是你不知道在哪看文档 [dog],后面有要求短链URL schema 一人一链,第一个人访问过就会过期,又要去整改,等你改完,又发公告说一人一链取消,我们又可以用啦,哦耶,天才。
改版了,看看公告吧https://developers.weixin.qq.com/community/develop/doc/00022c683e8a80b29bed2142b56c01,请使用头像昵称填写功能https://developers.weixin.qq.com/miniprogram/dev/framework/open-ability/userProfile.html
又一个两年没开发过小程序的
https://developers.weixin.qq.com/miniprogram/dev/framework/open-ability/userProfile.html
建议认真看文档,这个接口目前本来就不能获得用户的昵称和头像。有此类需求,需使用”头像昵称填写”组件,可参考https://developers.weixin.qq.com/miniprogram/dev/framework/open-ability/userProfile.html
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