liufumingren 7b11f7052d feat(subject): 主体到期暂停设备上报,新增续期订单与支付回调
- 主体状态缓存(Redis 优先、进程内兜底):设备心跳与上报判断不再查库,续期/停用后主动失效
- 上报写接口按缓存校验期限:过期 403 subject_expired、停用 subject_disabled、主体缺失 subject_missing
- 心跳与 /api/scanner/me 返回 subject 状态,桌面端据此暂停推送并在续期后自动补传积压
- 新增续期订单(subject_orders)与接口,支付回调 POST /api/pay/notify 幂等、支持 HMAC 签名,
  另提供内部令牌模拟支付用于联调
- 顺带提交工作区中已完成的「登录协议」后端改动(agreement):与本次改动共用 router.js / config.default.js

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
2026-10-20 18:55:57 +08:00

66 lines
2.7 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

'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;