'use strict'; const { Controller } = require('egg'); const crypto = require('crypto'); /** * 支付渠道通知(`POST /api/pay/notify`,**公开接口**) * * 渠道接入前先用它模拟「已付款」:带上订单号与金额调用即可续期(见 README)。 * * 请求体(兼容常见的两种命名): * `{ orderNo | out_trade_no, transactionId | trade_no, amount | total_amount, channel?, paidAt? }` * * 签名:配置了 `config.pay.callbackSecret`(env `PAY_CALLBACK_SECRET`)时, * 必须带 header `X-Pay-Sign = HMAC-SHA256(secret, "orderNo\ntransactionId\namount")`(hex)。 * 未配置密钥且 `PAY_MOCK=true` 时允许不带签名(仅开发/测试)。 * * 响应:`{ ok: true, data: { duplicated, order } }`;订单号不存在 404,金额不符 422。 */ class PayNotifyController extends Controller { async index() { const { ctx } = this; const body = ctx.request.body || {}; const orderNo = String(body.orderNo || body.out_trade_no || '').trim(); const transactionId = body.transactionId || body.transaction_id || body.trade_no || null; const amount = body.amount !== undefined && body.amount !== null ? body.amount : body.total_amount; const channel = body.channel || 'mock'; const payCfg = this.config.pay || {}; const secret = String(payCfg.callbackSecret || ''); if (secret) { const expected = crypto .createHmac('sha256', secret) .update(`${orderNo}\n${transactionId || ''}\n${amount === undefined || amount === null ? '' : amount}`) .digest('hex'); const actual = String(ctx.get('x-pay-sign') || '').trim().toLowerCase(); if (!actual || !safeEqual(actual, expected)) { ctx.logger.warn('[pay] 回调签名校验失败:orderNo=%s', orderNo); ctx.status = 400; ctx.body = { ok: false, status: 'sign_invalid', message: '支付回调签名校验失败' }; return; } } else if (!payCfg.mock) { ctx.status = 503; ctx.body = { ok: false, status: 'pay_not_configured', message: '未配置支付回调密钥(PAY_CALLBACK_SECRET)' }; return; } else { ctx.logger.warn('[pay] 模拟回调(未配置 PAY_CALLBACK_SECRET,PAY_MOCK=%s):orderNo=%s', payCfg.mock, orderNo); } const data = await ctx.service.subjectOrder.payNotify({ orderNo, transactionId, amount, channel }); ctx.body = { ok: true, data }; } } /** 定长比较,避免按字符提前返回 */ function safeEqual(a, b) { const left = Buffer.from(String(a)); const right = Buffer.from(String(b)); return left.length === right.length && crypto.timingSafeEqual(left, right); } module.exports = PayNotifyController;