diff --git a/.env.example b/.env.example index a74a1de..153786d 100644 --- a/.env.example +++ b/.env.example @@ -22,6 +22,9 @@ H5_PUBLIC_BASE_URL=http://127.0.0.1:5173 # ONE_SHOP_PUBLIC_URL=https://shop.example.com # ONE_SHOP_INTERNAL_URL=http://127.0.0.1:18808 # MEMIND_SHOP_BRIDGE_SECRET=<与商城一致的随机密钥,至少32字节> +# 微信 V2 原路退款所需商户 API 证书和私钥,路径仅在服务端配置。 +# H5_WECHAT_REFUND_CERT_PATH=/secure/apiclient_cert.pem +# H5_WECHAT_REFUND_KEY_PATH=/secure/apiclient_key.pem # 访问统计平台说明(Umami 唯一;Rybbit 已退役 2026-08)见 docs/analytics-platform.md # MEMIND_ANALYTICS_ENABLED=true diff --git a/server/one-shop-cash-payment.test.mjs b/server/one-shop-cash-payment.test.mjs new file mode 100644 index 0000000..6e8e278 --- /dev/null +++ b/server/one-shop-cash-payment.test.mjs @@ -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) => 'SUCCESSSUCCESS' + fields + ''; + pool.intercept({ path: '/pay/orderquery', method: 'POST' }).reply(200, reply('NOTPAY')); + pool.intercept({ path: '/pay/closeorder', method: 'POST' }).reply(200, 'SUCCESSFAILORDERPAID'); + pool.intercept({ path: '/pay/orderquery', method: 'POST' }).reply(200, reply('SUCCESS1234wx-race')); + 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, 'SUCCESSFAILORDERNOTEXIST'); + 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(); + } +}); diff --git a/server/portal-one-shop-routes.mjs b/server/portal-one-shop-routes.mjs index ec74b9a..d2ff0b5 100644 --- a/server/portal-one-shop-routes.mjs +++ b/server/portal-one-shop-routes.mjs @@ -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 { diff --git a/wechat-pay.mjs b/wechat-pay.mjs index 0ade1c7..90720b8 100644 --- a/wechat-pay.mjs +++ b/wechat-pay.mjs @@ -1,3 +1,4 @@ +import https from 'node:https'; import crypto from 'node:crypto'; import fs from 'node:fs'; import { fetch } from 'undici'; @@ -142,7 +143,7 @@ function normalizeV2Transaction(fields) { }; } -async function wechatV2Request(config, path, fields) { +async function wechatV2Request(config, path, fields, allowTradeFailure = false) { const payload = { appid: config.appId, mch_id: config.mchId, @@ -151,20 +152,43 @@ async function wechatV2Request(config, path, fields) { }; payload.sign = signV2Params(payload, config.apiKey); const body = buildXml(payload); - const res = await fetch(`${API_BASE}${path}`, { - method: 'POST', - headers: { 'Content-Type': 'text/xml' }, - body, - }); - const text = await res.text(); + let text; + let ok; + if (path.startsWith('/secapi/')) { + const cert = process.env.H5_WECHAT_REFUND_CERT_PATH; + const key = process.env.H5_WECHAT_REFUND_KEY_PATH; + if (!cert || !key) throw new Error('微信 V2 原路退款需要商户 API 证书和私钥'); + const result = await new Promise((resolve, reject) => { + const request = https.request(new URL(path, API_BASE), { + method: 'POST', cert: fs.readFileSync(cert), key: fs.readFileSync(key), + headers: { 'Content-Type': 'text/xml' }, timeout: 12000, + }, (response) => { + const chunks = []; + response.on('data', (chunk) => chunks.push(chunk)); + response.on('end', () => resolve({ ok: response.statusCode === 200, text: Buffer.concat(chunks).toString() })); + response.on('error', reject); + }); + request.on('timeout', () => request.destroy(new Error('WeChat refund timeout'))); + request.on('error', reject); + request.end(body); + }); + ({ text, ok } = result); + } else { + const res = await fetch(`${API_BASE}${path}`, { + method: 'POST', headers: { 'Content-Type': 'text/xml' }, body, + signal: AbortSignal.timeout(12000), + }); + text = await res.text(); + ok = res.ok; + } const data = parseXmlFields(text); - if (!res.ok) { - throw new Error(`微信支付请求失败 (${res.status}): ${text}`); + if (!ok) { + throw new Error(`微信支付请求失败: ${text}`); } if (data.return_code !== 'SUCCESS') { throw new Error(`微信支付请求失败: ${data.return_msg || data.return_code || text}`); } - if (data.result_code !== 'SUCCESS') { + if (data.result_code !== 'SUCCESS' && !allowTradeFailure) { throw new Error(`微信支付下单失败: ${data.err_code_des || data.err_code || text}`); } return data; @@ -212,7 +236,9 @@ async function wechatV3Request(config, method, path, bodyObj) { } if (!res.ok) { const detail = data?.message ?? data?.detail ?? text; - throw new Error(`微信支付请求失败 (${res.status}): ${detail}`); + const error = new Error(`微信支付请求失败 (${res.status}): ${detail}`); + error.code = data?.code; + throw error; } return data; } @@ -324,7 +350,32 @@ function createV2Client(config) { return { transaction: normalizeV2Transaction(fields) }; }; + const queryOrder = async (outTradeNo) => { + const fields = await wechatV2Request(config, '/pay/orderquery', { out_trade_no: outTradeNo }, true); + if (fields.err_code === 'ORDERNOTEXIST') return { status: 'closed' }; + if (fields.result_code !== 'SUCCESS') throw new Error('微信查单失败'); + return { + status: fields.trade_state === 'SUCCESS' ? 'paid' : ['CLOSED', 'REVOKED'].includes(fields.trade_state) ? 'closed' : 'pending', + amount_cents: Number(fields.total_fee), transaction_id: fields.transaction_id, + }; + }; + const closeOrder = async (outTradeNo) => { + const queried = await queryOrder(outTradeNo); + if (queried.status !== 'pending') return queried; + await wechatV2Request(config, '/pay/closeorder', { out_trade_no: outTradeNo }, true); + return queryOrder(outTradeNo); + }; + const refundOrder = async ({ outTradeNo, refundNo, amountCents }) => { + await wechatV2Request(config, '/secapi/pay/refund', { + out_trade_no: outTradeNo, out_refund_no: refundNo, + total_fee: String(amountCents), refund_fee: String(amountCents), + }); + const result = await wechatV2Request(config, '/pay/refundquery', { out_refund_no: refundNo }); + return { status: result.refund_status_0 === 'SUCCESS' ? 'refunded' : 'processing' }; + }; + return { + queryOrder, closeOrder, refundOrder, enabled: true, apiVersion: 'v2', appId: config.appId, @@ -438,7 +489,43 @@ function createV3Client(config) { return { serial, transaction }; }; + const queryOrder = async (outTradeNo) => { + let data; + try { + data = await wechatV3Request(config, 'GET', + `/v3/pay/transactions/out-trade-no/${encodeURIComponent(outTradeNo)}?mchid=${encodeURIComponent(config.mchId)}`); + } catch (error) { + if (error.code === 'ORDER_NOT_EXIST') return { status: 'closed' }; + throw error; + } + return { + status: data.trade_state === 'SUCCESS' ? 'paid' : ['CLOSED', 'REVOKED'].includes(data.trade_state) ? 'closed' : 'pending', + amount_cents: data.amount?.total, transaction_id: data.transaction_id, + }; + }; + const closeOrder = async (outTradeNo) => { + const queried = await queryOrder(outTradeNo); + if (queried.status !== 'pending') return queried; + try { + await wechatV3Request(config, 'POST', + `/v3/pay/transactions/out-trade-no/${encodeURIComponent(outTradeNo)}/close`, { mchid: config.mchId }); + } catch (error) { + if (error.code !== 'ORDER_PAID') throw error; + } + return queryOrder(outTradeNo); + }; + const refundOrder = async ({ outTradeNo, refundNo, amountCents }) => { + await wechatV3Request(config, 'POST', '/v3/refund/domestic/refunds', { + out_trade_no: outTradeNo, out_refund_no: refundNo, + amount: { refund: amountCents, total: amountCents, currency: 'CNY' }, + }); + const result = await wechatV3Request(config, 'GET', + `/v3/refund/domestic/refunds/${encodeURIComponent(refundNo)}`); + return { status: result.status === 'SUCCESS' ? 'refunded' : 'processing' }; + }; + return { + queryOrder, closeOrder, refundOrder, enabled: true, apiVersion: 'v3', appId: config.appId,