Files
memind/server/one-shop-checkout.mjs
john 7f06361bd3 Ship the page-focused follow reply with the news and shop updates.
Replace the subscribe welcome with page-generation examples, add the trial news003 WeChat share card, and let OneShop checkout return to an order or recharge page.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-11-25 14:30:20 +08:00

97 lines
5.5 KiB
JavaScript

import { createHmac, timingSafeEqual } from 'node:crypto';
const lifetimeMs = 5 * 60_000;
const signature = (body, secret) => createHmac('sha256', secret)
.update('one-shop-checkout-v1:' + body).digest('base64url');
const returnPathPattern = /^(\/[a-z0-9-]{1,80})?\/(my\/orders\/[1-9]\d*\/pay|recharge)$/;
export function resolveReturnUrl(shopOrigin, { orderId, returnPath } = {}) {
let path = returnPath;
if (path == null || path === '') {
if (!Number.isSafeInteger(orderId) || orderId <= 0) return null;
path = `/my/orders/${orderId}/pay`;
}
const pattern = Number.isSafeInteger(orderId) && orderId > 0
? new RegExp(`^(?:/[a-z0-9-]{1,80})?/my/orders/${orderId}/pay$`)
: /^(?:\/[a-z0-9-]{1,80})?\/recharge$/;
if (typeof path !== 'string' || path.length > 120 || !pattern.test(path)) return null;
const target = new URL(path, shopOrigin);
if (target.origin !== shopOrigin || target.pathname !== path || target.search || target.hash) return null;
return target.href;
}
export function createCheckoutToken(payload, secret, now = Date.now()) {
const body = Buffer.from(JSON.stringify({ ...payload, expires: now + lifetimeMs })).toString('base64url');
return body + '.' + signature(body, secret);
}
export function readCheckoutToken(token, secret, shopOrigin, now = Date.now()) {
if (typeof token !== 'string' || token.length > 8192) throw new Error('Invalid checkout');
const [body, signed, extra] = token.split('.');
if (!body || !signed || extra !== undefined) throw new Error('Invalid checkout');
const expected = Buffer.from(signature(body, secret));
const actual = Buffer.from(signed);
if (actual.length !== expected.length || !timingSafeEqual(actual, expected)) throw new Error('Invalid checkout');
const payload = JSON.parse(Buffer.from(body, 'base64url').toString());
const target = new URL(payload.return_url);
if (!Number.isSafeInteger(payload.expires) || payload.expires <= now || payload.expires > now + lifetimeMs ||
target.origin !== shopOrigin || !returnPathPattern.test(target.pathname) || target.search || target.hash ||
!Number.isSafeInteger(payload.amount_cents) || payload.amount_cents <= 0 || !payload.jsapi_params?.package) {
throw new Error('Invalid checkout');
}
return payload;
}
// A standalone document ensures WeChat sees Memind's URL rather than a shop SPA entry URL.
export function checkoutHtml(nonce) {
return `<!doctype html><html lang="zh-CN"><head><meta charset="utf-8">
<meta name="viewport" content="width=device-width,initial-scale=1"><title>商城订单付款</title>
<style nonce="${nonce}">body{font-family:system-ui,sans-serif;background:#f5f6f8;color:#17212b;margin:0;padding:28px 20px}main{max-width:420px;margin:40px auto;background:white;padding:28px;border-radius:16px}h1{font-size:22px}#amount{font-size:36px;font-weight:700}button{font:inherit;width:100%;padding:14px;margin-top:14px;border:0;border-radius:9px;background:#07a857;color:white}button:disabled{opacity:.5}#back{background:#edf0f3;color:#17212b}p{line-height:1.6}</style></head>
<body><main><h1>商城订单付款</h1><p id="amount"></p><p id="message" role="status">正在加载付款信息…</p>
<button id="pay" disabled>微信支付</button><button id="back" hidden>返回商城订单</button></main>
<script nonce="${nonce}">
const pay = document.getElementById('pay');
const back = document.getElementById('back');
const message = document.getElementById('message');
let checkout;
let paying = false;
function ready() { pay.disabled = !checkout || !window.WeixinJSBridge || paying; }
document.addEventListener('WeixinJSBridgeReady', ready);
back.onclick = () => { if (checkout) window.location.replace(checkout.return_url); };
pay.onclick = () => {
if (!checkout || paying || !window.WeixinJSBridge) return;
if (Date.now() >= checkout.expires) { message.textContent = '付款链接已过期,请返回商城重新发起支付。'; pay.disabled = true; return; }
paying = true; ready();
window.WeixinJSBridge.invoke('getBrandWCPayRequest', checkout.jsapi_params, (result) => {
paying = false;
if (result.err_msg === 'get_brand_wcpay_request:ok') {
message.textContent = '正在返回商城确认支付结果…';
window.location.replace(checkout.return_url);
} else {
message.textContent = result.err_msg === 'get_brand_wcpay_request:cancel'
? '已取消付款,可重新支付或返回商城。'
: '微信支付未完成,请返回商城重试。' + (result.err_msg || '');
ready();
}
});
};
(async () => {
try {
const token = new URLSearchParams(window.location.hash.slice(1)).get('checkout');
history.replaceState(null, '', window.location.pathname);
if (!token) throw new Error('付款链接无效,请返回商城重新发起支付。');
const response = await fetch('/auth/one-shop/payment', {
method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ token }),
});
if (!response.ok) throw new Error('付款链接已过期或无效,请返回商城重新发起支付。');
checkout = await response.json();
document.getElementById('amount').textContent = '¥' + (checkout.amount_cents / 100).toFixed(2);
message.textContent = /MicroMessenger/i.test(navigator.userAgent)
? '请点击微信支付,付款后将返回商城确认订单。'
: '请在微信内打开商城订单后重新发起支付。';
back.hidden = false; ready();
} catch (error) { message.textContent = error.message; }
})();
</script></body></html>`;
}