- 新增 service/wxpay.js:统一下单 / 查询订单 / 关闭订单 / APIv2 验签,二维码在服务端本地生成 SVG - 新增 pay/wechat.js 与 XML 编解码,公开回调 POST /api/pay/wechat/notify - 订单:同主体 + 同套餐复用未超时待支付单;2 小时超时关单;回调 / 查单 / 手工确认统一走 payNotify - 迁移 subject_orders 增加 code_url / prepay_id 等字段,配置项 WXPAY_* - 前端续期弹窗展示二维码并按 2s 轮询支付结果 - 文档与测试同步更新 Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
109 lines
4.2 KiB
JavaScript
109 lines
4.2 KiB
JavaScript
'use strict';
|
||
|
||
const { Controller } = require('egg');
|
||
const { buildXml, parseXml, parseWxTime } = require('../../lib/wxpay-xml');
|
||
|
||
/** 回调包体上限(正常只有几百字节,防止被灌大包) */
|
||
const MAX_BODY_BYTES = 64 * 1024;
|
||
|
||
/**
|
||
* 微信支付结果通知(`POST /api/pay/wechat/notify`,**公开接口**,XML 进出)
|
||
*
|
||
* 文档:https://pay.weixin.qq.com/doc/v2/merchant/4011936582
|
||
*
|
||
* 处理顺序:读原始 XML → 验签(APIv2 密钥,同时核对 appid / mch_id)→ 只处理
|
||
* `return_code=SUCCESS & result_code=SUCCESS` → 走 `service.subjectOrder.payNotify()`
|
||
* (标记已支付 + 主体顺延 + 失效缓存,幂等)。
|
||
*
|
||
* 应答约定(微信按 `return_code` 决定要不要重推):
|
||
* - 回调内容有问题但重试也没用(订单不存在 / 已超时关闭 / 金额不符)→ 回 `SUCCESS` 并记 error 日志,人工跟进;
|
||
* - 我方临时故障(5xx / 网络)→ 回 `FAIL`,让微信按策略重推。
|
||
*/
|
||
class PayWechatController extends Controller {
|
||
async notify() {
|
||
const { ctx } = this;
|
||
ctx.set('Cache-Control', 'no-store');
|
||
ctx.type = 'application/xml; charset=utf-8';
|
||
|
||
const raw = await readRawBody(ctx.req);
|
||
if (raw === null) {
|
||
ctx.status = 413;
|
||
ctx.body = replyXml('FAIL', '请求体过大');
|
||
return;
|
||
}
|
||
|
||
const params = parseXml(raw);
|
||
const orderNo = String(params.out_trade_no || '').trim();
|
||
if (!orderNo) {
|
||
ctx.logger.warn('[wxpay] 回调缺少 out_trade_no:%s', raw.slice(0, 300));
|
||
ctx.body = replyXml('FAIL', '参数错误');
|
||
return;
|
||
}
|
||
|
||
const wxpay = ctx.service.wxpay;
|
||
if (!wxpay.enabled) {
|
||
ctx.logger.error('[wxpay] 收到支付回调但微信支付未配置:out_trade_no=%s', orderNo);
|
||
ctx.body = replyXml('FAIL', '微信支付未配置');
|
||
return;
|
||
}
|
||
|
||
const sign = wxpay.verifySign(params);
|
||
if (!sign.ok) {
|
||
ctx.logger.warn('[wxpay] 回调验签失败(%s):out_trade_no=%s', sign.message, orderNo);
|
||
ctx.body = replyXml('FAIL', '签名校验失败');
|
||
return;
|
||
}
|
||
|
||
if (params.return_code !== 'SUCCESS' || params.result_code !== 'SUCCESS') {
|
||
ctx.logger.warn('[wxpay] 支付结果非成功,忽略:out_trade_no=%s return_code=%s result_code=%s err=%s',
|
||
orderNo, params.return_code, params.result_code, params.err_code || '');
|
||
ctx.body = replyXml('SUCCESS', 'OK');
|
||
return;
|
||
}
|
||
|
||
const fee = params.total_fee === undefined || params.total_fee === '' ? null : Number(params.total_fee);
|
||
try {
|
||
const data = await ctx.service.subjectOrder.payNotify({
|
||
orderNo,
|
||
transactionId: params.transaction_id || null,
|
||
amount: fee === null || !Number.isFinite(fee) ? undefined : fee / 100,
|
||
channel: 'wechat',
|
||
paidAt: parseWxTime(params.time_end),
|
||
});
|
||
ctx.logger.info('[wxpay] 回调入账成功:out_trade_no=%s transaction_id=%s duplicated=%s',
|
||
orderNo, params.transaction_id || '-', data.duplicated);
|
||
ctx.body = replyXml('SUCCESS', 'OK');
|
||
} catch (err) {
|
||
const status = Number(err.status) || 500;
|
||
if (status >= 500) {
|
||
ctx.logger.error('[wxpay] 回调处理异常(等微信重推):out_trade_no=%s %s', orderNo, err.message);
|
||
ctx.body = replyXml('FAIL', '处理失败');
|
||
return;
|
||
}
|
||
// 404 订单不存在 / 409 已超时关闭 / 422 金额不符:重推也不会成功,回 SUCCESS 停止推送
|
||
ctx.logger.error('[wxpay] 回调处理失败(不再重试,需人工核对):out_trade_no=%s status=%s %s',
|
||
orderNo, status, err.message);
|
||
ctx.body = replyXml('SUCCESS', 'OK');
|
||
}
|
||
}
|
||
}
|
||
|
||
/** 读原始请求体(`text/xml` 不在 bodyParser 的 enableTypes 里,流还在) */
|
||
async function readRawBody(stream, limit = MAX_BODY_BYTES) {
|
||
const chunks = [];
|
||
let size = 0;
|
||
for await (const chunk of stream) {
|
||
size += chunk.length;
|
||
if (size > limit) return null;
|
||
chunks.push(chunk);
|
||
}
|
||
return Buffer.concat(chunks).toString('utf8');
|
||
}
|
||
|
||
/** 应答报文:`{ return_code, return_msg }` */
|
||
function replyXml(returnCode, returnMsg) {
|
||
return buildXml({ return_code: returnCode, return_msg: returnMsg });
|
||
}
|
||
|
||
module.exports = PayWechatController;
|