/* Copyright (C) 2025 QuantumNous This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with this program. If not, see . For commercial licensing, please contact support@quantumnous.com */ import React, { useEffect, useLayoutEffect, useRef, useState, useContext, } from 'react'; import { useLocation } from 'react-router-dom'; import { Segmented, Tabs } from 'antd'; import { Modal, Toast } from '@/components/ui'; import UserCenterPageHeader from '../../components/common/UserCenterPageHeader'; import { useTranslation } from 'react-i18next'; import { UserContext } from '../../context/User'; import { StatusContext } from '../../context/Status'; import { API, showError, showInfo, showSuccess, renderQuota, renderQuotaWithAmount, } from '../../helpers'; import PageBackground from '../../components/common/PageBackground'; import RechargePanel from './RechargePanel'; import usePayPalQuote from '../../hooks/common/usePayPalQuote'; import MembershipPanel from './MembershipPanel'; import HistoryPanel from './HistoryPanel'; import WalletCard from './WalletCard'; import { MembershipHistoryContent } from '../../components/membership/MembershipHistoryModal'; import './recharge.css'; import PaymentConfirmModal from '../../components/topup/modals/PaymentConfirmModal'; import WechatQRModal from '../../components/topup/modals/WechatQRModal'; import { formatPayPalUSD, getPayPalReturnState, isPayPalAvailable, parsePayPalQuote, requestPayPalOrder, removePayPalReturnState, } from '../../helpers/paypalPayment'; const Recharge = ({ embedded = false }) => { const { t } = useTranslation(); const { pathname } = useLocation(); const alignStandaloneContent = !embedded && pathname === '/recharge'; const contentRef = useRef(null); useLayoutEffect(() => { if (!alignStandaloneContent) return undefined; const content = contentRef.current; const topbar = document.querySelector('.ui-topbar'); if (!content || !topbar) return undefined; const resizeObserver = new ResizeObserver(() => alignContent()); const alignContent = () => { const label = topbar.querySelector( '.ui-header-navigation a[href="/market"] > span', ); if (window.innerWidth > 768 && label?.getClientRects().length) { const inset = Math.max( 16, label.getBoundingClientRect().left - content.getBoundingClientRect().left, ); content.style.setProperty('--rc-content-inset', `${inset}px`); } else { content.style.removeProperty('--rc-content-inset'); } if (label) resizeObserver.observe(label); const brand = topbar.querySelector('.ui-header-brand'); if (brand) resizeObserver.observe(brand); }; // The navigation may finish loading or change language after this page mounts. const mutationObserver = new MutationObserver(alignContent); mutationObserver.observe(topbar, { childList: true, subtree: true }); resizeObserver.observe(topbar); resizeObserver.observe(content); window.addEventListener('resize', alignContent); alignContent(); return () => { resizeObserver.disconnect(); mutationObserver.disconnect(); window.removeEventListener('resize', alignContent); content.style.removeProperty('--rc-content-inset'); }; }, [alignStandaloneContent]); const [userState, userDispatch] = useContext(UserContext); const [statusState] = useContext(StatusContext); // 充值相关状态 const [redemptionCode, setRedemptionCode] = useState(''); const [amount, setAmount] = useState(0.0); const [minTopUp, setMinTopUp] = useState(statusState?.status?.min_topup || 1); const [topUpCount, setTopUpCount] = useState( statusState?.status?.min_topup || 1, ); const [priceRatio, setPriceRatio] = useState(statusState?.status?.price || 1); const [topUpLink, setTopUpLink] = useState( statusState?.status?.top_up_link || '', ); // 支付相关状态 const [enableOnlineTopUp, setEnableOnlineTopUp] = useState(false); const [enableAlipayTopUp, setEnableAlipayTopUp] = useState(false); const [enableWechatTopUp, setEnableWechatTopUp] = useState(false); const [enableStripeTopUp, setEnableStripeTopUp] = useState(false); const [enablePayPalTopUp, setEnablePayPalTopUp] = useState(false); const [payPalMinTopUp, setPayPalMinTopUp] = useState(1); const [enableCreemTopUp, setEnableCreemTopUp] = useState(false); const [creemProducts, setCreemProducts] = useState([]); const [selectedCreemProduct, setSelectedCreemProduct] = useState(null); const [creemOpen, setCreemOpen] = useState(false); // 微信支付二维码弹窗 const [wechatQRVisible, setWechatQRVisible] = useState(false); const [wechatOrderData, setWechatOrderData] = useState(null); const [statusLoading, setStatusLoading] = useState(true); const [balanceLoading, setBalanceLoading] = useState(true); const [isSubmitting, setIsSubmitting] = useState(false); const [open, setOpen] = useState(false); const [payWay, setPayWay] = useState(''); const [amountLoading, setAmountLoading] = useState(false); const [paymentLoading, setPaymentLoading] = useState(false); const [confirmLoading, setConfirmLoading] = useState(false); const [payMethods, setPayMethods] = useState([]); // 预设充值额度 const [presetAmounts, setPresetAmounts] = useState([]); const [selectedPreset, setSelectedPreset] = useState(null); const [selectedPresetObj, setSelectedPresetObj] = useState(null); // 存储完整的预设对象 const { quote: payPalQuote, setQuote: setPayPalQuote, loading: quoteLoading, refresh: getPayPalAmount, } = usePayPalQuote( '/api/user/paypal/amount', selectedPresetObj?.id !== undefined ? { amount_option_id: selectedPresetObj.id } : { amount: parseInt(topUpCount) }, payWay === 'paypal' && selectedPreset !== null, ); // 充值配置信息 const [topupInfo, setTopupInfo] = useState({ amount_options: [], discount: {}, }); // 刷新账单列表的回调 const [refreshHistory, setRefreshHistory] = useState(0); // Tab 切换:充值 / 会员 const [activeTab, setActiveTab] = useState('recharge'); // 兑换码充值 const topUp = async () => { if (redemptionCode === '') { showInfo(t('请输入兑换码!')); return; } setIsSubmitting(true); try { const res = await API.post('/api/user/topup', { key: redemptionCode, }); const { success, message, data } = res.data; if (success) { showSuccess(t('兑换成功!')); Modal.success({ title: t('兑换成功!'), content: t('成功兑换额度:') + renderQuota(data), centered: true, }); if (userState.user) { const updatedUser = { ...userState.user, quota: userState.user.quota + data, }; userDispatch({ type: 'login', payload: updatedUser }); } setRedemptionCode(''); setRefreshHistory((prev) => prev + 1); } else { showError(message); } } catch (err) { showError(t('请求失败')); } finally { setIsSubmitting(false); } }; // 打开充值链接 const openTopUpLink = () => { if (!topUpLink) { showError(t('超级管理员未设置充值链接!')); return; } window.open(topUpLink, '_blank'); }; // 预充值 const preTopUp = async (payment) => { // 必须先选择充值档位 if (selectedPreset === null) { showError(t('请先选择充值金额')); return; } if (payment === 'stripe') { if (!enableStripeTopUp) { showError(t('管理员未开启Stripe充值!')); return; } } else if (payment === 'paypal') { if (!isPayPalAvailable(enablePayPalTopUp, payMethods)) { showError(t('管理员未开启 PayPal 充值!')); return; } } else if (payment === 'alipay') { if (!enableAlipayTopUp) { showError(t('管理员未开启支付宝充值!')); return; } } else if (payment === 'wxpay') { if (!enableWechatTopUp) { showError(t('管理员未开启微信充值!')); return; } } else { if (!enableOnlineTopUp) { showError(t('管理员未开启在线充值!')); return; } } setPayWay(payment); setPaymentLoading(true); try { // 如果选择了预设档位,已经在 selectPresetAmount 中计算好了金额(包含折扣和汇率),不需要重新获取 // 只有自定义金额时才需要从后端获取 if (payment === 'paypal') { if (!(await getPayPalAmount())) return; } else if (!selectedPresetObj) { if (payment === 'stripe') { await getStripeAmount(); } else { await getAmount(); } } const selectedMinimum = payment === 'paypal' ? payPalMinTopUp : minTopUp; if (topUpCount < selectedMinimum) { showError(t('充值数量不能小于') + selectedMinimum); return; } setOpen(true); } catch (error) { showError(t('获取金额失败')); } finally { setPaymentLoading(false); } }; // 在线充值 const onlineTopUp = async () => { let keepConfirmOpen = false; // 【Bug#7修复】仅在非预设档位(自定义金额)且金额为0时才从后端获取金额 // 避免覆盖已计算好的档位折扣价 if (!selectedPresetObj && payWay !== 'paypal') { if (payWay === 'stripe') { if (amount === 0) { await getStripeAmount(); } } else { if (amount === 0) { await getAmount(); } } } const selectedMinimum = payWay === 'paypal' ? payPalMinTopUp : minTopUp; if (topUpCount < selectedMinimum) { showError('充值数量不能小于' + selectedMinimum); return; } setConfirmLoading(true); try { let res; if (payWay === 'stripe') { res = await API.post('/api/user/stripe/pay', { amount: parseInt(topUpCount), payment_method: 'stripe', }); } else if (payWay === 'paypal' && enablePayPalTopUp) { const requestData = selectedPresetObj?.id ? { amount_option_id: selectedPresetObj.id, quote_token: payPalQuote?.quoteToken, } : { amount: parseInt(topUpCount), quote_token: payPalQuote?.quoteToken, }; res = await requestPayPalOrder( API, '/api/user/paypal/pay', requestData, { skipErrorHandler: true }, ); } else if (payWay === 'alipay' && enableAlipayTopUp) { // 使用独立支付宝接口 // 如果选择了预设档位,发送 amount_option_id 以应用折扣 const requestData = selectedPresetObj?.id ? { amount_option_id: selectedPresetObj.id } : { amount: parseInt(topUpCount) }; res = await API.post('/api/user/alipay/pc', requestData); } else if (payWay === 'wxpay' && enableWechatTopUp) { // 使用独立微信接口 // 如果选择了预设档位,发送 amount_option_id 以应用折扣 const requestData = selectedPresetObj?.id ? { amount_option_id: selectedPresetObj.id } : { amount: parseInt(topUpCount) }; res = await API.post('/api/user/wechat/native', requestData); } else { // 使用易支付接口 res = await API.post('/api/user/pay', { amount: parseInt(topUpCount), payment_method: payWay, }); } if (res !== undefined) { const { success, message, data } = res.data; // 支持新版和旧版响应格式 if (success || message === 'success') { if (payWay === 'stripe') { window.open(data.pay_link, '_blank'); } else if (payWay === 'paypal' && data.approval_url) { setPayPalQuote(parsePayPalQuote(data)); window.location.href = data.approval_url; return; } else if ( payWay === 'paypal' && res.status === 202 && message === 'PAYPAL_ORDER_CREATING' ) { showInfo(t('PayPal 订单创建中,请稍后重试')); return; } else if (payWay === 'alipay' && enableAlipayTopUp && data.pay_url) { // 支付宝独立接口 - 打开支付页面 // Safari 会拦截 await 之后的 window.open(用户手势已过期),改为同标签跳转 let isSafari = navigator.userAgent.indexOf('Safari') > -1 && navigator.userAgent.indexOf('Chrome') < 1; if (isSafari) { // 同标签跳转支付宝,页面即将卸载:立即 return, // 避免下方 setRefreshHistory 再发起注定被中断的账单请求而误报网络错误 window.location.href = data.pay_url; return; } else { window.open(data.pay_url, '_blank'); } } else if (payWay === 'wxpay' && enableWechatTopUp && data.code_url) { // 微信独立接口 - 显示二维码弹窗 setWechatOrderData(data); setWechatQRVisible(true); } else { // 易支付 - 表单提交 let params = data; let url = res.data.url; let form = document.createElement('form'); form.action = url; form.method = 'POST'; let isSafari = navigator.userAgent.indexOf('Safari') > -1 && navigator.userAgent.indexOf('Chrome') < 1; if (!isSafari) { form.target = '_blank'; } for (let key in params) { let input = document.createElement('input'); input.type = 'hidden'; input.name = key; input.value = params[key]; form.appendChild(input); } document.body.appendChild(form); form.submit(); document.body.removeChild(form); } setRefreshHistory((prev) => prev + 1); } else { showError(data || message); } } else { showError(res); } } catch (err) { const code = err?.response?.data?.message; if (payWay === 'paypal' && code?.startsWith('PAYPAL_QUOTE_')) { try { await getPayPalAmount(); keepConfirmOpen = true; showInfo(t('PayPal 报价已更新,请重新确认')); } catch { showError(t('获取金额失败')); } } else { console.log(err); showError(err?.response?.data?.message || t('支付请求失败')); } } finally { if (!keepConfirmOpen) setOpen(false); setConfirmLoading(false); } }; // Creem 预充值 const creemPreTopUp = async (product) => { if (!enableCreemTopUp) { showError(t('管理员未开启 Creem 充值!')); return; } setSelectedCreemProduct(product); setCreemOpen(true); }; // Creem 在线充值 const onlineCreemTopUp = async () => { if (!selectedCreemProduct) { showError(t('请选择产品')); return; } if (!selectedCreemProduct.productId) { showError(t('产品配置错误,请联系管理员')); return; } setConfirmLoading(true); try { const res = await API.post('/api/user/creem/pay', { product_id: selectedCreemProduct.productId, payment_method: 'creem', }); if (res !== undefined) { const { message, data } = res.data; if (message === 'success') { window.open(data.checkout_url, '_blank'); setRefreshHistory((prev) => prev + 1); } else { showError(data); } } else { showError(res); } } catch (err) { console.log(err); showError(t('支付请求失败')); } finally { setCreemOpen(false); setConfirmLoading(false); } }; // 微信支付完成回调 const handleWechatPayComplete = (success) => { setWechatQRVisible(false); setWechatOrderData(null); if (success) { showSuccess(t('充值成功!')); getUserQuota(); setRefreshHistory((prev) => prev + 1); } }; // 获取用户配额 const getUserQuota = async () => { setBalanceLoading(true); try { let res = await API.get(`/api/user/self`); const { success, message, data } = res.data; if (success) { userDispatch({ type: 'login', payload: data }); } else { showError(message); } } catch (err) { console.error('获取用户信息失败:', err); } finally { setBalanceLoading(false); } }; // 获取充值配置信息 const getTopupInfo = async () => { try { const res = await API.get('/api/user/topup/info'); const { data, success } = res.data; if (success) { setTopupInfo({ amount_options: data.amount_options || [], discount: data.discount || {}, }); // 处理支付方式 let payMethods = data.pay_methods || []; try { if (typeof payMethods === 'string') { payMethods = JSON.parse(payMethods); } if (payMethods && payMethods.length > 0) { payMethods = payMethods.filter( (method) => method.name && method.type, ); payMethods = payMethods.map((method) => { const normalizedMinTopup = Number(method.min_topup); method.min_topup = Number.isFinite(normalizedMinTopup) ? normalizedMinTopup : 0; if ( method.type === 'stripe' && (!method.min_topup || method.min_topup <= 0) ) { const stripeMin = Number(data.stripe_min_topup); if (Number.isFinite(stripeMin)) { method.min_topup = stripeMin; } } if (!method.color) { if (method.type === 'alipay') { method.color = 'rgba(var(--ui-blue-5), 1)'; } else if (method.type === 'wxpay') { method.color = 'rgba(var(--ui-green-5), 1)'; } else if (method.type === 'stripe') { method.color = 'rgba(var(--ui-purple-5), 1)'; } else if (method.type === 'paypal') { method.color = '#0070ba'; } else { method.color = 'rgba(var(--ui-primary-5), 1)'; } } return method; }); } else { payMethods = []; } setPayMethods(payMethods); const enableOnline = data.enable_online_topup || false; const enableAlipay = data.enable_alipay_topup || false; const enableWechat = data.enable_wechat_topup || false; const enableStripe = data.enable_stripe_topup || false; const enablePayPal = data.enable_paypal_topup || false; const enableCreem = data.enable_creem_topup || false; const minTopUpValue = enableOnline ? data.min_topup : enableStripe ? data.stripe_min_topup : 1; setEnableOnlineTopUp(enableOnline); setEnableAlipayTopUp(enableAlipay); setEnableWechatTopUp(enableWechat); setEnableStripeTopUp(enableStripe); setEnablePayPalTopUp(enablePayPal); setPayPalMinTopUp(Number(data.paypal_min_topup) || 1); setEnableCreemTopUp(enableCreem); setMinTopUp(minTopUpValue); setTopUpCount(minTopUpValue); // 设置 Creem 产品 try { const products = JSON.parse(data.creem_products || '[]'); setCreemProducts(products); } catch (e) { setCreemProducts([]); } // 处理充值档位配置 // 优先使用新版 amount_options_v2,其次使用旧版 amount_options,最后使用默认生成 if (data.amount_options_v2 && data.amount_options_v2.length > 0) { // 使用新版充值档位(按 sort 排序) const sortedOptions = [...data.amount_options_v2].sort( (a, b) => (a.sort || 0) - (b.sort || 0), ); const customPresets = sortedOptions.map((opt) => ({ id: opt.id, value: opt.amount, discount: opt.discount || 1.0, label: opt.label, badge: opt.badge, badgeColor: opt.badge_color, isRecommend: opt.is_recommend, isHot: opt.is_hot, bonus: opt.bonus, minVipLevel: opt.min_vip_level, })); setPresetAmounts(customPresets); } else if (data.amount_options && data.amount_options.length > 0) { // 使用旧版充值档位 const customPresets = data.amount_options.map((amount) => ({ value: amount, discount: data.discount[amount] || 1.0, })); setPresetAmounts(customPresets); } else { // 生成默认预设 setPresetAmounts(generatePresetAmounts(minTopUpValue)); } } catch (e) { console.log('解析支付方式失败:', e); setPayMethods([]); } } } catch (error) { console.error('获取充值配置异常:', error); } }; // 获取支付金额 const getAmount = async (value) => { if (value === undefined) { value = topUpCount; } setAmountLoading(true); try { const res = await API.post('/api/user/amount', { amount: parseFloat(value), }); if (res !== undefined) { const { message, data } = res.data; if (message === 'success') { setAmount(parseFloat(data)); } else { setAmount(0); Toast.error({ content: '错误:' + data, id: 'getAmount' }); } } else { showError(res); } } catch (err) { console.log(err); } setAmountLoading(false); }; // 获取 Stripe 支付金额 const getStripeAmount = async (value) => { if (value === undefined) { value = topUpCount; } setAmountLoading(true); try { const res = await API.post('/api/user/stripe/amount', { amount: parseFloat(value), }); if (res !== undefined) { const { message, data } = res.data; if (message === 'success') { setAmount(parseFloat(data)); } else { setAmount(0); Toast.error({ content: '错误:' + data, id: 'getAmount' }); } } else { showError(res); } } catch (err) { console.log(err); } finally { setAmountLoading(false); } }; // 选择预设充值额度 const selectPresetAmount = (preset) => { setTopUpCount(preset.value); setSelectedPreset(preset.value); setSelectedPresetObj(preset); // 保存完整的预设对象 const discount = preset.discount || topupInfo.discount[preset.value] || 1.0; // 计算实付金额(人民币) // 新版档位(有 id 字段):amount 已经是人民币金额,直接乘以折扣 // 旧版档位或自定义金额:需要乘以汇率 const isNewVersion = preset.id !== undefined; const discountedAmount = isNewVersion ? preset.value * discount // 新版:人民币金额 * 折扣 : preset.value * priceRatio * discount; // 旧版:额度 * 汇率 * 折扣 setAmount(discountedAmount); }; // 生成预设充值额度 const generatePresetAmounts = (minAmount) => { const multipliers = [1, 5, 10, 30, 50, 100, 300, 500]; return multipliers.map((multiplier) => ({ value: minAmount * multiplier, })); }; const renderAmount = () => { if (payWay === 'paypal') { return payPalQuote ? formatPayPalUSD(payPalQuote.payAmount) : '-'; } return amount + ' ' + t('元'); }; const handleCancel = () => { setOpen(false); }; const handleCreemCancel = () => { setCreemOpen(false); setSelectedCreemProduct(null); }; // 页面加载时始终刷新用户余额,确保显示最新数据 // (用户可能在其他页面消费或在其他设备充值,localStorage缓存的余额可能过期) useEffect(() => { getUserQuota(); }, []); useEffect(() => { getTopupInfo(); }, []); useEffect(() => { const result = getPayPalReturnState(window.location.search); if (!result) return; if (result.status === 'success') showSuccess(t('PayPal 充值成功')); else if (result.status === 'pending') showInfo(t('PayPal 支付处理中,请稍后查看充值记录')); else if (result.status === 'cancelled') showInfo(t('已取消 PayPal 支付')); else showError(t('PayPal 支付确认失败,请稍后重试')); getUserQuota(); setRefreshHistory((previous) => previous + 1); window.history.replaceState( {}, '', removePayPalReturnState(window.location.href), ); // The callback query must be consumed exactly once on page entry. // eslint-disable-next-line react-hooks/exhaustive-deps }, []); useEffect(() => { if (statusState?.status) { setTopUpLink(statusState.status.top_up_link || ''); setPriceRatio(statusState.status.price || 1); setStatusLoading(false); } }, [statusState?.status]); return (
{/* 统一页面背景层 —— 走 bg-glow-* 主题变量。 * embedded(嵌入 UserCenter/topup)时由父 shell 提供背景,此处跳过避免双层叠加; * 独立路由(/recharge、/console/topup)时自渲染 rich 背景 + 网格。 */} {!embedded && } {/* 支付确认弹窗 */} payWay === 'paypal' && payPalQuote?.quota ? renderQuota(payPalQuote.quota) : renderQuotaWithAmount(value) } amountLoading={amountLoading || quoteLoading} renderAmount={renderAmount} payWay={payWay} payMethods={payMethods} amountNumber={payWay === 'paypal' ? 0 : amount} discountRate={ payWay === 'paypal' ? 1.0 : selectedPresetObj?.discount || topupInfo?.discount?.[topUpCount] || 1.0 } payPalQuote={payPalQuote} /> {/* Creem 确认弹窗 */} {selectedCreemProduct && (

{t('产品名称')}:{selectedCreemProduct.name}

{t('价格')}:{selectedCreemProduct.currency === 'EUR' ? '€' : '¥'} {selectedCreemProduct.price}

{t('充值额度')}:{selectedCreemProduct.quota}

{t('是否确认充值?')}

)}
{/* 微信支付二维码弹窗 */} {/* 主内容区 */}

{t('为下一次调用补充能量')}

{t('选择充值额度或会员方案,继续使用 WeyAI 服务')}

{/* Tab 切换:充值 / 会员 */}
{activeTab === 'membership' ? ( ) : ( )}
{/* 充值记录 / 会员购买记录:页签首次激活时才挂载,沿用各自原有加载逻辑 */}
), }, { key: 'membership', label: t('会员购买记录'), children: , }, ]} />
); }; export default Recharge;