From 469b7a115e63eec96ef6becfebd17962c0db2286 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=BE=90=E9=A3=9E=E6=B4=8B?= <15778543+xufeiyang6017@user.noreply.gitee.com> Date: Mon, 8 Dec 2025 09:49:49 +0800 Subject: [PATCH] =?UTF-8?q?=E4=BF=AE=E5=A4=8D=E4=B8=AA=E4=BA=BA=E9=A1=B5?= =?UTF-8?q?=E9=9D=A2=E7=99=BB=E5=BD=95=E9=80=BB=E8=BE=91=EF=BC=8C=E7=A1=AE?= =?UTF-8?q?=E4=BF=9D=E4=B8=80=E6=AC=A1=E7=99=BB=E5=BD=95=E6=88=90=E5=8A=9F?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- pages/profile/index.js | 378 ++++++++++++++++++++++------------------- 1 file changed, 203 insertions(+), 175 deletions(-) diff --git a/pages/profile/index.js b/pages/profile/index.js index 0e5d1bf..cd174dc 100644 --- a/pages/profile/index.js +++ b/pages/profile/index.js @@ -315,7 +315,7 @@ Page({ }) }, // 处理手机号授权结果 - onPhoneNumberResult(e) { + async onPhoneNumberResult(e) { console.log('手机号授权结果:', e) // 首先检查用户是否拒绝授权 @@ -329,183 +329,211 @@ Page({ return } - // 用户同意授权,继续执行后续操作 - // 检查是否有openid,如果没有则先登录 - const openid = wx.getStorageSync('openid') - if (!openid) { - console.log('未登录,执行登录流程') - // 显示登录loading提示 - wx.showLoading({ title: '登录中...' }) - // 调用微信登录接口 - wx.login({ - success: loginRes => { - if (loginRes.code) { - // 引入API服务 - const API = require('../../utils/api.js') - // 获取openid - API.getOpenid(loginRes.code) - .then(openidRes => { - wx.hideLoading() - console.log('获取openid响应:', openidRes) - - // 增强版响应处理逻辑,支持多种返回格式 - 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); - openid = openidRes.openid || openidRes.OpenID || null; - userId = openidRes.userId || openidRes.userid || null; - sessionKey = openidRes.session_key || openidRes.sessionKey || null; - } - - // 检查服务器状态信息 - const isSuccess = openidRes && (openidRes.success === true || openidRes.code === 200); - - if (openid) { - // 存储openid和session_key - wx.setStorageSync('openid', openid) - if (sessionKey) { - wx.setStorageSync('sessionKey', sessionKey) - } - - // 如果有userId,也存储起来 - if (userId) { - wx.setStorageSync('userId', userId) - } - - console.log('获取openid成功并存储:', openid) - - // 登录成功,显示提示并重新加载页面 - wx.showToast({ - title: '登录成功', - icon: 'none' - }) - - // 在登录成功后重新加载页面 - wx.reLaunch({ - url: '/pages/profile/index' - }) - } else { - console.error('获取openid失败,响应数据:', openidRes) - wx.showToast({ - title: '登录失败,请重试', - icon: 'none' - }) - } - }) - .catch(err => { - wx.hideLoading() - console.error('获取openid失败:', err) - wx.showToast({ - title: '登录失败,请重试', - icon: 'none' - }) - }) - } else { - wx.hideLoading() - console.error('微信登录失败:', loginRes) - wx.showToast({ - title: '登录失败,请重试', - icon: 'none' - }) - } - }, - fail: err => { - wx.hideLoading() - console.error('wx.login失败:', err) - wx.showToast({ - title: '获取登录状态失败,操作已取消', - icon: 'none' - }) - } - }) - return - } + wx.showLoading({ + title: '登录中...', + mask: true + }) - // 已登录且用户同意授权,获取加密数据 - const phoneData = e.detail - - wx.showLoading({ title: '获取手机号中...' }) - - // 引入API服务 - const API = require('../../utils/api.js') - - // 上传到服务器解密 - API.uploadPhoneNumberData(phoneData) - .then(res => { - wx.hideLoading() - if (res.success) { - console.log('获取手机号结果:', res) - - // 检查是否有手机号冲突 - const hasPhoneConflict = res.phoneNumberConflict || false - const isNewPhone = res.isNewPhone || true - const phoneNumber = res.phoneNumber || null - - // 如果有手机号冲突,直接提示用户 - if (hasPhoneConflict) { - wx.showToast({ - title: '手机号已被其他账号绑定,请更换账号后重试', - icon: 'none', - duration: 3000 - }) - } else if (phoneNumber) { - // 保存手机号到用户信息 - const app = getApp() - const userInfo = app.globalData.userInfo || wx.getStorageSync('userInfo') || {} - userInfo.phoneNumber = phoneNumber - - // 更新本地和全局用户信息 - app.globalData.userInfo = userInfo - wx.setStorageSync('userInfo', userInfo) - - // 获取userId - const userId = wx.getStorageSync('userId') - const users = wx.getStorageSync('users') || {} - const currentUserType = users[userId] && users[userId].type ? users[userId].type : '' - - // 同时更新服务器用户信息 - this.uploadUserInfoToServer(userInfo, userId, currentUserType) - - // 更新页面状态 - this.setData({ - needPhoneAuth: false - }) - - // 重新加载用户信息以更新UI - this.loadUserInfo() - - wx.showToast({ - title: '手机号绑定成功', - icon: 'success' - }) - } else { - console.error('获取手机号失败:', res) - wx.showToast({ - title: '获取手机号失败', - icon: 'none' - }) - } + try { + // 引入API服务 + const API = require('../../utils/api.js') + + // 1. 先执行微信登录获取code + const loginRes = await new Promise((resolve, reject) => { + wx.login({ + success: resolve, + 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); + openid = openidRes.openid || openidRes.OpenID || null; + 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) + } + + // 如果有userId,也存储起来 + if (userId) { + wx.setStorageSync('userId', userId) + } else { + // 生成临时userId + const tempUserId = 'user_' + Date.now() + wx.setStorageSync('userId', tempUserId) + userId = tempUserId + } + + 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)) { + // 如果服务器返回格式不标准但包含手机号,也接受 + if (!(phoneRes && phoneRes.phoneNumber)) { + throw new Error('获取手机号失败: ' + (phoneRes && phoneRes.message ? phoneRes.message : '未知错误')) } - }) - .catch(err => { - wx.hideLoading() - console.error('获取手机号失败:', err) - wx.showToast({ - title: '获取手机号失败', - icon: 'none' - }) + } + + // 检查是否有手机号冲突 + 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 { + userProfile = await new Promise((resolve, reject) => { + wx.getUserProfile({ + desc: '用于完善会员资料', + success: resolve, + fail: reject + }); + }); + console.log('获取用户信息成功:', userProfile); + } catch (err) { + console.warn('获取用户信息失败:', err); + // 如果获取失败,使用默认值 + } + + // 5. 创建用户信息 + const app = getApp() + const existingUserInfo = app.globalData.userInfo || wx.getStorageSync('userInfo') || {} + const userInfo = { + nickName: existingUserInfo.nickName || (userProfile ? userProfile.userInfo.nickName : '微信用户'), + avatarUrl: existingUserInfo.avatarUrl || (userProfile ? userProfile.userInfo.avatarUrl : 'https://mmbiz.qpic.cn/mmbiz/icTdbqWNOwNRna42FI242Lcia07jQodd2FJGIYQfG0LAJGFxM4FbnQP6yfMxBgJ0F3YRqJCJ1aPAK2dQagdusBZg/0'), + gender: existingUserInfo.gender || (userProfile ? userProfile.userInfo.gender : 0), + country: existingUserInfo.country || (userProfile ? userProfile.userInfo.country : ''), + province: existingUserInfo.province || (userProfile ? userProfile.userInfo.province : ''), + city: existingUserInfo.city || (userProfile ? userProfile.userInfo.city : ''), + language: existingUserInfo.language || (userProfile ? userProfile.userInfo.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.showToast({ + title: '登录成功,但手机号已被其他账号绑定', + icon: 'none', + duration: 3000 }) + } else { + wx.showToast({ + title: '登录成功,手机号已绑定', + icon: 'success', + duration: 2000 + }) + } + + } catch (error) { + wx.hideLoading() + console.error('登录过程中发生错误:', error) + + // 更具体的错误提示 + let errorMsg = '登录失败,请重试' + if (error.message.includes('网络')) { + errorMsg = '网络连接失败,请检查网络后重试' + } else if (error.message.includes('服务器')) { + errorMsg = '服务器连接失败,请稍后重试' + } else if (error.message.includes('openid')) { + errorMsg = '获取登录信息失败,请重试' + } else if (error.message.includes('手机号')) { + errorMsg = '获取手机号失败,请重试' + } + + wx.showToast({ + title: errorMsg, + icon: 'none', + duration: 3000 + }) + + // 清除可能已经保存的不完整信息 + try { + wx.removeStorageSync('openid') + wx.removeStorageSync('sessionKey') + wx.removeStorageSync('userId') + } catch (e) { + console.error('清除临时登录信息失败:', e) + } + } }, // 上传用户信息到服务器