'use strict'; const crypto = require('crypto'); const POLYAPI_CONFIG_CACHE_KEY = 'polo_api_client:polyapi:config'; const POLYAPI_CONFIG_CACHE_TTL_SECONDS = 60 * 60; /** * PolyAPI 底层 HTTP 客户端。 * 封装签名、表单编码、请求发送等通用逻辑,与业务无关。 */ class PoloApiClient { /** * @param {object} ctx - Egg 上下文对象。 */ constructor(ctx) { this.ctx = ctx; this._config = null; this._configPromise = null; this.contenttype = 'json'; } /** * 按需加载并缓存 PolyAPI 配置。 * * 优先读取应用级缓存;缓存未命中或读取失败时,再回源数据库。 * 数据库查到配置后,会回写到应用级缓存,缓存 TTL 为 1 小时。 * * @param platid * @return {Promise} PolyAPI 配置记录。 */ async getConfig(platid) { if (this._config) { return this._config; } if (!this._configPromise) { this._configPromise = this._loadConfig(platid).then(config => { this._config = config || null; return this._config; }).finally(() => { this._configPromise = null; }); } return this._configPromise; } /** * 读取 PolyAPI 配置:先查缓存,未命中则查数据库。 * * @param platid * @return {Promise} PolyAPI 配置记录。 */ async _loadConfig(platid) { const cachedConfig = await this._getCachedConfig(platid); if (cachedConfig) { return cachedConfig; } const config = await this._loadConfigFromDatabase(platid); if (config) { await this._setCachedConfig(config); } return config; } /** * 从应用级缓存读取 PolyAPI 配置。 * * 缓存读取失败时,返回 null 并由调用方继续回源数据库。 * * @param platid * @return {Promise} 缓存中的配置记录。 */ async _getCachedConfig(platid) { if (!this.ctx.app || typeof this.ctx.app.getCacheAsync !== 'function') { return null; } try { return await this.ctx.app.getCacheAsync(`${POLYAPI_CONFIG_CACHE_KEY}:${platid}`); } catch (error) { if (this.ctx.logger && typeof this.ctx.logger.warn === 'function') { this.ctx.logger.warn('[PoloApiClient._getCachedConfig] 读取缓存失败,回退数据库查询: %s', error.message); } return null; } } /** * 查询数据库中的 PolyAPI 配置。 * * @param platid * @return {Promise} 数据库中的配置记录。 */ async _loadConfigFromDatabase(platid) { if (!this.ctx.app || !this.ctx.app.model || !this.ctx.app.model.ExpressPlatform || typeof this.ctx.app.model.ExpressPlatform.findOne !== 'function') { return null; } return await this.ctx.app.model.ExpressPlatform.findOne({ where: { platid }, }); } /** * 将 PolyAPI 配置写回应用级缓存。 * * @param {object} config - PolyAPI 配置记录。 * @return {Promise} */ async _setCachedConfig(config) { if (!this.ctx.app || typeof this.ctx.app.setCacheAsync !== 'function') { return; } try { const cacheValue = config && typeof config.toJSON === 'function' ? config.toJSON() : config; await this.ctx.app.setCacheAsync(`${POLYAPI_CONFIG_CACHE_KEY}:${config.platid}`, cacheValue, POLYAPI_CONFIG_CACHE_TTL_SECONDS); } catch (error) { if (this.ctx.logger && typeof this.ctx.logger.warn === 'function') { this.ctx.logger.warn('[PoloApiClient._setCachedConfig] 写入缓存失败,继续使用数据库结果: %s', error.message); } } } /** * 发起 PolyAPI 表单 POST 请求。 * * @param {object} options - 请求参数。 * @param {string} options.method - 远端接口方法名。 * @param {number|string} options.platid - 平台 ID。 * @param {object|string} [options.bizcontent={}] - 业务参数内容。 * @return {Promise} 接口响应 data。 */ async request(options = {}) { const { method, platid, bizcontent = {}, } = options; let config = await this.getConfig(platid); if (!config) { // throw new Error('未找到 polyapi 配置'); config = await this.getConfig(633); } const signMap = this._buildSignMap(config, method, platid, bizcontent); const signText = this._getSignText(signMap, config.app_secret); const sign = this._md5(signText.toLowerCase()); const formBody = this._encodeForm({ ...signMap, sign }); const response = await this.ctx.curl(String(config.interface_url || ''), { method: 'POST', headers: { 'Content-Type': 'application/x-www-form-urlencoded', 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36', }, content: formBody, }); return response && response.data !== undefined ? response.data : null; } // ── 内部方法 ── /** * 组装签名所需的请求参数。 * @param config * @param method * @param platid * @param bizcontent */ _buildSignMap(config, method, platid, bizcontent) { const normalizedBizcontent = bizcontent && typeof bizcontent === 'object' ? JSON.stringify(bizcontent) : (bizcontent === undefined || bizcontent === null ? '' : bizcontent); return { method, appkey: config.appkey, token: config.token, platid, version: config.version, contenttype: this.contenttype, bizcontent: normalizedBizcontent, timestamp: this._formatDate(new Date()), }; } /** * 生成签名原文 = secret + key1value1 + key2value2 ... + secret(按 key 字母序)。 * @param signMap * @param secret */ _getSignText(signMap, secret) { let sb = '' + secret; Object.keys(signMap).sort().forEach(key => { sb += key + signMap[key]; }); sb += secret; return sb; } /** * MD5 摘要。 * @param text * @param encoding */ _md5(text, encoding = 'utf8') { return crypto.createHash('md5').update(text, encoding).digest('hex'); } /** * 将参数编码为 application/x-www-form-urlencoded。 * @param map */ _encodeForm(map) { const params = new URLSearchParams(); for (const key of Object.keys(map)) { const v = map[key]; params.append(key, v === undefined || v === null ? '' : (typeof v === 'object' ? JSON.stringify(v) : String(v))); } return params.toString(); } /** * 格式化日期 → yyyy-MM-dd HH:mm:ss。 * @param date */ _formatDate(date) { const pad = n => (n < 10 ? '0' + n : n); return date.getFullYear() + '-' + pad(date.getMonth() + 1) + '-' + pad(date.getDate()) + ' ' + pad(date.getHours()) + ':' + pad(date.getMinutes()) + ':' + pad(date.getSeconds()); } /** * 格式化取件日期。 * @param year * @param month * @param day */ _formatPickupDate(year, month, day) { const pad = n => (n < 10 ? '0' + n : n); return `${year}-${pad(month)}-${pad(day)} 18:00:00`; } } module.exports = PoloApiClient;