'use strict'; const { Controller } = require('egg'); const { qimenSign, timingSafeEqual } = require('../lib/wms/sign'); const { toSuccess, toFailure, nowTimestamp } = require('../lib/apiResponse'); const { normalizeTimestamp, isTimestampValid, parseBody } = require('../lib/openapiCallback'); const { recordCallbackLog } = require('../lib/callbackLog'); const openapiMethods = require('../lib/openapiMethods'); const openapiIdempotency = require('../lib/openapiIdempotency'); /** * @controller OpenapiController 对外通用回调接口(公开) * * 外部系统(WMS/第三方)统一通过 POST /openapi 回调 OMS,协议与 WMS /openapi 对齐: * - query:method(模块.动作,如 index.ping)/ app_key / v / timestamp / sign * - body :业务参数 JSON * - 签名:md5(canonicalQuery + app_secret + md5(stableStringify(body))) * - 返回:{ flag, code, message, data, timestamp };失败时 HTTP 状态码与业务码一致 * * 处理流程:校验系统参数与时间戳 → 按 app_key 定位仓库接口配置与仓库(数据隔离靠 * warehouse_apis.principal_id / warehouse_id)→ 验签 → 按 method 分发到 * app/lib/openapiMethods.js 中注册的方法(index.ping / entryorder.confirm / entryorder.match / * deliveryorder.confirm / deliveryorder.getwaybill / stockout.confirm / order.cancel), * 单据处理统一走 app/lib/orderCallback.js。 * 每次请求(含未通过校验的)都会写入 callback_logs,记录请求 query/报文与返回报文。 * 带 request_id 的请求按 (app_key, method, request_id) 幂等:处理完成后保存完整响应, * 重复请求直接回放原响应(见 app/lib/openapiIdempotency.js)。 */ class OpenapiController extends Controller { /** * 对外回调统一入口:处理请求、按 OpenAPI 协议输出响应,并记录请求与返回 * @return {Promise} */ async index() { const { ctx } = this; const startedAt = Date.now(); let result; try { result = await this.handle(); } catch (err) { ctx.logger.error('[openapi] 处理异常', err); result = { ok: false, httpStatus: 500, code: 500, message: `接口错误: ${err.message}` }; } // 幂等重放:直接返回首次处理的完整响应(含批量逐单结果) if (result.replay) { const body = result.replay.body || toFailure({ message: '幂等记录缺少响应报文,请更换 request_id 后重试', code: 500, }); ctx.status = result.replay.httpStatus || 200; ctx.body = body; ctx.type = 'application/json'; recordCallbackLog(this.app, { method: ctx.query.method, appKey: ctx.query.app_key || ctx.query.appkey, query: ctx.query, requestBody: ctx.request.body, responseBody: body, api: result.api, warehouse: result.warehouse, httpStatus: ctx.status, ok: !!body && body.flag === 'success', message: `幂等重放(request_id=${result.requestId || ''})`, duration: Date.now() - startedAt, ip: ctx.ip, }); return; } const ok = !!result.ok; const httpStatus = ok ? 200 : (result.httpStatus || 500); const body = ok ? toSuccess(result.data, result.message || 'ok') : toFailure({ message: result.message || '请求失败', code: result.code || httpStatus, data: result.data }); ctx.status = httpStatus; ctx.body = body; ctx.type = 'application/json'; // 幂等结果落库:同 request_id 重试时直接回放该响应 if (result.idempotency) { await openapiIdempotency.finish(ctx, result.idempotency, { httpStatus, body, ok }); } // 回调日志:请求(query/报文)+ 返回(业务码/报文),未通过 app_key 校验的请求同样记录 recordCallbackLog(this.app, { method: ctx.query.method, appKey: ctx.query.app_key || ctx.query.appkey, query: ctx.query, requestBody: ctx.request.body, responseBody: body, api: result.api, warehouse: result.warehouse, httpStatus, ok, message: result.message || body.message, duration: Date.now() - startedAt, ip: ctx.ip, }); } /** * 校验系统参数、按 app_key 定位仓库、验签并分发到具体 method * @return {Promise<{ok: Boolean, data?: *, message?: String, httpStatus?: Number, code?: Number}>} 处理结果 */ async handle() { const { ctx } = this; const query = ctx.query || {}; const method = String(query.method || '').trim(); const appKey = String(query.app_key || query.appkey || '').trim(); const providedSign = String(query.sign || query.signature || '').trim(); if (!method || !method.includes('.')) { return { ok: false, httpStatus: 400, code: 400, message: '参数缺失或错误: method(需为 模块.动作,如 index.ping)' }; } if (!appKey) { return { ok: false, httpStatus: 400, code: 400, message: '参数缺失或错误: app_key' }; } if (!providedSign) { return { ok: false, httpStatus: 400, code: 400, message: '参数缺失或错误: sign' }; } const timestamp = normalizeTimestamp(query.timestamp); if (timestamp == null) { return { ok: false, httpStatus: 400, code: 400, message: '参数缺失或错误: timestamp' }; } if (!isTimestampValid(timestamp)) { return { ok: false, httpStatus: 400, code: 400, message: `时间戳已过期或无效,服务器时间: ${nowTimestamp()}`, }; } // 按 app_key 定位仓库接口配置:一个 app_key 唯一对应「某主体某仓库」的一条启用配置 const api = await ctx.model.WarehouseApi.findOne({ where: { app_key: appKey, status: 1 }, order: [[ 'id', 'ASC' ]], }); if (!api) { return { ok: false, httpStatus: 401, code: 401, message: `app_key 校验失败: 未找到启用的接口配置(app_key=${appKey})` }; } if (!api.app_secret) { return { ok: false, httpStatus: 401, code: 401, message: 'app_key 校验失败: 接口配置未设置应用密钥' }; } // 定位该接口配置所属仓库(主体隔离与仓库编码均由此得出) const warehouse = await ctx.model.Warehouse.findByPk(api.warehouse_id); if (!warehouse) { return { ok: false, httpStatus: 403, code: 403, message: `仓库定位失败: 接口配置关联的仓库不存在(warehouse_id=${api.warehouse_id})`, }; } // 验签:query 全量参与(sign/signature 自动忽略),body 用解析后的对象 const body = parseBody(ctx); const expectSign = qimenSign({ query, body, secret: api.app_secret }); if (!timingSafeEqual(expectSign, providedSign)) { ctx.logger.warn('[openapi] 签名校验失败', { appKey, method }); return { ok: false, httpStatus: 401, code: 401, message: '签名校验失败', api, warehouse }; } const handler = openapiMethods.resolve(method); if (!handler) { // 未注册的方法必须报错(HTTP 400 + 业务码 400),不静默回执成功,避免调用方误以为已处理 ctx.logger.warn('[openapi] 未注册的方法', { appKey, method, supported: openapiMethods.list() }); return { ok: false, httpStatus: 400, code: 400, message: `openapi method 不存在: ${method}(已支持: ${openapiMethods.list().join(', ')})`, api, warehouse, }; } // 幂等:验签与 method 校验通过后按 request_id 占用,避免重复执行 const idempotency = await openapiIdempotency.begin(ctx, { appKey, method, body, api, warehouse }); if (idempotency.replay) { if (idempotency.replay.invalid) { return { ok: false, httpStatus: 400, code: 400, message: 'request_id 已被使用且报文不一致,请更换 request_id 后重试', api, warehouse, }; } if (idempotency.replay.processing) { return { ok: false, httpStatus: 409, code: 409, message: '相同 request_id 的请求正在处理中,请稍后重试', api, warehouse, }; } return { replay: idempotency.replay, requestId: idempotency.requestId, api, warehouse, }; } const idemContext = { idempotency, requestId: idempotency.requestId }; let handled; try { handled = await handler(ctx, { api, warehouse, body, query, appKey, method, timestamp }); } catch (err) { ctx.logger.error('[openapi] 业务处理异常', err); return { ok: false, httpStatus: 500, code: 500, message: `接口错误: ${err.message}`, api, warehouse, ...idemContext, }; } // 方法返回 { ok, message, data }:ok=false 视为业务处理失败(HTTP 400),便于调用方重试/告警 if (handled && handled.ok === false) { return { ok: false, httpStatus: 400, code: 400, message: handled.message || '业务处理失败', data: handled.data, api, warehouse, ...idemContext, }; } return { ok: true, message: (handled && handled.message) || 'ok', data: handled ? handled.data : null, api, warehouse, ...idemContext, }; } } module.exports = OpenapiController;