Display Alipay cashier QR directly

This commit is contained in:
Alex committed 2026-11-02 14:59:08 +08:00
1 parent 91abad4066
commit 804e539932
6 files changed
+66 -15

No files matched your search

+2 -2
View File
@@ -5,7 +5,7 @@
## 已实现
- 公开收银台:必须传入有效用户 ID,支持充值套餐、积分展示和近六个月充值记录。
- 支付通道:本地模拟支付、支付宝 `alipay.trade.precreate`、微信支付 APIv3 Native 下单。
- 支付通道:本地模拟支付、支付宝电脑网站支付官方收银台二维码、可选当面付、微信支付 APIv3 Native 下单。
- 安全校验:支付宝/微信请求签名、平台回调验签、金额复核、幂等处理。
- 业务通知:HMAC-SHA256 签名、失败自动重试、手动重试、完整通知日志。
- 管理后台:数据概览、用户管理、充值套餐、充值记录、按渠道/状态/分类/时间查询、对账明细、网关配置。
@@ -120,7 +120,7 @@ sign = HMAC-SHA256(merchant_secret, content).hex()
### 支付宝
后台新增支付宝网关,填写 AppID、商户 PID、应用 RSA2 私钥和支付宝公钥。沙箱模式默认使用沙箱网关,正式模式使用生产网关。应用需在支付宝开放平台开通“当面付”。
后台新增支付宝网关,填写 AppID、商户 PID、应用 RSA2 私钥和支付宝公钥。使用电脑网站支付时,服务端会打开支付宝官方收银台并提取其真实付款二维码展示在本站扫码区,不向用户提供收银台跳转链接;二维码会定时刷新。正式应用需开通“电脑网站支付”,仅在选择 `precreate` 时需要开通“当面付”。
### 微信支付
+2 -2
View File
@@ -3,7 +3,7 @@
<head>
<meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1">
<meta name="robots" content="noindex,nofollow"><title>MultiPay 管理后台</title>
<link rel="stylesheet" href="/assets/app.css?v=20261102-refund">
<link rel="stylesheet" href="/assets/app.css?v=20261102-scanqr">
</head>
<body class="admin-body">
<section id="loginPage" class="login-page">
@@ -20,6 +20,6 @@
</section>
<div id="toast" class="toast"></div>
<div id="modal" class="modal hidden"><div class="modal-backdrop" data-close></div><div class="modal-card"><button class="modal-close" data-close>×</button><div id="modalContent"></div></div></div>
<script src="/assets/admin.js?v=20261102-refund" defer></script>
<script src="/assets/admin.js?v=20261102-scanqr" defer></script>
</body>
</html>
+2 -2
View File
@@ -5,7 +5,7 @@
<meta name="viewport" content="width=device-width,initial-scale=1">
<meta name="robots" content="noindex,nofollow">
<title>安全收银台</title>
<link rel="stylesheet" href="/assets/app.css?v=20261102-refund">
<link rel="stylesheet" href="/assets/app.css?v=20261102-cashierqr">
</head>
<body class="checkout-body">
<header class="checkout-header">
@@ -48,6 +48,6 @@
<div class="history-table-wrap"><table><thead><tr><th>充值时间</th><th>订单号</th><th>支付渠道</th><th>充值金额</th><th>获得积分</th></tr></thead><tbody id="historyBody"></tbody></table></div>
</section>
<footer class="checkout-footer"><span>支付过程受签名验证与金额校验保护</span><span>如有疑问请联系商户</span></footer>
<script src="/assets/checkout.js?v=20261102-refund" defer></script>
<script src="/assets/checkout.js?v=20261102-cashierqr" defer></script>
</body>
</html>
+5 -2
View File
@@ -2,6 +2,7 @@ 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)}`;
@@ -80,15 +81,17 @@ 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');
if (state.currentOrder.paymentUrl) { link.href = state.currentOrder.paymentUrl; link.textContent = '打开支付宝官方收银台 →'; link.classList.remove('hidden'); $('.qr-copy h3').textContent = '打开官方收银台扫码'; $('.qr-copy p').textContent = '请在电脑上打开支付宝官方收银台,页面会展示付款二维码;支付完成后此页面会自动更新。'; }
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); showSuccess(data.order); } else if (['failed', 'closed'].includes(data.order?.status)) { clearInterval(pollTimer); showError('订单已关闭或支付失败'); } } catch { /* keep polling */ }
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() {
+39 -3
View File
@@ -109,6 +109,34 @@ function extractJsonObject(raw: string, field: string): string | null {
return null;
}
function decodeHtmlAttribute(value: string): string {
return value.replace(/&amp;/gi, "&").replace(/&quot;/gi, '"').replace(/&#39;/g, "'")
.replace(/&#x([0-9a-f]+);/gi, (_, hex) => String.fromCodePoint(Number.parseInt(hex, 16)))
.replace(/&#(\d+);/g, (_, number) => String.fromCodePoint(Number(number)));
}
async function fetchAlipayCashierQr(paymentUrl: string): Promise<string> {
const response = await fetch(paymentUrl, {
redirect: "follow",
headers: { "user-agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 Chrome/130 Safari/537.36" },
signal: AbortSignal.timeout(15_000)
});
if (!response.ok) throw new Error(`支付宝官方收银台 HTTP ${response.status}`);
const finalUrl = new URL(response.url);
if (finalUrl.protocol !== "https:" || !(finalUrl.hostname.endsWith(".alipay.com") || finalUrl.hostname.endsWith(".alipaydev.com"))) {
throw new Error("支付宝官方收银台跳转地址不可信");
}
const html = await response.text();
const input = html.match(/<input\b[^>]*\bid=["']J_qrCode["'][^>]*>/i)?.[0];
const rawQr = input?.match(/\bvalue=["']([^"']+)["']/i)?.[1];
if (!rawQr) throw new Error("支付宝官方收银台未返回可用付款二维码");
const qr = new URL(decodeHtmlAttribute(rawQr));
if (qr.protocol !== "https:" || !(qr.hostname === "qr.alipay.com" || qr.hostname.endsWith(".alipay.com"))) {
throw new Error("支付宝官方付款二维码地址不可信");
}
return qr.toString();
}
async function createAlipayPayment(gateway: GatewayRecord, order: PaymentOrderInput, baseUrl: string): Promise<ProviderPaymentResult> {
const config = gateway.config;
required(config, ["appId", "privateKey", "alipayPublicKey"]);
@@ -139,9 +167,10 @@ async function createAlipayPayment(gateway: GatewayRecord, order: PaymentOrderIn
};
pageParams.sign = alipaySign(pageParams, config.privateKey);
const paymentUrl = `${gatewayUrl}?${new URLSearchParams(pageParams).toString()}`;
const qrContent = await fetchAlipayCashierQr(paymentUrl);
return {
qrContent: paymentUrl,
providerPayload: { flow: "redirect", payment_product: "page", redirect_url: paymentUrl }
qrContent,
providerPayload: { flow: "cashier_qr", payment_product: "page", redirect_url: paymentUrl }
};
}
const params: Record<string, string> = {
@@ -180,7 +209,7 @@ async function createAlipayPayment(gateway: GatewayRecord, order: PaymentOrderIn
if (!payload.sign || !signedContent || !alipayVerify(signedContent, payload.sign, config.alipayPublicKey)) {
throw new Error("支付宝响应验签失败");
}
return { qrContent: result.qr_code, providerPayload: payload };
return { qrContent: result.qr_code, providerPayload: { ...payload, payment_product: "precreate" } };
}
async function queryAlipayPayment(gateway: GatewayRecord, merchantOrderNo: string): Promise<ProviderCallbackResult | null> {
@@ -413,6 +442,13 @@ export async function createProviderPayment(gateway: GatewayRecord, order: Payme
return createWechatPayment(gateway, order, baseUrl);
}
export async function refreshProviderQrContent(gateway: GatewayRecord, providerPayload: unknown): Promise<string | null> {
if (gateway.channel !== "alipay" || gateway.mode === "mock") return null;
const payload = providerPayload && typeof providerPayload === "object" ? providerPayload as Record<string, unknown> : {};
if (payload.payment_product !== "page" || typeof payload.redirect_url !== "string") return null;
return fetchAlipayCashierQr(payload.redirect_url);
}
export async function queryProviderPayment(gateway: GatewayRecord, merchantOrderNo: string): Promise<ProviderCallbackResult | null> {
if (gateway.channel === "alipay" && gateway.mode !== "mock") {
return queryAlipayPayment(gateway, merchantOrderNo);
+16 -4
View File
@@ -3,6 +3,7 @@ import { db, getSetting, initializeDatabase, setSetting } from "./db";
import { decryptJson, encryptJson, hmacHex, randomId, safeEqual } from "./security";
import {
createProviderPayment, createProviderRefund, parseAlipayCallback, parseWechatCallback,
refreshProviderQrContent,
queryProviderPayment, queryProviderRefund,
type GatewayRecord, type ProviderCallbackResult
} from "./payments";
@@ -116,8 +117,6 @@ function normalizeUserId(value: unknown): string {
}
function publicOrder(row: Row) {
let provider: Record<string, any> = {};
try { provider = row.provider_payload ? JSON.parse(row.provider_payload) : {}; } catch { /* ignore malformed legacy payload */ }
return {
id: row.id,
merchantOrderNo: row.merchant_order_no,
@@ -129,7 +128,6 @@ function publicOrder(row: Row) {
expiresAt: row.expires_at,
paidAt: row.paid_at,
returnUrl: row.return_url,
paymentUrl: provider.flow === "redirect" ? provider.redirect_url : null,
userId: row.user_id,
packageId: row.package_id,
points: Number(row.points || 0),
@@ -515,8 +513,22 @@ const server = Bun.serve({
const qrMatch = path.match(/^\/api\/checkout\/orders\/([^/]+)\/qrcode$/);
if (qrMatch && request.method === "GET") {
const row = db.query("SELECT qr_content, status FROM orders WHERE id = ?").get(decodeURIComponent(qrMatch[1])) as Row | null;
const row = db.query("SELECT * FROM orders WHERE id = ?").get(decodeURIComponent(qrMatch[1])) as Row | null;
if (!row?.qr_content) return new Response("QR code unavailable", { status: 404 });
if (row.status === "pending" && row.channel === "alipay") {
try {
const gateway = getGateway(row.gateway_id);
const payload = JSON.parse(row.provider_payload || "{}");
const refreshed = gateway ? await refreshProviderQrContent(gateway, payload) : null;
if (refreshed) {
row.qr_content = refreshed;
db.query("UPDATE orders SET qr_content=?, updated_at=? WHERE id=?")
.run(refreshed, new Date().toISOString(), row.id);
}
} catch (error) {
console.error(`[ALIPAY QR REFRESH] ${row.merchant_order_no}`, error);
}
}
const svg = await QRCode.toString(row.qr_content, { type: "svg", margin: 2, width: 320, color: { dark: "#12212b", light: "#ffffff" } });
return new Response(svg, { headers: { "content-type": "image/svg+xml", "cache-control": "no-store" } });
}