214 lines
6.9 KiB
JavaScript
214 lines
6.9 KiB
JavaScript
'use strict';
|
||
|
||
const crypto = require('crypto');
|
||
|
||
/**
|
||
* PolyAPI 底层 HTTP 客户端。
|
||
* 封装签名、表单编码、请求发送等通用逻辑,与业务无关。
|
||
*/
|
||
class PoloApiClient {
|
||
/**
|
||
* @param {object} ctx - Egg 上下文对象。
|
||
*/
|
||
constructor(ctx) {
|
||
this.ctx = ctx;
|
||
this.contenttype = 'json';
|
||
}
|
||
|
||
/**
|
||
* 发起 PolyAPI 表单 POST 请求。
|
||
*
|
||
* @param {object} options - 请求参数。
|
||
* @param {string} options.method - 远端接口方法名。
|
||
* @param {number|string} options.platid - 平台 ID。
|
||
* @param {object|string} [options.bizcontent={}] - 业务参数内容。
|
||
* @return {Promise<any>} 接口响应 data。
|
||
*/
|
||
async request(options = {}) {
|
||
const {
|
||
method,
|
||
bizcontent = {},
|
||
config = {},
|
||
token,
|
||
} = options;
|
||
if (!config || !config.interface_url) {
|
||
throw new Error('[PoloApiClient.request] 未提供有效的 config,无法发送请求');
|
||
}
|
||
const configWithToken = config;
|
||
if (token) {
|
||
configWithToken.token = token;
|
||
}
|
||
console.log('configWithToken', configWithToken);
|
||
const signMap = this._buildSignMap(configWithToken, method, config.platid, bizcontent);
|
||
console.log('signMap', signMap);
|
||
const signText = this._getSignText(signMap, config.app_secret);
|
||
const sign = this._md5(signText);
|
||
// const formBody = this._encodeForm({ ...signMap, sign });
|
||
signMap.sign = sign;
|
||
const formBody = Object.keys(signMap)
|
||
.map(key => `${key}=${encodeURIComponent(signMap[key])}`)
|
||
.join('&');
|
||
console.log('查询菠萝派平台数据,接口URL:', config.interface_url, '入参bizcontent:', JSON.stringify(bizcontent));
|
||
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,
|
||
});
|
||
console.log('formBody', formBody);
|
||
let result;
|
||
if (Buffer.isBuffer(response.data)) {
|
||
// 如果是 Buffer,转字符串再解析
|
||
const str = response.data.toString('utf8');
|
||
result = JSON.parse(str);
|
||
} else if (typeof response.data === 'string') {
|
||
result = JSON.parse(response.data);
|
||
} else {
|
||
result = response.data;
|
||
}
|
||
return result;
|
||
}
|
||
|
||
/**
|
||
* 发起 PolyAPI GET 请求。
|
||
*
|
||
* @param {object} options - 请求参数。
|
||
* @param {string} options.method - 远端接口方法名。
|
||
* @param {object|string} [options.bizcontent={}] - 业务参数内容。
|
||
* @param {object} [options.config={}] - 平台配置。
|
||
* @param {string} [options.token] - 可选 token,传入时优先覆盖配置 token。
|
||
* @return {Promise<any>} 接口响应 data。
|
||
*/
|
||
async get(options = {}) {
|
||
const {
|
||
method,
|
||
bizcontent = {},
|
||
config = {},
|
||
token,
|
||
} = options;
|
||
if (!config || !config.interface_url) {
|
||
throw new Error('[PoloApiClient.get] 未提供有效的 config,无法发送请求');
|
||
}
|
||
const configWithToken = { ...config, token: token || config.token };
|
||
const signMap = this._buildSignMap(configWithToken, method, config.platid, bizcontent);
|
||
const signText = this._getSignText(signMap, config.app_secret);
|
||
const sign = this._md5(signText);
|
||
const formBody = this._encodeForm({ ...signMap, sign });
|
||
const requestUrl = `http://39.98.7.126/OpenApi/Do?${formBody}`;
|
||
|
||
const response = await this.ctx.curl(requestUrl, {
|
||
method: 'GET',
|
||
headers: {
|
||
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36',
|
||
},
|
||
});
|
||
let result;
|
||
if (Buffer.isBuffer(response.data)) {
|
||
// 如果是 Buffer,转字符串再解析
|
||
const str = response.data.toString('utf8');
|
||
console.log('菠萝派平台接口响应原始数据', str);
|
||
result = JSON.parse(str);
|
||
} else if (typeof response.data === 'string') {
|
||
result = JSON.parse(response.data);
|
||
} else {
|
||
result = response.data;
|
||
}
|
||
return result;
|
||
|
||
}
|
||
// ── 内部方法 ──
|
||
|
||
/**
|
||
* 组装签名所需的请求参数。
|
||
* @param {object} config 平台配置对象。
|
||
* @param {string} method 接口方法名。
|
||
* @param {number|string} platid 平台 ID。
|
||
* @param {object|string} bizcontent 业务参数。
|
||
* @return {object} 签名参数映射。
|
||
*/
|
||
_buildSignMap(config, method, platid, bizcontent) {
|
||
const normalizedBizcontent = bizcontent && typeof bizcontent === 'object'
|
||
? JSON.stringify(bizcontent)
|
||
: (bizcontent === undefined || bizcontent === null ? '' : bizcontent);
|
||
const res = {
|
||
method,
|
||
appkey: config.appkey,
|
||
platid,
|
||
version: config.version,
|
||
contenttype: this.contenttype,
|
||
bizcontent: normalizedBizcontent,
|
||
timestamp: this._formatDate(new Date()),
|
||
};
|
||
if (config.token) {
|
||
res.token = config.token;
|
||
}
|
||
return res;
|
||
}
|
||
|
||
/**
|
||
* 生成签名原文 = secret + key1value1 + key2value2 ... + secret(按 key 字母序)。
|
||
* @param {object} signMap 待签名参数映射。
|
||
* @param {string} secret 签名密钥。
|
||
* @return {string} 转小写后的签名原文字符串。
|
||
*/
|
||
_getSignText(signMap, secret) {
|
||
let sb = '' + secret;
|
||
Object.keys(signMap).sort().forEach(key => {
|
||
sb += key + signMap[key];
|
||
});
|
||
sb += secret;
|
||
return sb.toLowerCase();
|
||
}
|
||
|
||
/**
|
||
* MD5 摘要。
|
||
* @param {string} text 待摘要文本。
|
||
* @param {BufferEncoding} [encoding='utf8'] 文本编码。
|
||
* @return {string} 十六进制 MD5 值。
|
||
*/
|
||
_md5(text, encoding = 'utf8') {
|
||
return crypto.createHash('md5').update(text, encoding).digest('hex');
|
||
}
|
||
|
||
/**
|
||
* 将参数编码为 application/x-www-form-urlencoded。
|
||
* @param {object} map 表单参数映射。
|
||
* @return {string} URL 编码后的查询串。
|
||
*/
|
||
_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} date 日期对象。
|
||
* @return {string} 格式化后的时间字符串。
|
||
*/
|
||
_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 {number} year 年。
|
||
* @param {number} month 月。
|
||
* @param {number} day 日。
|
||
* @return {string} 取件日期时间字符串。
|
||
*/
|
||
_formatPickupDate(year, month, day) {
|
||
const pad = n => (n < 10 ? '0' + n : n);
|
||
return `${year}-${pad(month)}-${pad(day)} 18:00:00`;
|
||
}
|
||
}
|
||
|
||
module.exports = PoloApiClient;
|