WMS_MAIN/app/service/systems/qimen_query.js
2026-04-17 19:21:57 +08:00

183 lines
5.8 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

const Service = require('egg').Service;
const https = require('https');
const http = require('http');
class QimenQueryService extends Service {
async send(method, customerId, data) {
try {
const wmsAppKey = this.app.config.qimen.appKey;
const baseQueryParams = this.getQueryParams(method, wmsAppKey, '2.0', customerId);
const baseUrl = 'http://qimen.api.taobao.com/router/qimen/service';
const xmlData = await this.ctx.service.systems.sign.toXml(data);
const queryData = this.replaceXmlTagsWithString(xmlData, 'item', 'orderLine');
const sign = await this.ctx.service.systems.sign.signTopRequest(baseQueryParams, queryData, this.app.config.qimen.security, 'md5');
const queryParams = this.addSign(baseQueryParams, sign);
const url = this.generateUrlWithParams(baseUrl, queryParams);
const logData = {
from_key: this.app.config.qimen.appKey,
to_key: wmsAppKey,
method,
sign,
costomer_id: customerId,
v: '2.0',
url,
created_at: new Date(),
body: '',
result: '',
use_time: 0,
};
const result = await this.sendRequest(url, queryData, logData);
const xmlArray = await this.ctx.service.qimen.parseXmlToArray(result.res);
return { queryId: result.queryId, xmlArray };
} catch (error) {
throw error;
}
}
replaceXmlTagsWithString(xmlString, oldTag, newTag) {
// 匹配开始标签(包括属性)
const startTagRegex = new RegExp(`<\\s*${oldTag}(\\s+[^>]*)?>`, 'gi');
// 匹配结束标签
const endTagRegex = new RegExp(`<\\s*/\\s*${oldTag}\\s*>`, 'gi');
// 匹配自闭合标签
const selfClosingRegex = new RegExp(`<\\s*${oldTag}(\\s+[^>]*)?\\s*/>`, 'gi');
return xmlString
.replace(startTagRegex, (match, attributes = '') => {
return `<${newTag}${attributes}>`;
})
.replace(endTagRegex, `</${newTag}>`)
.replace(selfClosingRegex, (match, attributes = '') => {
return `<${newTag}${attributes}/>`;
});
}
addSign(baseQueryParams, sign) {
return Object.assign({}, baseQueryParams, { sign });
}
getQueryParams(method, app_key, v, customerId) {
const param = {
method,
format: 'xml',
app_key,
v,
sign_method: 'md5',
customerId,
timestamp: this.app.formatDate(new Date()),
};
return param;
}
generateUrlWithParams(baseUrl, params) {
if (!params || Object.keys(params).length === 0) {
return baseUrl;
}
const queryString = Object.keys(params)
.map(key => {
const value = params[key];
// 对参数进行URL编码
return `${encodeURIComponent(key)}=${encodeURIComponent(value)}`;
})
.join('&');
// 检查基础URL是否已包含查询参数
const separator = baseUrl.includes('?') ? '&' : '?';
return `${baseUrl}${separator}${queryString}`;
}
/**
* 发送奇门请求并在成功或失败时落库日志。
* @param {string} url 请求地址。
* @param {string} requestData 请求报文。
* @param {Object} [logData={}] 日志基础数据。
* @return {Promise<{queryId: *, res: string}>} 请求结果。
*/
async sendRequest(url, requestData, logData = {}) {
const startTime = Date.now();
const { service } = this;
const requestLogData = Object.assign({
body: requestData,
result: '',
log_id: this.ctx.qimenLogId || null,
}, logData);
requestLogData.body = requestLogData.body || requestData;
requestLogData.result = requestLogData.result || '';
requestLogData.log_id = requestLogData.log_id || this.ctx.qimenLogId || null;
let httpquery = null;
if (url.indexOf('https://') > -1) {
httpquery = https;
} else {
httpquery = http;
}
let requestXml;
try {
// 判断 requestData 是否为字符串,如果是字符串则直接使用,否则进行转换
if (typeof requestData === 'string') {
requestXml = requestData;
// 可选:验证字符串是否是有效的XML
if (requestXml.trim() === '') {
throw new Error('请求数据为空字符串');
}
} else {
requestXml = await this.ctx.service.qimen.formatResponse(requestData);
}
// 最终检查XML是否为空
if (!requestXml || requestXml.trim() === '') {
throw new Error('XML内容为空');
}
} catch (error) {
requestLogData.result = error.stack || `${error.name || 'Error'}: ${error.message || String(error)}`;
await service.qimen.saveQimenLog(requestLogData, startTime);
throw error;
}
const header = {
'Content-Type': 'application/xml',
'Content-Length': Buffer.byteLength(requestXml, 'utf8'),
'User-Agent': 'EggJS Client',
};
const options = {
method: 'POST',
headers: header,
};
let res;
try {
res = await new Promise((resolve, reject) => {
let req;
try {
req = httpquery.request(url, options, response => {
let datas = '';
response.on('data', chunk => {
datas += chunk;
});
response.on('end', () => {
resolve(datas);
});
});
} catch (error) {
reject(error);
return;
}
req.on('error', error => {
reject(error);
});
req.write(requestXml);
req.end();
});
} catch (error) {
requestLogData.result = error.stack || `${error.name || 'Error'}: ${error.message || String(error)}`;
await service.qimen.saveQimenLog(requestLogData, startTime);
throw error;
}
requestLogData.result = res;
const queryId = await service.qimen.saveQimenLog(requestLogData, startTime);
return { queryId, res };
}
}
module.exports = QimenQueryService;