Bridge OneShop WeChat login and payments

This commit is contained in:
john
2026-11-18 20:15:10 +08:00
parent 5db1292e73
commit cbaeb90c25
5 changed files with 267 additions and 1 deletions
+5
View File
@@ -18,6 +18,11 @@ H5_PORT=8081
# pnpm dev / dev-core 在未显式覆盖时会把 H5_PUBLIC_BASE_URL 设为 8081。
H5_PUBLIC_BASE_URL=http://127.0.0.1:5173
# OneShop 共用微信 OAuth 和付款桥接,按需启用。
# ONE_SHOP_PUBLIC_URL=https://shop.example.com
# ONE_SHOP_INTERNAL_URL=http://127.0.0.1:18808
# MEMIND_SHOP_BRIDGE_SECRET=<与商城一致的随机密钥,至少32字节>
# 访问统计平台说明(Umami 唯一;Rybbit 已退役 2026-08)见 docs/analytics-platform.md
# MEMIND_ANALYTICS_ENABLED=true
# MEMIND_ANALYTICS_URL=http://127.0.0.1:3100
+9
View File
@@ -38,6 +38,7 @@ import { attachPortalBillingRoutes } from './server/portal-billing-routes.mjs';
import { attachPortalCoreAuthRoutes } from './server/portal-core-auth-routes.mjs';
import { attachPortalWechatAuthRoutes } from './server/portal-wechat-auth-routes.mjs';
import { attachPortalWebhookRoutes } from './server/portal-webhook-routes.mjs';
import { attachPortalOneShopRoutes } from './server/portal-one-shop-routes.mjs';
import { attachPortalWikiRoutes } from './server/portal-wiki-routes.mjs';
import { bootstrapPortalAgentServices } from './server/portal-agent-services-bootstrap.mjs';
import { bootstrapPortalAuthServices } from './server/portal-auth-services-bootstrap.mjs';
@@ -794,6 +795,14 @@ const wechatMpBody = express.text({
type: ['text/xml', 'application/xml'],
limit: '128kb',
});
attachPortalOneShopRoutes({
app,
jsonBody,
wechatNotifyBody,
userAuthReady,
getUserAuth: () => userAuth,
userToken,
});
attachPortalWebhookRoutes({
app,
userAuthReady,
+154
View File
@@ -0,0 +1,154 @@
import { randomBytes, timingSafeEqual } from 'node:crypto';
import {
createWechatPayClient,
loadWechatPayConfig,
WECHAT_NOTIFY_SUCCESS_V2,
} from '../wechat-pay.mjs';
const statePattern = /^[a-f0-9]{48}$/;
const orderPattern = /^OS[A-F0-9]{30}$/;
const notifyPath = '/webhooks/one-shop/wechat-pay';
function hasBridgeKey(req, bridgeKey) {
const presented = Buffer.from(req.get('x-one-shop-bridge-key') || '');
return presented.length === bridgeKey.length && timingSafeEqual(presented, bridgeKey);
}
function buildShopPayClient() {
const config = loadWechatPayConfig();
if (!config.enabled || config.skipNotifyVerify ||
(config.apiVersion === 'v3' && !config.platformCert)) {
return null;
}
return {
...createWechatPayClient({
...config, notifyUrl: new URL(notifyPath, config.notifyUrl).href,
}),
mchId: config.mchId,
};
}
export function attachPortalOneShopRoutes({
app,
jsonBody,
wechatNotifyBody,
userAuthReady,
getUserAuth,
userToken,
shopPublicUrl = process.env.ONE_SHOP_PUBLIC_URL,
shopInternalUrl = process.env.ONE_SHOP_INTERNAL_URL || shopPublicUrl,
sharedSecret = process.env.MEMIND_SHOP_BRIDGE_SECRET || '',
getPayClient = buildShopPayClient,
fetchFn = fetch,
logger = console,
}) {
const bridgeKey = Buffer.from(sharedSecret);
if (bridgeKey.length < 32 || !shopPublicUrl || !shopInternalUrl) return;
const shopOrigin = new URL(shopPublicUrl).origin;
const shopBackend = new URL(shopInternalUrl).origin;
const notifyShop = async (path, payload) => {
const response = await fetchFn(new URL(path, shopBackend), {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'X-One-Shop-Bridge-Key': sharedSecret,
},
body: JSON.stringify(payload),
redirect: 'error',
signal: AbortSignal.timeout(4500),
});
if (!response.ok) {
throw new Error(`OneShop rejected ${path}: HTTP ${response.status}`);
}
};
app.get('/auth/one-shop/continue', async (req, res) => {
res.set('Cache-Control', 'no-store').set('Referrer-Policy', 'no-referrer');
const state = req.query.state;
if (typeof state !== 'string' || !statePattern.test(state)) {
return res.status(400).send('商城登录请求无效');
}
try {
await userAuthReady;
const user = await getUserAuth()?.getMe(userToken(req));
if (!user) {
const returnTo = `/auth/one-shop/continue?state=${state}`;
const fromWechat = /MicroMessenger|WindowsWechat/i.test(req.get('user-agent') || '');
const query = new URLSearchParams({ return_to: returnTo });
if (fromWechat) query.set('from', 'wechat');
return res.redirect(302, `/?${query}`);
}
const ticket = randomBytes(32).toString('hex');
await notifyShop('/api/internal/memind/login', {
state, ticket, memind_user_id: String(user.id),
});
const target = new URL('/login', shopOrigin);
target.hash = new URLSearchParams({ wechat_state: state, ticket }).toString();
return res.redirect(302, target.href);
} catch (error) {
logger.warn('OneShop login handoff failed:', error.message);
return res.status(502).send('商城登录交接失败,请返回商城重新发起微信登录');
}
});
app.post('/internal/one-shop/wechat-pay', jsonBody, async (req, res) => {
if (!hasBridgeKey(req, bridgeKey)) return res.sendStatus(403);
const { out_trade_no: outTradeNo, amount_cents: amountCents, memind_user_id: userId } = 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))) {
return res.sendStatus(400);
}
try {
const pay = getPayClient();
if (!pay?.enabled) return res.sendStatus(503);
const order = { outTradeNo, description: '商城积分充值', amountCents };
if (userId) {
await userAuthReady;
const openid = await getUserAuth()?.getWechatOpenidForUser(userId, pay.appId);
if (!openid) return res.sendStatus(409);
const { jsapiParams } = await pay.createJsapiOrder({ ...order, openid });
return res.json({ jsapi_params: jsapiParams });
}
const { codeUrl } = await pay.createNativeOrder(order);
return res.json({ code_url: codeUrl });
} catch (error) {
logger.warn('OneShop WeChat prepay failed:', error.message);
return res.sendStatus(502);
}
});
app.post(notifyPath, wechatNotifyBody, async (req, res) => {
let pay;
try {
pay = getPayClient();
if (!pay?.enabled) return res.sendStatus(503);
const body = Buffer.isBuffer(req.body) ? req.body.toString('utf8') : String(req.body ?? '');
const { transaction } = pay.verifyNotify({ headers: req.headers, body });
const {
out_trade_no: outTradeNo, transaction_id: transactionId, trade_state: tradeState,
appid, mchid, amount,
} = transaction;
if (!orderPattern.test(outTradeNo || '') || typeof transactionId !== 'string' ||
!transactionId || tradeState !== 'SUCCESS' || appid !== pay.appId || mchid !== pay.mchId ||
!Number.isSafeInteger(amount?.total) || amount.total <= 0 ||
(amount.currency && amount.currency !== 'CNY')) {
throw new Error('Invalid OneShop WeChat transaction');
}
await notifyShop('/api/internal/memind/payment', {
out_trade_no: outTradeNo, transaction_id: transactionId, amount_cents: amount.total,
});
if (pay.apiVersion === 'v2') return res.type('text/xml').send(WECHAT_NOTIFY_SUCCESS_V2);
return res.json({ code: 'SUCCESS', message: '成功' });
} catch (error) {
logger.warn('OneShop WeChat callback failed:', error.message);
if (pay?.apiVersion === 'v2') {
return res.status(500).type('text/xml').send(
'<xml><return_code><![CDATA[FAIL]]></return_code><return_msg><![CDATA[处理失败]]></return_msg></xml>',
);
}
return res.status(500).json({ code: 'FAIL', message: '处理失败' });
}
});
}
+96
View File
@@ -0,0 +1,96 @@
import assert from 'node:assert/strict';
import { once } from 'node:events';
import test from 'node:test';
import express from 'express';
import { attachPortalOneShopRoutes } from './portal-one-shop-routes.mjs';
test('OneShop login handoff and signed notification forwarding', async (t) => {
const app = express();
const state = 'a'.repeat(48);
const outTradeNo = 'OS' + 'A'.repeat(30);
const bridgeKey = 'test-only-shared-secret-for-oneshop';
const forwards = [];
let forwardStatus = 200;
let merchant = 'merchant-1';
attachPortalOneShopRoutes({
app,
jsonBody: express.json(),
wechatNotifyBody: express.raw({ type: '*/*' }),
userAuthReady: Promise.resolve(),
getUserAuth: () => ({
getMe: async (token) => token === 'fixture-session' ? { id: 'memind-user' } : null,
}),
userToken: (req) => req.get('cookie'),
shopPublicUrl: 'https://shop.example.test',
shopInternalUrl: 'http://shop-internal.example.test',
sharedSecret: bridgeKey,
getPayClient: () => ({
enabled: true,
apiVersion: 'v3',
appId: 'wx-app',
mchId: 'merchant-1',
createNativeOrder: async () => ({ codeUrl: 'weixin://fixture' }),
verifyNotify: ({ body }) => {
if (body !== 'signed fixture') throw new Error('invalid signature');
return { transaction: {
appid: 'wx-app', mchid: merchant, out_trade_no: outTradeNo,
transaction_id: 'wx-txn-1', trade_state: 'SUCCESS', amount: { total: 100, currency: 'CNY' },
} };
},
}),
fetchFn: async (url, options) => {
assert.equal(url.origin, 'http://shop-internal.example.test');
assert.equal(options.headers['X-One-Shop-Bridge-Key'], bridgeKey);
forwards.push([url.pathname, JSON.parse(options.body)]);
return new Response(null, { status: forwardStatus });
},
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 continuePath = `/auth/one-shop/continue?state=${state}`;
const anonymous = await fetch(base + continuePath, {
redirect: 'manual', headers: { 'User-Agent': 'MicroMessenger' },
});
const portal = new URL(anonymous.headers.get('location'), base);
assert.equal(portal.searchParams.get('return_to'), continuePath);
assert.equal(portal.searchParams.get('from'), 'wechat');
const authed = await fetch(base + continuePath, {
redirect: 'manual', headers: { Cookie: 'fixture-session' },
});
const handoff = new URL(authed.headers.get('location'));
const ticket = new URLSearchParams(handoff.hash.slice(1)).get('ticket');
assert.equal(handoff.origin, 'https://shop.example.test');
assert.match(ticket, /^[a-f0-9]{64}$/);
assert.deepEqual(forwards.shift(), ['/api/internal/memind/login', {
state, ticket, memind_user_id: 'memind-user',
}]);
const prepay = (key) => fetch(base + '/internal/one-shop/wechat-pay', {
method: 'POST',
headers: { 'Content-Type': 'application/json', 'X-One-Shop-Bridge-Key': key },
body: JSON.stringify({ out_trade_no: outTradeNo, amount_cents: 100 }),
});
assert.equal((await prepay('wrong-key')).status, 403);
assert.deepEqual(await (await prepay(bridgeKey)).json(), { code_url: 'weixin://fixture' });
const notify = (body) => fetch(base + '/webhooks/one-shop/wechat-pay', {
method: 'POST', headers: { 'Content-Type': 'text/plain' }, body,
});
assert.equal((await notify('invalid signature')).status, 500);
merchant = 'wrong-merchant';
assert.equal((await notify('signed fixture')).status, 500);
assert.equal(forwards.length, 0);
merchant = 'merchant-1';
forwardStatus = 503;
assert.equal((await notify('signed fixture')).status, 500);
forwardStatus = 200;
assert.equal((await notify('signed fixture')).status, 200);
assert.deepEqual(forwards, Array.from({ length: 2 }, () => [
'/api/internal/memind/payment',
{ out_trade_no: outTradeNo, transaction_id: 'wx-txn-1', amount_cents: 100 },
]));
});
+3 -1
View File
@@ -130,13 +130,15 @@ export function parseXmlFields(xml) {
function normalizeV2Transaction(fields) {
return {
appid: fields.appid,
mchid: fields.mch_id,
out_trade_no: fields.out_trade_no,
transaction_id: fields.transaction_id,
trade_state: fields.result_code === 'SUCCESS' ? 'SUCCESS' : fields.result_code,
result_code: fields.result_code,
return_code: fields.return_code,
total_fee: fields.total_fee ? Number(fields.total_fee) : undefined,
amount: fields.total_fee ? { total: Number(fields.total_fee) } : undefined,
amount: fields.total_fee ? { total: Number(fields.total_fee), currency: fields.fee_type } : undefined,
};
}