- 回调 method 由 snake_case 事件名改为 模块.动作:entryorder.confirm / entryorder.match / deliveryorder.confirm / stockout.confirm / deliveryorder.cancel(原 order.cancel 与入站方法同名,改名避免 callback_url 误指向 /openapi 时被路由到取消单据接口)。
- 时间戳统一为秒级(String(Math.floor(Date.now()/1000))),与 /openapi 入站 ±600 秒时效校验及回调调试页一致。
- 报文体由 { event, data, metadata } 改为奇门同层级 { request: {...} }(移除 metadata,事件标识只靠 query 的 method);入库类回调与奇门侧共用同一份报文组装。
- deliveryorder.confirm 改为逐单发送(仅同步成功的订单);stockout.confirm 直接复用 buildStockoutConfirmDataInternal 结果。
- 修复 entryorder.match 死代码:绑定成功且本次新建绑定时回传,重复触发不重复通知,回传失败不影响绑定。
- 调试页 /docs/api/openapi/callback-test 按真实报文预填;新增出站回调文档页 /docs/api/openapi_callback 及入口链接。
- script/update-api-doc.cjs 支持 spec.newDoc 新建文档与 docMeta.description(附单测)。
- 文档:methods/openapi_callback.json、AI_METHOD_ROUTING.md 5.6 节、docs/openapi-callback-events.md、docs/api-doc-update-workflow.md 等。
274 lines
9.9 KiB
JavaScript
274 lines
9.9 KiB
JavaScript
'use strict';
|
||
|
||
const Service = require('egg').Service;
|
||
const { signRequest } = require('../../lib/api_sign');
|
||
|
||
/** @type {number} 最大重试次数 */
|
||
const MAX_RETRY = 3;
|
||
|
||
/** @type {number[]} 递增重试延迟(毫秒) */
|
||
const RETRY_DELAY_MS = [ 2000, 5000, 15000 ];
|
||
|
||
/**
|
||
* OpenAPI 统一回调通知服务。
|
||
* 将订单状态变更等事件通过签名鉴权回调到外部 callback_url,
|
||
* 支持自动重试与日志记录。
|
||
*/
|
||
class OpenapiCallbackService extends Service {
|
||
|
||
/**
|
||
* 计算回调签名(与 OpenAPI 入口签名算法完全一致)。
|
||
* 算法:md5(canonicalQuery + selfAppSecret + md5(stableStringify(body)))。
|
||
* @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 入站时效校验一致)。
|
||
* @return {{ canonicalQuery: string, bodySign: string, sign: string }} 签名计算结果。
|
||
*/
|
||
signCallback({ event, appKey, selfAppSecret, body, timestamp }) {
|
||
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 包装,由发送端包装)。
|
||
* @return {Promise<Object>} 回调结果 { success, retryCount, response, error }。
|
||
*/
|
||
async sendWithRetry({ callbackUrl, appKey, selfAppSecret, event, request }) {
|
||
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 });
|
||
|
||
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 包装,由发送端包装)。
|
||
* @return {Promise<Object>} 回调结果 { success, retryCount, response, error }。
|
||
*/
|
||
async sendByAppKey({ appKey, event, request }) {
|
||
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,
|
||
});
|
||
}
|
||
|
||
/**
|
||
* 将回调响应报文格式化为日志可输出的字符串。
|
||
* 兼容对象、字符串、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;
|