155 lines
4.6 KiB
JavaScript
155 lines
4.6 KiB
JavaScript
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}`;
|
||
}
|
||
async sendRequest(url, requestData) {
|
||
const startTime = Date.now();
|
||
const { service } = this;
|
||
const logData = {};
|
||
logData.body = requestData;
|
||
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) {
|
||
throw error;
|
||
}
|
||
const header = {
|
||
'Content-Type': 'application/xml',
|
||
'Content-Length': Buffer.byteLength(requestXml, 'utf8'),
|
||
'User-Agent': 'EggJS Client',
|
||
};
|
||
const options = {
|
||
method: 'POST',
|
||
headers: header,
|
||
};
|
||
const res = await new Promise((resolve, reject) => {
|
||
const req = httpquery.request(url, options, response => {
|
||
let datas = '';
|
||
response.on('data', chunk => {
|
||
datas += chunk;
|
||
});
|
||
response.on('end', () => {
|
||
resolve(datas);
|
||
});
|
||
});
|
||
|
||
req.on('error', error => {
|
||
reject(error);
|
||
});
|
||
|
||
req.write(requestXml);
|
||
req.end();
|
||
});
|
||
logData.result = res;
|
||
const queryId = await service.qimen.saveQimenLog(logData, startTime);
|
||
return { queryId, res };
|
||
}
|
||
}
|
||
module.exports = QimenQueryService;
|