Browse Source

修复个人页面登录逻辑,确保一次登录成功

pull/1/head
徐飞洋 3 months ago
parent
commit
469b7a115e
  1. 378
      pages/profile/index.js

378
pages/profile/index.js

@ -315,7 +315,7 @@ Page({
}) })
}, },
// 处理手机号授权结果 // 处理手机号授权结果
onPhoneNumberResult(e) { async onPhoneNumberResult(e) {
console.log('手机号授权结果:', e) console.log('手机号授权结果:', e)
// 首先检查用户是否拒绝授权 // 首先检查用户是否拒绝授权
@ -329,183 +329,211 @@ Page({
return return
} }
// 用户同意授权,继续执行后续操作 wx.showLoading({
// 检查是否有openid,如果没有则先登录 title: '登录中...',
const openid = wx.getStorageSync('openid') mask: true
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
}
// 已登录且用户同意授权,获取加密数据 try {
const phoneData = e.detail // 引入API服务
const API = require('../../utils/api.js')
wx.showLoading({ title: '获取手机号中...' })
// 1. 先执行微信登录获取code
// 引入API服务 const loginRes = await new Promise((resolve, reject) => {
const API = require('../../utils/api.js') wx.login({
success: resolve,
// 上传到服务器解密 fail: reject
API.uploadPhoneNumberData(phoneData) })
.then(res => { })
wx.hideLoading()
if (res.success) { if (!loginRes.code) {
console.log('获取手机号结果:', res) throw new Error('获取登录code失败')
}
// 检查是否有手机号冲突
const hasPhoneConflict = res.phoneNumberConflict || false console.log('获取登录code成功:', loginRes.code)
const isNewPhone = res.isNewPhone || true
const phoneNumber = res.phoneNumber || null // 2. 使用code换取openid
const openidRes = await API.getOpenid(loginRes.code)
// 如果有手机号冲突,直接提示用户
if (hasPhoneConflict) { // 增强版响应处理逻辑,支持多种返回格式
wx.showToast({ let openid = null;
title: '手机号已被其他账号绑定,请更换账号后重试', let userId = null;
icon: 'none', let sessionKey = null;
duration: 3000
}) // 优先从data字段获取数据
} else if (phoneNumber) { if (openidRes && openidRes.data && typeof openidRes.data === 'object') {
// 保存手机号到用户信息 openid = openidRes.data.openid || openidRes.data.OpenID || null;
const app = getApp() userId = openidRes.data.userId || openidRes.data.userid || null;
const userInfo = app.globalData.userInfo || wx.getStorageSync('userInfo') || {} sessionKey = openidRes.data.session_key || openidRes.data.sessionKey || null;
userInfo.phoneNumber = phoneNumber }
// 更新本地和全局用户信息 // 如果data为空或不存在,尝试从响应对象直接获取
app.globalData.userInfo = userInfo if (!openid && openidRes && typeof openidRes === 'object') {
wx.setStorageSync('userInfo', userInfo) console.warn('服务器返回格式可能不符合预期,data字段为空或不存在,但尝试从根对象提取信息:', openidRes);
openid = openidRes.openid || openidRes.OpenID || null;
// 获取userId userId = openidRes.userId || openidRes.userid || null;
const userId = wx.getStorageSync('userId') sessionKey = openidRes.session_key || openidRes.sessionKey || null;
const users = wx.getStorageSync('users') || {} }
const currentUserType = users[userId] && users[userId].type ? users[userId].type : ''
// 检查服务器状态信息
// 同时更新服务器用户信息 const isSuccess = openidRes && (openidRes.success === true || openidRes.code === 200);
this.uploadUserInfoToServer(userInfo, userId, currentUserType)
if (!openid) {
// 更新页面状态 throw new Error('获取openid失败: ' + (openidRes && openidRes.message ? openidRes.message : '未知错误'))
this.setData({ }
needPhoneAuth: false
}) // 存储openid和session_key
wx.setStorageSync('openid', openid)
// 重新加载用户信息以更新UI if (sessionKey) {
this.loadUserInfo() wx.setStorageSync('sessionKey', sessionKey)
}
wx.showToast({
title: '手机号绑定成功', // 如果有userId,也存储起来
icon: 'success' if (userId) {
}) wx.setStorageSync('userId', userId)
} else { } else {
console.error('获取手机号失败:', res) // 生成临时userId
wx.showToast({ const tempUserId = 'user_' + Date.now()
title: '获取手机号失败', wx.setStorageSync('userId', tempUserId)
icon: 'none' 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) const hasPhoneConflict = phoneRes.phoneNumberConflict || false
wx.showToast({ const isNewPhone = phoneRes.isNewPhone || true
title: '获取手机号失败', const phoneNumber = phoneRes.phoneNumber || null
icon: 'none'
}) 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)
}
}
}, },
// 上传用户信息到服务器 // 上传用户信息到服务器

Loading…
Cancel
Save