'use strict'; const Service = require('egg').Service; class OpenapiService extends Service { /** * 解析 openapi method,拆分为服务路径与动作名。 * @param {string} methodName method 名称。 * @return {{ servicePath: string, actionName: string }} 解析结果。 */ resolveOpenapiMethod(methodName = '') { const method = String(methodName || '').trim(); const parts = method.split('.').filter(Boolean); const actionName = parts.pop() || ''; const servicePath = parts.join('.'); return { servicePath, actionName, }; } /** * 根据服务路径查找 openapiMethods 下的目标服务。 * @param {string} servicePath 服务路径。 * @return {Object|null} 目标服务实例。 */ getOpenapiMethodService(servicePath = '') { const { ctx } = this; const pathSegments = String(servicePath || '').split('.').filter(Boolean); let methodService = ctx.service.openapiMethods; if (pathSegments.length === 0) { return methodService; } for (const segment of pathSegments) { methodService = methodService && methodService[segment]; } return methodService || null; } /** * 解析 OpenAPI 合约信息(interface_type_id=2 必须绑定有效合约)。 * 查询 ApiApp 并强制关联 StoreWarehouse,校验 store_id 必须存在。 * @param {string} appKey 开放接口 app_key。 * @return {Promise} 包含 storeId、warehouseId、appKey、customerId、warehouseCode 的信息对象。 */ async resolveOpenapiContract(appKey) { const { ctx, app } = this; const normalizedAppKey = String(appKey || '').trim(); if (!normalizedAppKey) { throw new Error('app_key 缺失'); } const appConfig = await ctx.model.ApiApp.findOne({ attributes: [ 'id', 'warehouse_id', 'qimen_warehouse_code', [ app.Sequelize.col('contract.store_id'), 'store_id' ], ], where: { self_app_key: normalizedAppKey, is_enabled: 1, }, include: [ { model: ctx.model.StoreWarehouse, as: 'contract', attributes: [], required: true, }, ], raw: true, }); if (!appConfig || !appConfig.warehouse_id) { throw new Error(`无法解析仓库信息,请检查 app_key: ${normalizedAppKey}`); } if (!appConfig.store_id) { throw new Error(`未找到 app_key 对应的货主合约关系: ${normalizedAppKey}`); } const warehouseId = appConfig.warehouse_id; return { storeId: appConfig.store_id, warehouseId, appKey: normalizedAppKey, customerId: null, warehouseCode: appConfig.qimen_warehouse_code || String(warehouseId), }; } /** * 分发 openapi method 到 openapiMethods 目录。 * 分发前统一注入合约上下文(storeId/warehouseId/appKey 等), * 确保所有下游方法可通过 this.getInfo() 获取货主范围信息。 * @param {string} methodName method 名称。 * @param {Object} body 请求体。 * @param {Object} query 请求 query。 * @param {Object} contractInfo 合约上下文信息。 * @return {Promise} method 执行结果。 */ async dispatchOpenapiMethod(methodName, body, query, contractInfo) { const { servicePath, actionName } = this.resolveOpenapiMethod(methodName); const methodService = this.getOpenapiMethodService(servicePath); if (!methodService || typeof methodService[actionName] !== 'function') { return { ok: false, httpStatus: 400, code: 400, message: `openapi method 不存在: ${methodName}`, data: null, }; } // 统一注入合约上下文到方法服务实例 if (contractInfo && typeof methodService.setInfo === 'function') { methodService.setInfo( contractInfo.storeId, contractInfo.warehouseId, contractInfo.appKey, contractInfo.customerId, contractInfo.warehouseCode ); } const methodResult = await methodService[actionName]({ body, query, }); return { ok: true, httpStatus: 200, code: 1, message: 'ok', data: methodResult, }; } /** * 校验 openapi 基础 query 参数,仅校验 method/v/timestamp。 * @param {Object} query 请求 query 参数。 * @return {boolean} 是否通过基础参数校验。 */ validateOpenapiParams(query) { const requiredFields = [ 'method', 'v', 'timestamp' ]; for (const field of requiredFields) { if (!query || !query[field]) { return false; } } if (typeof query.method !== 'string' || !query.method.includes('.')) { return false; } return true; } /** * 读取并解析 JSON 请求体,采用 rawBody 优先策略。 * @return {Promise} 解析后的 JSON 对象。 */ async parseJsonBody() { const { ctx } = this; let jsonData = ''; if (ctx.request.rawBody) { jsonData = ctx.request.rawBody; } else if (ctx.request.body !== undefined) { jsonData = typeof ctx.request.body === 'string' ? ctx.request.body : JSON.stringify(ctx.request.body); } else { jsonData = await new Promise((resolve, reject) => { let data = ''; ctx.req.on('data', chunk => { data += chunk; }); ctx.req.on('end', () => { resolve(data); }); ctx.req.on('error', reject); }); } jsonData = jsonData ? String(jsonData) : ''; if (!jsonData || jsonData.trim() === '') { return { ok: false, httpStatus: 400, code: 400, message: 'json数据为空', data: null, }; } try { return JSON.parse(jsonData); } catch (error) { return { ok: false, httpStatus: 400, code: 400, message: 'json数据解析错误', data: null, }; } } /** * 提取并归一化 openapi 所需的 appKey 与 sign。 * @param {Object} query 请求 query 参数。 * @return {{ appKey: string, providedSign: string }} 归一化后的关键信息。 */ normalizeSignFields(query = {}) { const appKey = String(query.app_key || query.appkey || query.self_app_key || '').trim(); const providedSign = String(query.sign || query.signature || '').trim(); return { appKey, providedSign, }; } /** * 处理 openapi 请求并返回统一结果。 * @return {Promise} 统一结果对象。 */ async processRequest() { const { ctx } = this; const query = ctx.query || {}; if (!this.validateOpenapiParams(query)) { return { ok: false, httpStatus: 400, code: 400, message: '参数缺失或错误: method/v/timestamp', data: null, }; } // 时间戳时效校验(±10分钟) const nowTs = Math.floor(Date.now() / 1000); const reqTs = Number(query.timestamp); if (!Number.isFinite(reqTs) || Math.abs(nowTs - reqTs) > 600) { return { ok: false, httpStatus: 400, code: 400, message: `时间戳已过期或无效,服务器时间: ${nowTs}`, data: null, }; } const body = await this.parseJsonBody(); if (body && body.ok === false) { return body; } const { appKey, providedSign } = this.normalizeSignFields(query); if (!appKey) { return { ok: false, httpStatus: 400, code: 400, message: '参数缺失或错误: app_key', data: null, }; } const { systems: systemsService } = ctx.service; const apiSignService = systemsService.apiSign; let appConfig; try { appConfig = await apiSignService.getApiAppSecretByAppKey(appKey); } catch (error) { return { ok: false, httpStatus: 401, code: 401, message: `app_key 校验失败: ${error.message}`, data: null, }; } const verifyResult = await apiSignService.verifyRequestSignByAppKey({ appKey, query, body, providedSign, }); if (!verifyResult.ok) { return { ok: false, httpStatus: 401, code: 401, message: `签名校验失败: ${verifyResult.message}`, data: null, }; } // interface_type_id=2(OPENAPI)必须解析合约并注入货主信息 let contractInfo = null; try { contractInfo = await this.resolveOpenapiContract(appKey); } catch (error) { return { ok: false, httpStatus: 403, code: 403, message: `合约校验失败: ${error.message}`, data: null, }; } const queryWithAppKey = { ...query, app_key: appConfig.appKey, }; return await this.dispatchOpenapiMethod(query.method, body, queryWithAppKey, contractInfo); } } module.exports = OpenapiService;