WxApp/page/component/user/user.js

177 lines
3.8 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

const app = getApp();
const baseUrl = app.globalData.baseUrl;
Page({
data: {
thumb: "", // 用户头像
nickname: "", // 用户昵称
orders: [], // 订单列表
hasAddress: false, // 是否有地址信息
address: {}, // 地址信息
},
onLoad() {
this.checkUserProfile(); // 检查并获取用户信息
/**
* 发起请求获取订单列表信息
*/
this.loadOrders(); // 加载订单列表
},
/**
* 检查本地缓存中是否有用户信息
*/
checkUserProfile() {
const userInfo = wx.getStorageSync('userInfo');
if (userInfo) {
// 如果有用户信息,直接设置数据
this.setData({
thumb: userInfo.userInfo.avatarUrl,
nickname: userInfo.userInfo.nickName,
});
} else {
// 没有用户信息,提示用户登录授权
wx.showModal({
title: '温馨提示',
content: '请先登录!',
showCancel: false,
success: (res) => {
if (res.confirm) {
this.getUserProfile();
}
}
});
}
},
/**
* 获取用户信息
*/
getUserProfile() {
wx.getUserProfile({
desc: "用于完善会员资料", // 这里必须声明用途
success: (userInfo) => {
// 存储用户信息到本地缓存中
wx.setStorageSync('userInfo', userInfo);
// 在页面中展示用户信息
this.setData({
thumb: userInfo.userInfo.avatarUrl,
nickname: userInfo.userInfo.nickName,
});
console.log('用户信息', userInfo);
},
fail: (err) => {
wx.showToast({
title: "用户拒绝了授权",
icon: "none",
});
console.log(err);
}
});
},
/**
* 微信登录
*/
wxLogin() {
wx.login({
success: (res) => {
if (res.code) {
console.log('微信登录成功code:', res.code);
// 可以将code发送到服务器进行登录验证
} else {
console.log('登录失败!' + res.errMsg);
}
}
});
},
/**
* 登录到服务器(可选,基于需求)
*/
loginToServer(code, userInfo) {
wx.request({
url: `${baseUrl}/login`, // 替换为你的服务器登录接口
method: 'POST',
data: {
code: code, // 微信登录凭证
avatar: userInfo.avatarUrl,
nickname: userInfo.nickName,
gender: userInfo.gender
},
success: (res) => {
if (res.data.code === 1) {
// 登录成功,保存服务器返回的 token
wx.setStorageSync('token', res.data.token);
// 其他登录后的初始化操作
}
},
fail: (err) => {
console.log('服务器登录失败', err);
}
});
},
/**
* 加载订单列表
*/
loadOrders() {
wx.request({
url: `${baseUrl}/order/loadData`,
method: "POST",
data: {
userId: 1, // 示例用户ID
},
success: (res) => {
this.setData({
orders: res.data,
});
},
fail: (err) => {
console.log('获取订单失败', err);
}
});
},
onShow() {
/**
* 获取本地缓存 地址信息
*/
wx.getStorage({
key: "address",
success: (res) => {
this.setData({
hasAddress: true,
address: res.data,
});
},
});
},
/**
* 发起支付请求
*/
payOrders() {
wx.requestPayment({
timeStamp: "String1",
nonceStr: "String2",
package: "String3",
signType: "MD5",
paySign: "String4",
success: (res) => {
console.log(res);
},
fail: (res) => {
wx.showModal({
title: "支付提示",
content: "<text>",
showCancel: false,
});
},
});
},
});