Host shop cash checkout on the Memind payment origin
Memind CI / Test, build, and release guards (push) Has been cancelled

This commit is contained in:
john
2026-11-19 09:35:00 +08:00
parent 3012e097ab
commit e3b06a3066
4 changed files with 231 additions and 2 deletions
@@ -0,0 +1,11 @@
# 商城微信付款页面 URL 未注册
用户在 iOS 微信中从商城登录进入商品付款页,微信提示当前页面 URL 未注册,错误中的 URL 仍是商城 `/login` 登录回调地址。后端预支付已成功,但收银台从商城域名下拉起,支付授权目录未匹配;SPA 路由变化没有替换微信识别的初始文档。
修复:现金订单桥接下单携带服务端订单 ID,Memind 返回 `H5_PUBLIC_BASE_URL` Origin 下 `/one-shop-pay` 的签名付款链接。商城使用整页导航。独立收银台通过 POST 验证片段中的短时 HMAC token,显示服务端金额,点击后调用微信。成功或手动返回时整页回到固定商城原订单,由商城读取微信回调后的状态。
链接有效期 5 分钟,签名覆盖金额、预支付参数和固定返回地址。链接不携带商城登录 token 或桥接密钥,不允许浏览器修改价格或返回站点。页面禁止缓存、外部资源和嵌入,返回地址仅允许商城订单路径。扫码支付和旧充值桥接保持兼容。
配置核验:生产 `H5_PUBLIC_BASE_URL=https://m.tkmind.cn`,微信商户平台 JSAPI 支付授权目录需匹配(建议 `https://m.tkmind.cn/`)。无法通过本地自动化读取商户后台的实际授权目录,最终需微信真机低金额付款验收。
验证:`node --test server/one-shop-checkout.test.mjs server/portal-one-shop-routes.test.mjs server/one-shop-cash-payment.test.mjs wechat-pay.test.mjs`,覆盖签名篡改、过期、外站返回拒绝、服务端金额、取消重试和成功返回。商城前后台执行 `npm run build`。不主动扣款。
+80
View File
@@ -0,0 +1,80 @@
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');
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 || !/^\/my\/orders\/[1-9]\d*\/pay$/.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>`;
}
+106
View File
@@ -0,0 +1,106 @@
import assert from 'node:assert/strict';
import { once } from 'node:events';
import test from 'node:test';
import vm from 'node:vm';
import express from 'express';
import { attachPortalOneShopRoutes } from './portal-one-shop-routes.mjs';
import { checkoutHtml, createCheckoutToken, readCheckoutToken } from './one-shop-checkout.mjs';
const key = 'test-only-shop-checkout-secret-32bytes';
const origin = 'https://shop.example.test';
const params = { appId: 'wx-app', package: 'prepay_id=test', paySign: 'test-sign' };
const payload = { amount_cents: 1234, return_url: origin + '/my/orders/42/pay', jsapi_params: params };
test('checkout handoff rejects altered, expired, wrong-key and foreign-return tokens', () => {
const now = 1_000_000;
const token = createCheckoutToken(payload, key, now);
assert.equal(readCheckoutToken(token, key, origin, now).amount_cents, 1234);
assert.throws(() => readCheckoutToken(token + 'x', key, origin, now));
assert.throws(() => readCheckoutToken(token, 'wrong-key', origin, now));
assert.throws(() => readCheckoutToken(token, key, origin, now + 300_000));
assert.throws(() => readCheckoutToken(token, key, 'https://other.example.test', now));
for (const return_url of ['https://evil.example/', origin + '//evil', origin + '/my/orders/42/pay?return=evil']) {
assert.throws(() => readCheckoutToken(createCheckoutToken({ ...payload, return_url }, key, now), key, origin, now));
}
});
test('cash prepay returns Memind checkout and signed data without trusting browser prices or Host', async (t) => {
const app = express();
let created = 0;
attachPortalOneShopRoutes({
app, jsonBody: express.json(), wechatNotifyBody: express.raw({ type: '*/*' }),
userAuthReady: Promise.resolve(),
getUserAuth: () => ({ getWechatOpenidForUser: async (user, appId) => {
assert.equal(user, 'user-1'); assert.equal(appId, 'wx-app'); return 'openid-1';
} }),
userToken: () => '', shopPublicUrl: origin, shopInternalUrl: origin,
sharedSecret: key, paymentPublicUrl: 'https://memind.example.test',
getPayClient: () => ({ enabled: true, appId: 'wx-app', createJsapiOrder: async (order) => {
assert.equal(order.amountCents, 1234); assert.equal(order.openid, 'openid-1');
created++; return { jsapiParams: params };
} }), logger: { warn() {} },
});
const server = app.listen(0, '127.0.0.1');
t.after(() => new Promise(resolve => server.close(resolve)));
await once(server, 'listening');
const base = `http://127.0.0.1:${server.address().port}`;
const prepay = (secret, order_id = 42) => fetch(base + '/internal/one-shop/wechat-pay', {
method: 'POST', headers: { 'Content-Type': 'application/json', 'X-One-Shop-Bridge-Key': secret, Host: 'evil.example' },
body: JSON.stringify({ out_trade_no: 'OC' + 'A'.repeat(30), amount_cents: 1234, memind_user_id: 'user-1', order_id }),
});
assert.equal((await prepay('bad')).status, 403);
assert.equal((await prepay(key, '../evil')).status, 400);
assert.equal(created, 0);
const response = await prepay(key);
assert.equal(response.headers.get('cache-control'), 'no-store');
const url = new URL((await response.json()).checkout_url);
assert.equal(url.origin, 'https://memind.example.test');
assert.equal(url.pathname, '/one-shop-pay');
assert.equal(url.search, '');
const token = new URLSearchParams(url.hash.slice(1)).get('checkout');
const redeem = (body) => fetch(base + '/auth/one-shop/payment', {
method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(body),
});
const checkout = await redeem({ token, amount_cents: 1, return_url: 'https://evil.example' });
assert.equal(checkout.headers.get('cache-control'), 'no-store');
const data = await checkout.json();
assert.equal(data.amount_cents, 1234);
assert.equal(data.return_url, payload.return_url);
assert.deepEqual(data.jsapi_params, params);
assert.equal((await redeem({ token: token + 'x' })).status, 410);
assert.equal((await redeem({})).status, 410);
const page = await fetch(base + '/one-shop-pay');
assert.match(page.headers.get('content-security-policy'), /frame-ancestors 'none'/);
assert.equal(page.headers.get('referrer-policy'), 'no-referrer');
assert.equal(page.headers.get('cache-control'), 'no-store');
assert.match(await page.text(), /商城订单付款/);
});
test('checkout invokes bridge on user click, handles cancellation, and returns for server confirmation', async () => {
const elements = Object.fromEntries(['pay', 'back', 'message', 'amount'].map(id => [id, {}]));
const redirects = [];
let callback;
let invokes = 0;
const script = checkoutHtml('fixture').match(/<script[^>]*>([\s\S]*?)<\/script>/)[1];
const browser = {
document: { getElementById: id => elements[id], addEventListener() {} },
navigator: { userAgent: 'MicroMessenger' }, history: { replaceState() {} }, URLSearchParams,
window: { location: { hash: '#checkout=fixture', pathname: '/one-shop-pay', replace: url => redirects.push(url) },
WeixinJSBridge: { invoke: (name, data, cb) => {
assert.equal(name, 'getBrandWCPayRequest'); assert.deepEqual(data, params); invokes++; callback = cb;
} } },
fetch: async () => ({ ok: true, json: async () => ({ ...payload, expires: Date.now() + 60_000 }) }),
};
await vm.runInNewContext(script, browser);
assert.equal(invokes, 0);
assert.equal(elements.amount.textContent, '¥12.34');
elements.pay.onclick();
elements.pay.onclick();
assert.equal(invokes, 1);
callback({ err_msg: 'get_brand_wcpay_request:cancel' });
assert.equal(redirects.length, 0);
assert.match(elements.message.textContent, /已取消/);
elements.pay.onclick();
callback({ err_msg: 'get_brand_wcpay_request:ok' });
assert.deepEqual(redirects, [payload.return_url]);
});
+34 -2
View File
@@ -1,5 +1,6 @@
import { existsSync } from 'node:fs';
import { randomBytes, timingSafeEqual } from 'node:crypto';
import { checkoutHtml, createCheckoutToken, readCheckoutToken } from './one-shop-checkout.mjs';
import {
createWechatPayClient,
loadWechatPayConfig,
@@ -44,6 +45,7 @@ export function attachPortalOneShopRoutes({
shopPublicUrl = process.env.ONE_SHOP_PUBLIC_URL,
shopInternalUrl = process.env.ONE_SHOP_INTERNAL_URL || shopPublicUrl,
sharedSecret = process.env.MEMIND_SHOP_BRIDGE_SECRET || '',
paymentPublicUrl = process.env.H5_PUBLIC_BASE_URL || loadWechatPayConfig().notifyUrl,
getPayClient = buildShopPayClient,
fetchFn = fetch,
logger = console,
@@ -115,11 +117,13 @@ export function attachPortalOneShopRoutes({
});
app.post('/internal/one-shop/wechat-pay', jsonBody, async (req, res) => {
res.set('Cache-Control', 'no-store');
if (!hasBridgeKey(req, bridgeKey)) return res.sendStatus(403);
const { out_trade_no: outTradeNo, amount_cents: amountCents, memind_user_id: userId } = req.body || {};
const { out_trade_no: outTradeNo, amount_cents: amountCents, memind_user_id: userId, order_id: orderId } = req.body || {};
if (typeof outTradeNo !== 'string' || !orderPattern.test(outTradeNo) ||
!Number.isSafeInteger(amountCents) || amountCents <= 0 || amountCents > 100_000_000 ||
(userId != null && (typeof userId !== 'string' || !userId || userId.length > 128))) {
(userId != null && (typeof userId !== 'string' || !userId || userId.length > 128)) ||
(orderId != null && (!Number.isSafeInteger(orderId) || orderId <= 0 || !outTradeNo.startsWith('OC')))) {
return res.sendStatus(400);
}
try {
@@ -131,6 +135,16 @@ export function attachPortalOneShopRoutes({
const openid = await getUserAuth()?.getWechatOpenidForUser(userId, pay.appId);
if (!openid) return res.sendStatus(409);
const { jsapiParams } = await pay.createJsapiOrder({ ...order, openid });
if (orderId) {
const token = createCheckoutToken({
jsapi_params: jsapiParams, amount_cents: amountCents,
return_url: new URL(`/my/orders/${orderId}/pay`, shopOrigin).href,
}, sharedSecret);
// Use the configured public payment origin, never an untrusted Host header.
const publicOrigin = new URL(paymentPublicUrl).origin;
if (!['https:', 'http:'].includes(new URL(paymentPublicUrl).protocol)) throw new Error('Invalid payment origin');
return res.json({ checkout_url: publicOrigin + '/one-shop-pay#checkout=' + token });
}
return res.json({ jsapi_params: jsapiParams });
}
const { codeUrl } = await pay.createNativeOrder(order);
@@ -141,6 +155,24 @@ export function attachPortalOneShopRoutes({
}
});
app.get('/one-shop-pay', (req, res) => {
const nonce = randomBytes(18).toString('base64');
res.set({
'Cache-Control': 'no-store', 'Referrer-Policy': 'no-referrer', 'X-Content-Type-Options': 'nosniff',
'Content-Security-Policy': `default-src 'none'; script-src 'nonce-${nonce}'; style-src 'nonce-${nonce}'; connect-src 'self'; base-uri 'none'; frame-ancestors 'none'; form-action 'none'`,
});
return res.type('html').send(checkoutHtml(nonce));
});
app.post('/auth/one-shop/payment', jsonBody, (req, res) => {
res.set('Cache-Control', 'no-store').set('Referrer-Policy', 'no-referrer');
try {
return res.json(readCheckoutToken(req.body?.token, sharedSecret, shopOrigin));
} catch {
return res.status(410).json({ error: '付款链接已过期或无效,请返回商城重新发起支付' });
}
});
app.post('/internal/one-shop/wechat-refund-ready', jsonBody, (req, res) => {
if (!hasBridgeKey(req, bridgeKey)) return res.sendStatus(403);
const pay = getPayClient();