'use strict'; const MainService = require('../main'); /** * OpenAPI 回调测试方法服务。 * 提供模拟发送回调通知的能力,用于测试回调链路是否正常。 */ class OpenapiCallbackMethodService extends MainService { /** * 通过 app_key 解析应用信息。 * 查询 ApiApp 表校验 app_key 有效性。 * @param {string} appKey 开放接口 app_key。 * @return {Promise} 包含 appKey 的信息对象。 */ async resolveAppInfo(appKey) { const { ctx } = this; const normalizedAppKey = String(appKey || '').trim(); if (!normalizedAppKey) { throw new Error('app_key 缺失'); } const appConfig = await ctx.model.ApiApp.findOne({ attributes: [ 'self_app_key' ], where: { self_app_key: normalizedAppKey, is_enabled: 1, }, raw: true, }); if (!appConfig) { throw new Error(`无法找到应用,请检查 app_key: ${normalizedAppKey}`); } return { appKey: normalizedAppKey, }; } /** * 模拟发送回调通知(测试用)。 * 通过 app_key 查找回调配置并发送一次回调请求。 * @param {Object} [payload={}] 调用参数。 * @param {Object} [payload.body={}] 请求体数据,可指定 event 与 data。 * @param {Object} [payload.query={}] 请求 query 数据,需包含 app_key。 * @return {Promise} 回调测试结果。 */ async test(payload = {}) { const { body = {}, query = {} } = payload; const { event = 'order_completed', data = {} } = body; try { const info = await this.resolveAppInfo(query.app_key); const result = await this.ctx.service.openapi.callback.sendByAppKey({ appKey: info.appKey, event, data, metadata: { test: true }, }); if (result.success) { return this.success('回调测试成功', { retryCount: result.retryCount }); } return this.fail('回调测试失败', { error: result.error, retryCount: result.retryCount, }); } catch (error) { return this.fail(`回调测试异常: ${error.message}`); } } } module.exports = OpenapiCallbackMethodService;