Browse Source

修复客服列表网络请求和位置信息写入数据库问题

pull/1/head
SwTt29 2 months ago
parent
commit
e0618ebe3b
  1. BIN
      images/轮播图1.jpg
  2. BIN
      images/轮播图2.jpg
  3. BIN
      images/轮播图3.jpg
  4. 234
      pages/profile/index.js
  5. 3174
      server-example/server-mysql.js

BIN
images/轮播图1.jpg

Binary file not shown.

Before

Width:  |  Height:  |  Size: 11 KiB

BIN
images/轮播图2.jpg

Binary file not shown.

Before

Width:  |  Height:  |  Size: 7.8 MiB

BIN
images/轮播图3.jpg

Binary file not shown.

Before

Width:  |  Height:  |  Size: 11 KiB

234
pages/profile/index.js

@ -32,14 +32,14 @@ Page({
loadUserInfo() {
console.log('开始加载用户信息')
const app = getApp()
// 从本地存储获取用户信息
const localUserInfo = wx.getStorageSync('userInfo') || {}
if (app.globalData.userInfo) {
this.setData({ userInfo: app.globalData.userInfo })
} else {
app.globalData.userInfo = localUserInfo
this.setData({
this.setData({
userInfo: localUserInfo,
needPhoneAuth: !localUserInfo.phoneNumber
})
@ -53,7 +53,7 @@ Page({
if (userId && openid) {
// 从服务器获取最新的用户信息,确保身份由数据库决定
this.refreshUserInfoFromServer(openid, userId)
// 确保users存储结构存在
let users = wx.getStorageSync('users')
if (!users) {
@ -111,7 +111,7 @@ Page({
// 始终根据当前用户类型显示对应的身份标签
if (userType && userType !== '') {
let identityLabel = '身份:not_set'
switch (userType) {
case 'buyer': identityLabel = '身份:买家'; break
case 'seller': identityLabel = '身份:卖家'; break
@ -129,29 +129,29 @@ Page({
// 从服务器刷新用户信息并同步身份数据
refreshUserInfoFromServer(openid, userId) {
const API = require('../../utils/api.js')
API.getUserInfo(openid).then(res => {
console.log('从服务器获取用户信息成功:', res)
if (res.success && res.data) {
const serverUserInfo = res.data
// 更新本地用户信息
const app = getApp()
const updatedUserInfo = {
...app.globalData.userInfo,
...serverUserInfo
}
app.globalData.userInfo = updatedUserInfo
wx.setStorageSync('userInfo', updatedUserInfo)
this.setData({ userInfo: updatedUserInfo })
// 同步更新用户身份信息(当前身份由数据库决定)
if (serverUserInfo.type) {
this.syncUserTypeFromServer(userId, serverUserInfo.type)
}
console.log('用户信息已更新,昵称:', updatedUserInfo.name, '手机号:', updatedUserInfo.phoneNumber, '身份:', serverUserInfo.type)
}
}).catch(err => {
@ -159,26 +159,26 @@ Page({
// 如果getUserInfo失败,尝试使用validateUserLogin作为备选
API.validateUserLogin().then(res => {
console.log('使用validateUserLogin获取用户信息成功:', res)
if (res.success && res.data) {
const serverUserInfo = res.data
// 更新本地用户信息
const app = getApp()
const updatedUserInfo = {
...app.globalData.userInfo,
...serverUserInfo
}
app.globalData.userInfo = updatedUserInfo
wx.setStorageSync('userInfo', updatedUserInfo)
this.setData({ userInfo: updatedUserInfo })
// 同步更新用户身份信息(当前身份由数据库决定)
if (serverUserInfo.type) {
this.syncUserTypeFromServer(userId, serverUserInfo.type)
}
console.log('用户信息已更新(备选方案):', updatedUserInfo)
}
}).catch(validateErr => {
@ -194,40 +194,40 @@ Page({
console.error('同步用户身份信息失败: 参数不完整')
return
}
console.log('从服务器同步用户身份信息:', { userId, serverType })
// 更新本地存储的用户身份
let users = wx.getStorageSync('users') || {}
if (!users[userId]) {
users[userId] = {}
}
// 移除serverType中的customer(如果存在)
let processedServerType = serverType.replace(/,?customer/g, '').replace(/^,|,$/g, '')
// 构建新的用户类型
let newUserType = processedServerType
// 只有当新构建的用户类型与本地不同时才更新
if (users[userId].type !== newUserType) {
users[userId].type = newUserType
wx.setStorageSync('users', users)
// 更新全局用户类型
const app = getApp()
app.globalData.userType = newUserType
// 更新页面显示的用户类型
this.setData({
userType: this.formatUserType(newUserType)
this.setData({
userType: this.formatUserType(newUserType)
})
console.log('用户身份已从服务器同步并保留客服标识:', newUserType)
} else {
console.log('用户身份与服务器一致,无需更新:', newUserType)
}
// 更新用户标签,确保传入正确的参数
this.updateUserTags(userId, newUserType)
},
@ -272,16 +272,16 @@ Page({
// 使用API更新用户类型,确保与服务器同步
API.updateUserType(newType).then(res => {
console.log('用户类型更新成功:', res)
// 更新页面显示
const app = getApp()
this.setData({
userType: this.formatUserType(app.globalData.userType)
this.setData({
userType: this.formatUserType(app.globalData.userType)
})
// 更新用户标签
this.updateUserTags(userId, app.globalData.userType)
wx.showToast({
title: `Switched to ${typeName}`,
icon: 'success',
@ -328,27 +328,27 @@ Page({
// 处理手机号授权结果
async onPhoneNumberResult(e) {
console.log('手机号授权结果:', e)
// 首先检查用户是否拒绝授权
if (e.detail.errMsg !== 'getPhoneNumber:ok') {
console.log('用户拒绝授权手机号')
wx.showToast({
title: '您已拒绝授权,操作已取消',
icon: 'none'
wx.showToast({
title: '您已拒绝授权,操作已取消',
icon: 'none'
})
// 直接返回,取消所有后续操作
return
}
wx.showLoading({
title: '登录中...',
mask: true
wx.showLoading({
title: '登录中...',
mask: true
})
try {
// 引入API服务
const API = require('../../utils/api.js')
// 1. 先执行微信登录获取code
const loginRes = await new Promise((resolve, reject) => {
wx.login({
@ -356,28 +356,28 @@ Page({
fail: reject
})
})
if (!loginRes.code) {
throw new Error('获取登录code失败')
}
console.log('获取登录code成功:', loginRes.code)
// 2. 使用code换取openid
const openidRes = await API.getOpenid(loginRes.code)
// 增强版响应处理逻辑,支持多种返回格式
let openid = null;
let userId = null;
let sessionKey = null;
// 优先从data字段获取数据
if (openidRes && openidRes.data && typeof openidRes.data === 'object') {
openid = openidRes.data.openid || openidRes.data.OpenID || null;
userId = openidRes.data.userId || openidRes.data.userid || null;
sessionKey = openidRes.data.session_key || openidRes.data.sessionKey || null;
}
// 如果data为空或不存在,尝试从响应对象直接获取
if (!openid && openidRes && typeof openidRes === 'object') {
console.warn('服务器返回格式可能不符合预期,data字段为空或不存在,但尝试从根对象提取信息:', openidRes);
@ -385,20 +385,20 @@ Page({
userId = openidRes.userId || openidRes.userid || null;
sessionKey = openidRes.session_key || openidRes.sessionKey || null;
}
// 检查服务器状态信息
const isSuccess = openidRes && (openidRes.success === true || openidRes.code === 200);
if (!openid) {
throw new Error('获取openid失败: ' + (openidRes && openidRes.message ? openidRes.message : '未知错误'))
}
// 存储openid和session_key
wx.setStorageSync('openid', openid)
if (sessionKey) {
wx.setStorageSync('sessionKey', sessionKey)
}
// 确保始终使用从服务器获取的正式用户ID,不再生成临时ID
if (userId) {
wx.setStorageSync('userId', userId)
@ -413,19 +413,19 @@ Page({
console.warn('未找到有效的用户ID,请确保用户已授权登录');
}
}
console.log('获取openid成功并存储:', openid)
// 3. 上传手机号加密数据到服务器解密
const phoneData = {
...e.detail,
openid: openid,
sessionKey: sessionKey || ''
}
console.log('准备上传手机号加密数据到服务器')
const phoneRes = await API.uploadPhoneNumberData(phoneData)
// 改进手机号解密结果的处理逻辑
if (!phoneRes || (!phoneRes.success && !phoneRes.phoneNumber)) {
// 如果服务器返回格式不标准但包含手机号,也接受
@ -433,18 +433,18 @@ Page({
throw new Error('获取手机号失败: ' + (phoneRes && phoneRes.message ? phoneRes.message : '未知错误'))
}
}
// 检查是否有手机号冲突
const hasPhoneConflict = phoneRes.phoneNumberConflict || false
const isNewPhone = phoneRes.isNewPhone || true
const phoneNumber = phoneRes.phoneNumber || null
console.log('手机号解密结果:', {
phoneNumber: phoneNumber,
hasPhoneConflict: hasPhoneConflict,
isNewPhone: isNewPhone
})
// 4. 获取用户微信名称和头像
let userProfile = null;
try {
@ -460,7 +460,7 @@ Page({
console.warn('获取用户信息失败:', err);
// 如果获取失败,使用默认值
}
// 5. 创建用户信息
const app = getApp()
const existingUserInfo = app.globalData.userInfo || wx.getStorageSync('userInfo') || {}
@ -475,36 +475,36 @@ Page({
language: (userProfile ? userProfile.userInfo.language : existingUserInfo.language) || 'zh_CN',
phoneNumber: phoneNumber
}
// 6. 获取用户类型
const users = wx.getStorageSync('users') || {}
let currentUserType = users[userId] && users[userId].type ? users[userId].type : ''
// 如果没有用户类型,尝试从全局获取
if (!currentUserType) {
currentUserType = app.globalData.userType || ''
}
// 7. 保存用户信息并等待上传完成
console.log('开始保存用户信息并上传到服务器...')
await this.uploadUserInfoToServer(userInfo, userId, currentUserType)
console.log('用户信息保存并上传完成')
// 更新本地和全局用户信息
app.globalData.userInfo = userInfo
wx.setStorageSync('userInfo', userInfo)
// 更新页面状态
this.setData({
needPhoneAuth: false,
userInfo: userInfo
})
// 重新加载用户信息以更新UI
this.loadUserInfo()
wx.hideLoading()
// 根据服务器返回的结果显示不同的提示
if (hasPhoneConflict) {
wx.showModal({
@ -538,11 +538,11 @@ Page({
}
});
}
} catch (error) {
wx.hideLoading()
console.error('登录过程中发生错误:', error)
// 更具体的错误提示
let errorMsg = '登录失败,请重试'
if (error.message.includes('网络')) {
@ -554,13 +554,13 @@ Page({
} else if (error.message.includes('手机号')) {
errorMsg = '获取手机号失败,请重试'
}
wx.showToast({
title: errorMsg,
icon: 'none',
duration: 3000
})
// 清除可能已经保存的不完整信息
try {
wx.removeStorageSync('openid')
@ -582,7 +582,7 @@ Page({
// 获取openid
const openid = wx.getStorageSync('openid')
// 验证必要参数
if (!userId || !openid) {
const error = new Error('缺少必要的用户信息');
@ -620,7 +620,7 @@ Page({
// 修改用户名称
onEditName() {
const currentName = this.data.userInfo.name || '未登录';
wx.showModal({
title: '修改用户名称',
editable: true,
@ -632,7 +632,7 @@ Page({
// 移除首尾空格并过滤多余空格
let newName = res.content.trim();
newName = newName.replace(/\s+/g, ' ');
// 验证昵称不能为空
if (!newName) {
wx.showToast({
@ -642,7 +642,7 @@ Page({
});
return;
}
// 验证昵称长度
if (newName.length > 10) {
wx.showToast({
@ -652,7 +652,7 @@ Page({
});
return;
}
// 检查名称是否变化
if (newName === currentName) {
wx.showToast({
@ -662,13 +662,13 @@ Page({
});
return;
}
// 显示加载提示
wx.showLoading({
title: '正在更新...',
mask: true
});
// 更新用户信息
this.updateName(newName).finally(() => {
// 无论成功失败,都隐藏加载提示
@ -678,7 +678,7 @@ Page({
}
});
},
// 检查位置授权状态
checkLocationAuth() {
const that = this;
@ -753,7 +753,7 @@ Page({
// 获取用户当前位置
getUserLocation() {
const that = this;
// 先检查位置授权状态
wx.getSetting({
success(res) {
@ -767,27 +767,79 @@ Page({
const longitude = res.longitude;
// 调用逆地理编码API获取详细地址
that.reverseGeocode(latitude, longitude);
// 将位置信息存储到本地
wx.setStorageSync('userLocation', { latitude, longitude });
// 立即将位置数据上传到数据库users表的authorized_region字段
const locationData = {
latitude: latitude,
longitude: longitude
};
// 构造上传的数据,包含authorized_region字段
const userInfo = {
// 构造上传的数据,包含authorized_region字段和必要的phoneNumber
let userInfo = {
authorized_region: JSON.stringify(locationData) // 将位置数据转换为JSON字符串存储
};
// 确保包含phoneNumber字段(服务器接口要求)
let phoneNumber = wx.getStorageSync('phoneNumber');
if (!phoneNumber) {
// 尝试从用户信息中获取phoneNumber
const globalUserInfo = wx.getStorageSync('userInfo');
phoneNumber = globalUserInfo?.phoneNumber;
}
// 如果找到phoneNumber,添加到上传数据中
if (phoneNumber) {
userInfo.phoneNumber = phoneNumber;
} else {
console.warn('位置上传警告: 未找到phoneNumber,可能导致上传失败');
}
// 检查openid是否存在
let openid = wx.getStorageSync('openid');
if (!openid) {
// 尝试从用户信息中获取openid
const globalUserInfo = wx.getStorageSync('userInfo');
openid = globalUserInfo?.openid;
}
// 确保openid存在
if (!openid) {
console.error('位置上传失败: 未找到openid');
wx.showToast({
title: '位置上传失败,请先登录',
icon: 'none',
duration: 2000
});
return;
}
console.log('位置上传前检查openid:', openid);
console.log('准备上传的位置数据:', userInfo);
// 调用API上传位置数据
const api = require('../../utils/api.js');
api.uploadUserInfo(userInfo).then(res => {
api.uploadUserInfo({
...userInfo,
openid: openid // 明确传递openid
}).then(res => {
console.log('位置数据上传成功:', res);
// 显示上传成功提示
wx.showToast({
title: '位置更新成功',
icon: 'success',
duration: 1500
});
}).catch(err => {
console.error('位置数据上传失败:', err);
// 显示上传失败提示
wx.showToast({
title: '位置上传失败',
icon: 'none',
duration: 2000
});
});
},
fail() {
@ -845,20 +897,20 @@ Page({
...this.data.userInfo,
name: newName
};
// 保存到本地存储和全局状态
app.globalData.userInfo = updatedUserInfo;
wx.setStorageSync('userInfo', updatedUserInfo);
// 更新页面显示
this.setData({
userInfo: updatedUserInfo
});
// 更新服务器信息
const userId = wx.getStorageSync('userId');
const currentUserType = this.data.userType;
// 如果有用户ID,则上传到服务器
if (userId) {
// 使用Promise链处理上传

3174
server-example/server-mysql.js

File diff suppressed because it is too large
Loading…
Cancel
Save