- 新增出站回调 waybill.getreceive(注册到 callback_functions,管理端可勾选):
请求 { request: { waybill_codes: [...] } },响应裸数组/包装体均兼容,
1/0 与 Y/N 归一后回写 wms_order_express.is_galaxy_receive(按 warehouse_id 隔离)
- 回调签名新增 signMode=simple(MD5(appSecret+timestamp+bodyJson)),
waybill.getreceive 使用该口径,与仓库通知协议一致;其它事件默认口径不变
- 新增 waybill.warehouse.updateReceive / updateReceiveTaskProgress:
复用导出的异步任务ID与进度模式(前缀 waybill_receive_),单批 10 单自动切批;
支持 waybillCodes 或与 waybill.warehouse.list 一致的 where 条件圈选(上限 5000);
仓库未配置外部接口时直接失败,不创建任务
- 抽出 buildListQueryWhere / resolveWaybillCodesByWhere,列表与批量更新共用筛选口径
- order_express:is_back / is_intercept / is_galaxy_receive 补默认值 N
- 迁移:存量 NULL 回填为 N(Y 不动);三列分别建立单列索引(INPLACE + LOCK=NONE)
- 文档:methods/system.json(0.3.324)、变更记录、设计文档与出站回调说明同步
Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
298 lines
11 KiB
JavaScript
298 lines
11 KiB
JavaScript
'use strict';
|
||
|
||
const crypto = require('crypto');
|
||
const Service = require('egg').Service;
|
||
const { signRequest } = require('../../lib/api_sign');
|
||
|
||
/** @type {number} 最大重试次数 */
|
||
const MAX_RETRY = 3;
|
||
|
||
/** 签名模式:md5(canonicalQuery + secret + md5(body)),与 /openapi 入站验签一致 */
|
||
const SIGN_MODE_OPENAPI = 'openapi';
|
||
|
||
/** 签名模式:md5(secret + timestamp + bodyJson),与 methods/warehouse_notify.json 协议一致 */
|
||
const SIGN_MODE_SIMPLE = 'simple';
|
||
|
||
/** @type {number[]} 递增重试延迟(毫秒) */
|
||
const RETRY_DELAY_MS = [ 2000, 5000, 15000 ];
|
||
|
||
/**
|
||
* OpenAPI 统一回调通知服务。
|
||
* 将订单状态变更等事件通过签名鉴权回调到外部 callback_url,
|
||
* 支持自动重试与日志记录。
|
||
*/
|
||
class OpenapiCallbackService extends Service {
|
||
|
||
/**
|
||
* 计算回调签名。
|
||
* 默认算法(signMode=openapi):md5(canonicalQuery + selfAppSecret + md5(stableStringify(body))),
|
||
* 与 OpenAPI 入口签名算法完全一致。
|
||
* signMode=simple 时改用 md5(selfAppSecret + timestamp + bodyJson),与
|
||
* `methods/warehouse_notify.json` 描述的仓库通知协议一致(部分外部系统按该口径验签)。
|
||
* @param {Object} options 签名参数。
|
||
* @param {string} options.event 回调 method(模块.动作,如 deliveryorder.confirm),仅用于 query 的 method。
|
||
* @param {string} options.appKey 应用 app_key。
|
||
* @param {string} options.selfAppSecret 应用密钥。
|
||
* @param {Object} options.body 完整回调报文体(奇门同层级 { request: {...} })。
|
||
* @param {string} options.timestamp 秒级时间戳(10 位字符串,与 /openapi 入站时效校验一致)。
|
||
* @param {string} [options.signMode='openapi'] 签名模式:openapi / simple。
|
||
* @return {{ canonicalQuery: string, bodySign: string, sign: string }} 签名计算结果。
|
||
*/
|
||
signCallback({ event, appKey, selfAppSecret, body, timestamp, signMode = SIGN_MODE_OPENAPI }) {
|
||
if (signMode === SIGN_MODE_SIMPLE) {
|
||
const bodyJson = JSON.stringify(body || {});
|
||
const secret = String(selfAppSecret || '');
|
||
return {
|
||
canonicalQuery: '',
|
||
bodySign: '',
|
||
sign: crypto.createHash('md5').update(secret + timestamp + bodyJson).digest('hex'),
|
||
};
|
||
}
|
||
|
||
const query = {
|
||
method: event,
|
||
v: '1.0',
|
||
timestamp,
|
||
app_key: appKey,
|
||
};
|
||
|
||
return signRequest({ query, body, selfAppSecret });
|
||
}
|
||
|
||
/**
|
||
* 发送回调请求(带自动重试)。
|
||
* 报文体固定为奇门同层级结构 { request: {...} },event 仅拼入 query 的 method;
|
||
* 非 2xx 响应或网络错误触发重试,最多重试 MAX_RETRY 次,
|
||
* 每次重试间隔递增(2s → 5s → 15s),请求超时 30 秒。
|
||
* @param {Object} options 回调选项。
|
||
* @param {string} options.callbackUrl 回调目标 URL。
|
||
* @param {string} options.appKey 应用 app_key。
|
||
* @param {string} options.selfAppSecret 应用密钥。
|
||
* @param {string} options.event 回调 method(模块.动作,如 deliveryorder.confirm),仅用于 query 的 method。
|
||
* @param {Object} options.request 奇门同层级业务报文内容(不含外层 request 包装,由发送端包装)。
|
||
* @param {string} [options.signMode='openapi'] 签名模式:openapi(默认)/ simple(仓库通知协议)。
|
||
* @return {Promise<Object>} 回调结果 { success, retryCount, response, error }。
|
||
*/
|
||
async sendWithRetry({ callbackUrl, appKey, selfAppSecret, event, request, signMode = SIGN_MODE_OPENAPI }) {
|
||
const { ctx } = this;
|
||
// 秒级时间戳(10 位):与 /openapi 入站时效校验(±600 秒窗口)及回调调试页保持一致
|
||
const timestamp = String(Math.floor(Date.now() / 1000));
|
||
// 报文体固定为奇门同层级 { request }:event 只出现在 query 的 method 中
|
||
const body = { request: request || {} };
|
||
const { sign } = this.signCallback({ event, appKey, selfAppSecret, body, timestamp, signMode });
|
||
|
||
const queryString = [
|
||
`method=${encodeURIComponent(event)}`,
|
||
'v=1.0',
|
||
`timestamp=${timestamp}`,
|
||
`app_key=${encodeURIComponent(appKey)}`,
|
||
`sign=${sign}`,
|
||
].join('&');
|
||
const separator = callbackUrl.includes('?') ? '&' : '?';
|
||
const url = `${callbackUrl}${separator}${queryString}`;
|
||
|
||
/** @type {string|null} 最后一次错误信息 */
|
||
let lastError = null;
|
||
|
||
/** @type {Object|null} 最后一次响应对象 */
|
||
let lastResponse = null;
|
||
|
||
for (let attempt = 0; attempt <= MAX_RETRY; attempt++) {
|
||
try {
|
||
const result = await ctx.curl(url, {
|
||
method: 'POST',
|
||
contentType: 'json',
|
||
dataType: 'json',
|
||
data: body,
|
||
timeout: 30000,
|
||
});
|
||
|
||
lastResponse = result;
|
||
|
||
if (result.status >= 200 && result.status < 300) {
|
||
console.log(`[OpenapiCallback] event=${event} appKey=${appKey} retry=${attempt} url=${url} status=${result.status} success=true response=${this._formatResponsePayload(result.data)}`);
|
||
|
||
await this.logCallback({
|
||
appKey,
|
||
event,
|
||
callbackUrl,
|
||
success: true,
|
||
retryCount: attempt,
|
||
response: result.data,
|
||
});
|
||
|
||
return {
|
||
success: true,
|
||
retryCount: attempt,
|
||
response: result.data,
|
||
error: null,
|
||
};
|
||
}
|
||
|
||
lastError = new Error(`回调返回非 2xx 状态码: ${result.status}`);
|
||
|
||
console.log(`[OpenapiCallback] event=${event} appKey=${appKey} retry=${attempt} url=${url} status=${result.status} success=false response=${this._formatResponsePayload(result.data)}`);
|
||
|
||
await this.logCallback({
|
||
appKey,
|
||
event,
|
||
callbackUrl,
|
||
success: false,
|
||
retryCount: attempt,
|
||
response: result.data,
|
||
error: lastError.message,
|
||
});
|
||
} catch (error) {
|
||
lastError = error;
|
||
const availableResponse = lastResponse ? lastResponse.data : null;
|
||
|
||
console.log(`[OpenapiCallback] event=${event} appKey=${appKey} retry=${attempt} url=${url} success=false error=${error.message} response=${this._formatResponsePayload(availableResponse)}`);
|
||
|
||
await this.logCallback({
|
||
appKey,
|
||
event,
|
||
callbackUrl,
|
||
success: false,
|
||
retryCount: attempt,
|
||
response: availableResponse,
|
||
error: error.message,
|
||
});
|
||
}
|
||
|
||
if (attempt < MAX_RETRY) {
|
||
const delay = RETRY_DELAY_MS[attempt] || RETRY_DELAY_MS[RETRY_DELAY_MS.length - 1];
|
||
await new Promise(resolve => setTimeout(resolve, delay));
|
||
}
|
||
}
|
||
|
||
return {
|
||
success: false,
|
||
retryCount: MAX_RETRY,
|
||
response: lastResponse ? lastResponse.data : null,
|
||
error: lastError ? lastError.message : '回调失败',
|
||
};
|
||
}
|
||
|
||
/**
|
||
* 根据 app_key 查询 api_app 获取 callback_url 与密钥,发送回调通知。
|
||
* 报文体由 sendWithRetry 统一包装为奇门同层级 { request: {...} }。
|
||
* @param {Object} options 回调选项。
|
||
* @param {string} options.appKey 应用 app_key。
|
||
* @param {string} options.event 回调 method(模块.动作,如 deliveryorder.confirm),仅用于 query 的 method。
|
||
* @param {Object} options.request 奇门同层级业务报文内容(不含外层 request 包装,由发送端包装)。
|
||
* @param {string} [options.signMode='openapi'] 签名模式:openapi(默认)/ simple(仓库通知协议)。
|
||
* @return {Promise<Object>} 回调结果 { success, retryCount, response, error }。
|
||
*/
|
||
async sendByAppKey({ appKey, event, request, signMode = SIGN_MODE_OPENAPI }) {
|
||
const { ctx } = this;
|
||
const normalizedAppKey = String(appKey || '').trim();
|
||
|
||
if (!normalizedAppKey) {
|
||
ctx.logger.warn('[OpenapiCallback] sendByAppKey 缺少 appKey');
|
||
|
||
return {
|
||
success: false,
|
||
retryCount: 0,
|
||
response: null,
|
||
error: '缺少 appKey',
|
||
};
|
||
}
|
||
|
||
const appConfig = await ctx.model.ApiApp.findOne({
|
||
attributes: [ 'self_app_key', 'self_app_secret', 'callback_url' ],
|
||
where: {
|
||
self_app_key: normalizedAppKey,
|
||
is_enabled: 1,
|
||
},
|
||
raw: true,
|
||
});
|
||
|
||
if (!appConfig || !appConfig.callback_url) {
|
||
ctx.logger.warn(`[OpenapiCallback] 未找到有效的回调配置,appKey=${normalizedAppKey}`);
|
||
|
||
return {
|
||
success: false,
|
||
retryCount: 0,
|
||
response: null,
|
||
error: '未找到有效的回调配置',
|
||
};
|
||
}
|
||
|
||
return await this.sendWithRetry({
|
||
callbackUrl: appConfig.callback_url,
|
||
appKey: normalizedAppKey,
|
||
selfAppSecret: appConfig.self_app_secret || '',
|
||
event,
|
||
request,
|
||
signMode,
|
||
});
|
||
}
|
||
|
||
/**
|
||
* 将回调响应报文格式化为日志可输出的字符串。
|
||
* 兼容对象、字符串、Buffer / ArrayBuffer / TypedArray 与 null / undefined,
|
||
* 超出最大长度时做截断处理,避免日志刷屏。
|
||
* @param {*} response 回调响应报文,类型不限。
|
||
* @return {string} 格式化后的报文字符串。
|
||
*/
|
||
_formatResponsePayload(response) {
|
||
const MAX_PAYLOAD_LENGTH = 500;
|
||
let payload;
|
||
|
||
if (response === null || response === undefined) {
|
||
payload = 'null';
|
||
} else if (typeof response === 'string') {
|
||
payload = response;
|
||
} else if (Buffer.isBuffer(response)) {
|
||
payload = response.toString('utf8');
|
||
} else if (response instanceof ArrayBuffer) {
|
||
payload = Buffer.from(response).toString('utf8');
|
||
} else if (ArrayBuffer.isView(response)) {
|
||
// TypedArray 与 DataView:仅取视图对应的内存区间
|
||
payload = Buffer.from(response.buffer, response.byteOffset, response.byteLength).toString('utf8');
|
||
} else {
|
||
try {
|
||
payload = JSON.stringify(response);
|
||
} catch (error) {
|
||
// 循环引用等序列化异常时降级处理
|
||
payload = String(response);
|
||
}
|
||
}
|
||
|
||
if (payload.length > MAX_PAYLOAD_LENGTH) {
|
||
return `${payload.slice(0, MAX_PAYLOAD_LENGTH)}...(truncated)`;
|
||
}
|
||
|
||
return payload;
|
||
}
|
||
|
||
/**
|
||
* 记录回调日志。
|
||
* 格式:[OpenapiCallback] event=xxx appKey=xxx url=xxx retry=N success=xxx response=xxx
|
||
* @param {Object} options 日志选项。
|
||
* @param {string} options.appKey 应用 app_key。
|
||
* @param {string} options.event 事件名。
|
||
* @param {string} options.callbackUrl 回调目标 URL。
|
||
* @param {boolean} options.success 是否成功。
|
||
* @param {number} options.retryCount 重试次数。
|
||
* @param {*} [options.response] 回调响应报文。
|
||
* @param {string} [options.error] 错误信息。
|
||
* @return {void} 无返回值。
|
||
*/
|
||
async logCallback({ appKey, event, callbackUrl, success, retryCount, response, error }) {
|
||
const { ctx } = this;
|
||
const payload = this._formatResponsePayload(response);
|
||
const logMessage = `[OpenapiCallback] event=${event} appKey=${appKey} url=${callbackUrl} retry=${retryCount} success=${success} response=${payload}`;
|
||
|
||
if (success) {
|
||
ctx.logger.info(logMessage);
|
||
} else if (retryCount >= MAX_RETRY) {
|
||
ctx.logger.error(`${logMessage} error=${error || '未知错误'}`);
|
||
} else {
|
||
ctx.logger.warn(`${logMessage} error=${error || '未知错误'}`);
|
||
}
|
||
}
|
||
}
|
||
|
||
module.exports = OpenapiCallbackService;
|