Support direct shop cash payments, cancellation and refunds
Memind CI / Test, build, and release guards (push) Failing after 18m59s

This commit is contained in:
john
2026-11-19 09:14:26 +08:00
parent 0cbc9da957
commit 3012e097ab
4 changed files with 216 additions and 13 deletions
+79
View File
@@ -0,0 +1,79 @@
import assert from 'node:assert/strict';
import test from 'node:test';
import { MockAgent, getGlobalDispatcher, setGlobalDispatcher } from 'undici';
import { createWechatPayClient } from '../wechat-pay.mjs';
test('V2 close reconciles a payment racing with cancellation', async () => {
const previous = getGlobalDispatcher();
const mock = new MockAgent();
mock.disableNetConnect();
setGlobalDispatcher(mock);
try {
const pool = mock.get('https://api.mch.weixin.qq.com');
const reply = (fields) => '<xml><return_code>SUCCESS</return_code><result_code>SUCCESS</result_code>' + fields + '</xml>';
pool.intercept({ path: '/pay/orderquery', method: 'POST' }).reply(200, reply('<trade_state>NOTPAY</trade_state>'));
pool.intercept({ path: '/pay/closeorder', method: 'POST' }).reply(200, '<xml><return_code>SUCCESS</return_code><result_code>FAIL</result_code><err_code>ORDERPAID</err_code></xml>');
pool.intercept({ path: '/pay/orderquery', method: 'POST' }).reply(200, reply('<trade_state>SUCCESS</trade_state><total_fee>1234</total_fee><transaction_id>wx-race</transaction_id>'));
const pay = createWechatPayClient({ enabled: true, apiVersion: 'v2', appId: 'test', mchId: 'test', apiKey: 'test-key' });
assert.deepEqual(await pay.closeOrder('OC' + 'A'.repeat(30)), {
status: 'paid', amount_cents: 1234, transaction_id: 'wx-race',
});
mock.assertNoPendingInterceptors();
} finally {
setGlobalDispatcher(previous);
await mock.close();
}
});
test('V2 unknown order can safely release reserved stock', async () => {
const previous = getGlobalDispatcher();
const mock = new MockAgent();
mock.disableNetConnect();
setGlobalDispatcher(mock);
try {
mock.get('https://api.mch.weixin.qq.com')
.intercept({ path: '/pay/orderquery', method: 'POST' })
.reply(200, '<xml><return_code>SUCCESS</return_code><result_code>FAIL</result_code><err_code>ORDERNOTEXIST</err_code></xml>');
const pay = createWechatPayClient({ enabled: true, apiVersion: 'v2', appId: 'test', mchId: 'test', apiKey: 'test-key' });
assert.deepEqual(await pay.closeOrder('OC' + 'B'.repeat(30)), { status: 'closed' });
mock.assertNoPendingInterceptors();
} finally {
setGlobalDispatcher(previous);
await mock.close();
}
});
test('V3 refund stays processing until WeChat confirms success', async () => {
const { generateKeyPairSync } = await import('node:crypto');
const { privateKey } = generateKeyPairSync('rsa', { modulusLength: 2048 });
const previous = getGlobalDispatcher();
const mock = new MockAgent();
mock.disableNetConnect();
setGlobalDispatcher(mock);
try {
const outTradeNo = 'OC' + 'C'.repeat(30);
const refundNo = 'RF' + outTradeNo.slice(2);
const pool = mock.get('https://api.mch.weixin.qq.com');
const body = JSON.stringify({
out_trade_no: outTradeNo, out_refund_no: refundNo,
amount: { refund: 1234, total: 1234, currency: 'CNY' },
});
for (const status of ['PROCESSING', 'SUCCESS']) {
pool.intercept({ path: '/v3/refund/domestic/refunds', method: 'POST', body })
.reply(200, { status: 'PROCESSING' });
pool.intercept({ path: '/v3/refund/domestic/refunds/' + refundNo, method: 'GET' })
.reply(200, { status });
}
const pay = createWechatPayClient({
enabled: true, apiVersion: 'v3', appId: 'test', mchId: 'test', serialNo: 'test',
privateKey: privateKey.export({ type: 'pkcs8', format: 'pem' }),
});
const request = { outTradeNo, refundNo, amountCents: 1234 };
assert.deepEqual(await pay.refundOrder(request), { status: 'processing' });
assert.deepEqual(await pay.refundOrder(request), { status: 'refunded' });
mock.assertNoPendingInterceptors();
} finally {
setGlobalDispatcher(previous);
await mock.close();
}
});
+36 -2
View File
@@ -1,3 +1,4 @@
import { existsSync } from 'node:fs';
import { randomBytes, timingSafeEqual } from 'node:crypto';
import {
createWechatPayClient,
@@ -6,7 +7,7 @@ import {
} from '../wechat-pay.mjs';
const statePattern = /^[a-f0-9]{48}$/;
const orderPattern = /^OS[A-F0-9]{30}$/;
const orderPattern = /^O[SC][A-F0-9]{30}$/;
const notifyPath = '/webhooks/one-shop/wechat-pay';
function hasBridgeKey(req, bridgeKey) {
@@ -25,6 +26,10 @@ function buildShopPayClient() {
...config, notifyUrl: new URL(notifyPath, config.notifyUrl).href,
}),
mchId: config.mchId,
refundEnabled: config.apiVersion === 'v3' || Boolean(
process.env.H5_WECHAT_REFUND_CERT_PATH && process.env.H5_WECHAT_REFUND_KEY_PATH &&
existsSync(process.env.H5_WECHAT_REFUND_CERT_PATH) && existsSync(process.env.H5_WECHAT_REFUND_KEY_PATH)
),
};
}
@@ -120,7 +125,7 @@ export function attachPortalOneShopRoutes({
try {
const pay = getPayClient();
if (!pay?.enabled) return res.sendStatus(503);
const order = { outTradeNo, description: '商城积分充值', amountCents };
const order = { outTradeNo, description: outTradeNo.startsWith('OC') ? '商城商品订单' : '商城积分充值', amountCents };
if (userId) {
await userAuthReady;
const openid = await getUserAuth()?.getWechatOpenidForUser(userId, pay.appId);
@@ -136,6 +141,35 @@ export function attachPortalOneShopRoutes({
}
});
app.post('/internal/one-shop/wechat-refund-ready', jsonBody, (req, res) => {
if (!hasBridgeKey(req, bridgeKey)) return res.sendStatus(403);
const pay = getPayClient();
return res.json({ ready: Boolean(pay?.enabled && pay.refundEnabled) });
});
for (const action of ['close', 'refund']) {
app.post(`/internal/one-shop/wechat-${action}`, jsonBody, async (req, res) => {
if (!hasBridgeKey(req, bridgeKey)) return res.sendStatus(403);
const outTradeNo = req.body?.out_trade_no;
const amountCents = req.body?.amount_cents;
if (!/^OC[A-F0-9]{30}$/.test(outTradeNo || '') ||
(action === 'refund' && (!Number.isSafeInteger(amountCents) || amountCents <= 0 || amountCents > 100_000_000))) {
return res.sendStatus(400);
}
try {
const pay = getPayClient();
if (!pay?.enabled) return res.sendStatus(503);
const result = action === 'close'
? await pay.closeOrder(outTradeNo)
: await pay.refundOrder({ outTradeNo, refundNo: 'RF' + outTradeNo.slice(2), amountCents });
return res.json(result);
} catch (error) {
logger.warn('OneShop WeChat order operation failed:', error.message);
return res.sendStatus(502);
}
});
}
app.post(notifyPath, wechatNotifyBody, async (req, res) => {
let pay;
try {