// pages/user/phone-verify/index.js const weChatAuthService = require('../../../services/auth/wechat'); Page({ data: { phoneNumber: '', verifyCode: '', canSendCode: false, canConfirm: false, sendCodeText: '发送验证码', countdown: 0, loading: false }, onLoad(options) { // weChatAuthService 已经是一个实例,直接使用 this.countdownTimer = null; }, onUnload() { if (this.countdownTimer) { clearInterval(this.countdownTimer); } }, // 手机号输入 onPhoneInput(e) { const phoneNumber = e.detail.value; this.setData({ phoneNumber }); this.checkCanSendCode(); this.checkCanConfirm(); }, // 验证码输入 onVerifyCodeInput(e) { const verifyCode = e.detail.value; this.setData({ verifyCode }); this.checkCanConfirm(); }, // 检查是否可以发送验证码 checkCanSendCode() { const { phoneNumber, countdown } = this.data; const phoneRegex = /^1[3-9]\d{9}$/; const canSendCode = phoneRegex.test(phoneNumber) && countdown === 0; this.setData({ canSendCode }); }, // 检查是否可以确认绑定 checkCanConfirm() { const { phoneNumber } = this.data; const phoneRegex = /^1[3-9]\d{9}$/; const canConfirm = phoneRegex.test(phoneNumber); this.setData({ canConfirm }); }, // 发送验证码 async sendVerifyCode() { if (!this.data.canSendCode) return; try { this.setData({ loading: true }); // 这里应该调用后端API发送验证码 // 暂时模拟发送成功 await this.simulateSendCode(); wx.showToast({ title: '验证码已发送', icon: 'success' }); // 开始倒计时 this.startCountdown(); } catch (error) { console.error('发送验证码失败:', error); wx.showToast({ title: '发送失败,请重试', icon: 'none' }); } finally { this.setData({ loading: false }); } }, // 模拟发送验证码(实际项目中应该调用真实API) simulateSendCode() { return new Promise((resolve) => { setTimeout(resolve, 1000); }); }, // 开始倒计时 startCountdown() { let countdown = 60; this.setData({ countdown, sendCodeText: `${countdown}s后重发`, canSendCode: false }); this.countdownTimer = setInterval(() => { countdown--; if (countdown > 0) { this.setData({ countdown, sendCodeText: `${countdown}s后重发` }); } else { this.setData({ countdown: 0, sendCodeText: '重新发送' }); this.checkCanSendCode(); clearInterval(this.countdownTimer); } }, 1000); }, // 确认绑定 async confirmBind() { if (!this.data.canConfirm) return; try { this.setData({ loading: true }); const { phoneNumber } = this.data; // 直接更新用户信息,不验证验证码 await this.updateUserPhone(phoneNumber); wx.showToast({ title: '绑定成功', icon: 'success' }); // 延迟返回上一页 setTimeout(() => { wx.navigateBack(); }, 1500); } catch (error) { console.error('绑定手机号失败:', error); wx.showToast({ title: error.message || '绑定失败,请重试', icon: 'none' }); } finally { this.setData({ loading: false }); } }, // 更新用户手机号 async updateUserPhone(phoneNumber) { try { // 调用微信授权服务更新用户信息 await weChatAuthService.updateUserProfile({ phoneNumber: phoneNumber }); // 更新本地存储的用户信息 const userInfo = wx.getStorageSync('userInfo') || {}; userInfo.phoneNumber = phoneNumber; wx.setStorageSync('userInfo', userInfo); } catch (error) { console.error('更新用户手机号失败:', error); throw error; } } });