Files
multiPay/public/checkout.js
T

124 lines
9.7 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
const $ = (selector) => document.querySelector(selector);
const query = new URLSearchParams(location.search);
const state = { user: null, packages: [], selectedPackage: null, selectedGateway: null, currentOrder: null };
let pollTimer = null;
let qrRefreshTimer = null;
const userId = query.get('user_id') || '';
const amountParam = query.get('amount') || '';
const orderNo = query.get('merchant_order_no') || `PAY${Date.now().toString().slice(-10)}`;
const subject = query.get('subject') || '账户充值';
$('#orderNoText').textContent = orderNo;
function showError(message) { const box = $('#errorBox'); box.textContent = message; box.classList.remove('hidden'); setTimeout(() => box.classList.add('hidden'), 5000); }
function showInvalidUser(value) { $('#userGate').classList.add('hidden'); $('#checkoutMain').classList.add('hidden'); $('#historyPanel').classList.add('hidden'); $('#invalidUserView').classList.remove('hidden'); $('#invalidUserId').textContent = value ? `用户 ID:${value}` : '未传入 user_id'; }
function channelName(channel) { return ({ alipay: '支付宝', wechat: '微信支付', mock: '本地模拟' })[channel] || channel; }
function channelIcon(channel) { return channel === 'alipay' ? '支' : channel === 'wechat' ? '微' : 'M'; }
function formatTime(value) { return new Date(value).toLocaleString('zh-CN', { hour12: false }); }
function formatAvailablePoints(value) {
const quota = Number(value ?? 0);
return Math.ceil((Number.isFinite(quota) ? quota : 0) / 5000).toLocaleString('zh-CN');
}
function syncAmount() {
const amount = state.selectedPackage ? (state.selectedPackage.amount_cents / 100).toFixed(2) : '0.00';
const points = state.selectedPackage ? state.selectedPackage.points : 0;
$('#amountText').textContent = Number(amount || 0).toFixed(2);
$('#pointsText').textContent = Number(points).toLocaleString('zh-CN');
$('#createOrder').disabled = !state.selectedGateway || Number(amount) <= 0;
}
function renderPackages() {
const list = $('#packageList'); list.innerHTML = '';
state.packages.forEach((item) => {
const button = document.createElement('button'); button.className = 'package-card';
button.innerHTML = `<span>${item.name}</span><strong>¥ ${(item.amount_cents / 100).toFixed(2)}</strong><small>赠送 <b>${Number(item.points).toLocaleString('zh-CN')}</b> 积分</small>`;
button.onclick = () => { document.querySelectorAll('.package-card').forEach((card) => card.classList.remove('selected')); button.classList.add('selected'); state.selectedPackage = item; syncAmount(); };
list.append(button);
});
if (!state.packages.length) list.innerHTML = '<div class="empty-state package-empty">暂无可用充值套餐,请联系管理员配置。</div>';
const matched = amountParam && state.packages.find((item) => item.amount_cents === Math.round(Number(amountParam) * 100));
if (matched) list.children[state.packages.indexOf(matched)]?.click(); else if (state.packages.length) list.children[0]?.click();
}
function renderHistory(history) {
$('#historyCount').textContent = `${history.length} 笔记录`;
$('#historyBody').innerHTML = history.length ? history.map((row) => `<tr><td>${formatTime(row.paid_at)}</td><td><code>${row.merchant_order_no}</code></td><td>${channelName(row.channel)}</td><td><b>¥ ${(row.amount_cents / 100).toFixed(2)}</b></td><td class="points-cell">+${Number(row.points || 0).toLocaleString('zh-CN')}</td></tr>`).join('') : '<tr><td colspan="5"><div class="table-empty">近六个月暂无充值记录</div></td></tr>';
}
async function loadGateways() {
const data = await fetch('/api/checkout/config').then((response) => response.json()); $('#brandName').textContent = data.siteName;
const list = $('#gatewayList'); list.innerHTML = '';
data.gateways.forEach((gateway, index) => {
const button = document.createElement('button'); button.className = `gateway-card channel-${gateway.channel}`;
button.innerHTML = `<span class="gateway-icon">${channelIcon(gateway.channel)}</span><span><b>${gateway.name}</b><small>${gateway.subject_type === 'company' ? '企业主体' : '个人/个体主体'} · ${channelName(gateway.channel)}</small></span><i></i>`;
button.onclick = () => { document.querySelectorAll('.gateway-card').forEach((card) => card.classList.remove('selected')); button.classList.add('selected'); state.selectedGateway = gateway; syncAmount(); };
list.append(button); if (index === 0) button.click();
});
if (!data.gateways.length) list.innerHTML = '<div class="empty-state">暂无可用支付通道,请联系管理员配置。</div>';
}
async function init() {
if (!userId) return showInvalidUser('');
try {
const response = await fetch(`/api/checkout/users/${encodeURIComponent(userId)}`); const data = await response.json();
if (!response.ok) return showInvalidUser(userId);
state.user = data.user; state.packages = data.packages;
$('#userName').textContent = data.user.username || data.user.displayName; $('#userAvatar').textContent = (data.user.username || data.user.displayName || data.user.id).slice(0, 1).toUpperCase(); $('#pointsBalance').textContent = formatAvailablePoints(data.user.quota);
renderPackages(); renderHistory(data.history); await loadGateways(); syncAmount();
$('#userGate').classList.add('hidden'); $('#checkoutMain').classList.remove('hidden'); $('#historyPanel').classList.remove('hidden');
} catch { showInvalidUser(userId); }
}
$('#createOrder').onclick = async () => {
if (!state.selectedPackage) return showError('请选择充值套餐');
const amount = (state.selectedPackage.amount_cents / 100).toFixed(2);
const button = $('#createOrder'); button.disabled = true; button.textContent = '正在创建订单…';
try {
const payload = { amount, user_id: state.user.id, package_id: state.selectedPackage?.id || '', merchant_order_no: orderNo, subject, category: 'recharge', gateway_id: state.selectedGateway.id, notify_url: query.get('notify_url') || '', return_url: query.get('return_url') || '', timestamp: query.get('timestamp') || '', sign: query.get('sign') || '' };
const response = await fetch('/api/checkout/orders', { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify(payload) }); const data = await response.json();
if (!response.ok) throw new Error(data.message || '创建订单失败');
state.currentOrder = data.order; $('#amountText').textContent = state.currentOrder.amount; $('#pointsText').textContent = Number(state.currentOrder.points || 0).toLocaleString('zh-CN'); renderQr();
} catch (error) { showError(error.message); button.disabled = false; button.textContent = '确认充值'; }
};
function renderQr() {
$('#chooseView').classList.add('hidden'); $('#qrView').classList.remove('hidden'); $('#qrImage').src = `/api/checkout/orders/${encodeURIComponent(state.currentOrder.id)}/qrcode?t=${Date.now()}`;
const badge = $('#channelBadge'); badge.className = `channel-badge channel-${state.currentOrder.channel}`; badge.textContent = channelName(state.currentOrder.channel);
const link = $('#paymentLink');
link.classList.add('hidden');
if (state.currentOrder.channel === 'alipay') { $('.qr-copy h3').textContent = '请使用支付宝扫码'; $('.qr-copy p').textContent = '当前显示支付宝官方收银台的真实付款码;支付完成后本页面会自动更新。'; }
else if (state.currentOrder.channel === 'mock') { link.href = `/mock-pay/${encodeURIComponent(state.currentOrder.id)}`; link.textContent = '打开模拟支付页 →'; link.classList.remove('hidden'); }
const expires = new Date(state.currentOrder.expiresAt).getTime();
const tick = () => { const left = Math.max(0, Math.floor((expires - Date.now()) / 1000)); $('#countdown').textContent = `${String(Math.floor(left / 60)).padStart(2, '0')}:${String(left % 60).padStart(2, '0')}`; if (left <= 0) { clearInterval(pollTimer); $('#statusLine').textContent = '二维码已过期,请重新发起充值'; } };
if (state.currentOrder.channel === 'alipay') qrRefreshTimer = setInterval(() => { $('#qrImage').src = `/api/checkout/orders/${encodeURIComponent(state.currentOrder.id)}/qrcode?t=${Date.now()}`; }, 60_000);
tick(); setInterval(tick, 1000); pollTimer = setInterval(checkStatus, 2000);
}
async function checkStatus() {
try { const data = await fetch(`/api/checkout/orders/${encodeURIComponent(state.currentOrder.id)}`).then((response) => response.json()); if (data.order?.status === 'paid') { clearInterval(pollTimer); clearInterval(qrRefreshTimer); showSuccess(data.order); } else if (['failed', 'closed'].includes(data.order?.status)) { clearInterval(pollTimer); clearInterval(qrRefreshTimer); showError('订单已关闭或支付失败'); } } catch { /* keep polling */ }
}
async function refreshUserBalance() {
try {
const data = await fetch(`/api/checkout/users/${encodeURIComponent(state.user.id)}`).then((response) => response.json());
if (data.user) { state.user = { ...state.user, ...data.user }; $('#pointsBalance').textContent = formatAvailablePoints(data.user.quota); }
} catch { /* 保留最后一次已加载的额度 */ }
}
function showSuccess(order) {
$('#qrView').classList.add('hidden'); $('#successView').classList.remove('hidden'); $('#successMeta').innerHTML = `<span>订单号</span><b>${order.merchantOrderNo}</b><span>充值金额</span><b>¥ ${order.amount}</b><span>获得积分</span><b>+${Number(order.points || 0).toLocaleString('zh-CN')}</b>`;
refreshUserBalance();
}
$('#backChoose').onclick = () => location.reload();
$('#returnButton').onclick = (event) => {
event.preventDefault();
window.close();
setTimeout(() => {
if (!window.closed) {
document.body.innerHTML = '<main class="closed-page"><div class="result-icon">✓</div><h2>充值已完成</h2><p>浏览器限制了自动关闭,请直接关闭此页面。</p></main>';
}
}, 200);
};
init();