226 lines
7.0 KiB
JavaScript
226 lines
7.0 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 入口签名算法完全一致)。
|
||
* @param {Object} options 签名参数。
|
||
* @param {string} options.event 事件名,如 order_completed。
|
||
* @param {string} options.appKey 应用 app_key。
|
||
* @param {string} options.selfAppSecret 应用密钥。
|
||
* @param {Object} options.body 回调请求体数据。
|
||
* @param {string} options.timestamp 毫秒时间戳。
|
||
* @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 });
|
||
}
|
||
|
||
/**
|
||
* 发送回调请求(带自动重试)。
|
||
* 非 2xx 响应或网络错误触发重试,最多重试 MAX_RETRY 次,
|
||
* 每次重试间隔递增(2s → 5s → 15s)。
|
||
* @param {Object} options 回调选项。
|
||
* @param {string} options.callbackUrl 回调目标 URL。
|
||
* @param {string} options.appKey 应用 app_key。
|
||
* @param {string} options.selfAppSecret 应用密钥。
|
||
* @param {string} options.event 事件名,如 order_completed。
|
||
* @param {Object} options.data 回调数据。
|
||
* @param {Object} [options.metadata] 额外元数据。
|
||
* @return {Promise<Object>} 回调结果 { success, retryCount, response, error }。
|
||
*/
|
||
async sendWithRetry({ callbackUrl, appKey, selfAppSecret, event, data, metadata }) {
|
||
const { ctx } = this;
|
||
const timestamp = String(Date.now());
|
||
const body = { event, data, metadata: metadata || {} };
|
||
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) {
|
||
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}`);
|
||
|
||
await this.logCallback({
|
||
appKey,
|
||
event,
|
||
callbackUrl,
|
||
success: false,
|
||
retryCount: attempt,
|
||
response: result.data,
|
||
error: lastError.message,
|
||
});
|
||
} catch (error) {
|
||
lastError = error;
|
||
|
||
await this.logCallback({
|
||
appKey,
|
||
event,
|
||
callbackUrl,
|
||
success: false,
|
||
retryCount: attempt,
|
||
response: null,
|
||
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 与密钥,发送回调通知。
|
||
* @param {Object} options 回调选项。
|
||
* @param {string} options.appKey 应用 app_key。
|
||
* @param {string} options.event 事件名,如 order_completed。
|
||
* @param {Object} options.data 回调数据。
|
||
* @param {Object} [options.metadata] 额外元数据。
|
||
* @return {Promise<Object>} 回调结果 { success, retryCount, response, error }。
|
||
*/
|
||
async sendByAppKey({ appKey, event, data, metadata }) {
|
||
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,
|
||
data,
|
||
metadata,
|
||
});
|
||
}
|
||
|
||
/**
|
||
* 记录回调日志。
|
||
* 格式:[OpenapiCallback] event=xxx appKey=xxx url=xxx retry=N success=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 logMessage = `[OpenapiCallback] event=${event} appKey=${appKey} url=${callbackUrl} retry=${retryCount} success=${success}`;
|
||
|
||
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;
|