931 lines
28 KiB
JavaScript
931 lines
28 KiB
JavaScript
const crypto = require('crypto');
|
||
const {
|
||
Controller,
|
||
} = require('egg');
|
||
const { toSuccess, toFailure } = require('../lib/api_response');
|
||
|
||
class HomeController extends Controller {
|
||
/**
|
||
* 解析平台授权回调 state,提取平台编码与授权随机码。
|
||
* @param {string} state 回调原始 state。
|
||
* @param {string} reservationCodePrefix 配置的预留前缀。
|
||
* @return {{normalizedState: string, platformCode: string, authRandomCode: string}|null} 解析结果,失败时返回 null。
|
||
*/
|
||
parsePlatformOauthState(state, reservationCodePrefix) {
|
||
const normalizedState = reservationCodePrefix && state.startsWith(reservationCodePrefix)
|
||
? state.slice(reservationCodePrefix.length)
|
||
: state;
|
||
const separatorIndex = normalizedState.indexOf('_');
|
||
|
||
if (separatorIndex <= 0 || separatorIndex === normalizedState.length - 1) {
|
||
return null;
|
||
}
|
||
|
||
const platformCode = normalizedState.slice(0, separatorIndex).trim();
|
||
const authRandomCode = normalizedState.slice(separatorIndex + 1).trim();
|
||
|
||
if (!platformCode || !authRandomCode) {
|
||
return null;
|
||
}
|
||
|
||
return {
|
||
normalizedState,
|
||
platformCode,
|
||
authRandomCode,
|
||
};
|
||
}
|
||
|
||
/**
|
||
* 组装平台授权回调页面展示数据。
|
||
* @param {object} payload 页面数据参数。
|
||
* @param {string} payload.code 平台回调返回的授权码。
|
||
* @param {string} payload.state 平台回调返回的原始 state。
|
||
* @param {{normalizedState: string, platformCode: string, authRandomCode: string}|null} payload.parsedState 解析后的 state 数据。
|
||
* @param {import('sequelize').Model|null} payload.shop 店铺记录。
|
||
* @param {string} payload.errorMessage 预校验失败提示。
|
||
* @return {object} 页面渲染数据。
|
||
*/
|
||
buildPlatformOauthCallbackViewData({ code, state, parsedState, shop, errorMessage }) {
|
||
const platformCode = parsedState ? parsedState.platformCode : '';
|
||
const authRandomCode = parsedState ? parsedState.authRandomCode : '';
|
||
const normalizedState = parsedState ? parsedState.normalizedState : '';
|
||
const hasShop = Boolean(shop);
|
||
const isProcessed = hasShop ? Number(shop.status) === 1 : null;
|
||
const isPlatformMatched = hasShop && parsedState
|
||
? String(shop.platform_code || '') === platformCode
|
||
: null;
|
||
let resultLevel = 'error';
|
||
let resultText = errorMessage || '授权回调校验失败';
|
||
|
||
if (!errorMessage && !hasShop) {
|
||
resultText = '预授权码不存在';
|
||
} else if (!errorMessage && isPlatformMatched === false) {
|
||
resultText = '平台不匹配';
|
||
} else if (!errorMessage && isProcessed === true) {
|
||
resultLevel = 'warning';
|
||
resultText = '该预授权码已处理';
|
||
} else if (!errorMessage && isProcessed === false && isPlatformMatched === true) {
|
||
resultLevel = 'success';
|
||
resultText = '预授权码有效,平台匹配且尚未处理';
|
||
}
|
||
|
||
return {
|
||
title: '平台授权回调结果',
|
||
resultLevel,
|
||
resultText,
|
||
code,
|
||
state,
|
||
normalizedState,
|
||
platformCode,
|
||
authRandomCode,
|
||
isProcessed,
|
||
isProcessedText: hasShop
|
||
? (isProcessed ? '是(已处理)' : '否(未处理)')
|
||
: '无法判断',
|
||
isPlatformMatched,
|
||
isPlatformMatchedText: hasShop
|
||
? (isPlatformMatched ? '是' : '否')
|
||
: '无法判断',
|
||
shopPlatformCode: hasShop ? String(shop.platform_code || '') : '',
|
||
shopStatus: hasShop ? Number(shop.status) : null,
|
||
hasShop,
|
||
};
|
||
}
|
||
|
||
async testSendData() {
|
||
await this.ctx.service.systems.print.index.test();
|
||
this.ctx.body = 'ok';
|
||
}
|
||
|
||
async index() {
|
||
const {
|
||
ctx,
|
||
} = this;
|
||
ctx.body = 'pong';
|
||
}
|
||
|
||
/**
|
||
* 使用授权码请求拼多多开放平台换取授权结果,并返回结构化处理结果。
|
||
* @param {string} code 平台回调返回的授权码。
|
||
* @return {Promise<{success: boolean, message?: string, result: object|null}>} 请求处理结果。
|
||
*/
|
||
async pdd(code) {
|
||
const pddConfig = this.app.config.pdd || {};
|
||
|
||
try {
|
||
const result = await this.ctx.curl('https://open-api.pinduoduo.com/oauth/token', {
|
||
method: 'POST',
|
||
headers: {
|
||
'Content-Type': 'application/json',
|
||
},
|
||
dataType: 'json',
|
||
data: {
|
||
client_id: pddConfig.client_id || '',
|
||
code,
|
||
grant_type: 'authorization_code',
|
||
client_secret: pddConfig.client_secret || '',
|
||
},
|
||
});
|
||
|
||
console.log(result);
|
||
|
||
if (result && result.data && result.data.error_response) {
|
||
const errorMessage = result.data.error_response.error_msg || '未知错误';
|
||
|
||
return {
|
||
success: false,
|
||
message: `拼多多授权失败:${errorMessage}`,
|
||
result,
|
||
};
|
||
}
|
||
|
||
return {
|
||
success: true,
|
||
result,
|
||
};
|
||
} catch (error) {
|
||
this.ctx.logger.error('[platform-oauth][PDD] oauth/token 请求异常: %s', error);
|
||
|
||
return {
|
||
success: false,
|
||
message: `拼多多授权请求异常:${error.message}`,
|
||
result: null,
|
||
};
|
||
}
|
||
}
|
||
|
||
/**
|
||
* 构建拼多多授权店铺回写字段。
|
||
* @param {object|null|undefined} oauthData 拼多多授权返回数据。
|
||
* @return {object} 可直接用于店铺模型回写的字段对象。
|
||
*/
|
||
buildPddOauthShopUpdatePayload(oauthData) {
|
||
const toDateFromUnixSeconds = value => {
|
||
const seconds = Number(value);
|
||
|
||
if (!Number.isFinite(seconds) || seconds <= 0) {
|
||
return null;
|
||
}
|
||
|
||
return new Date(seconds * 1000);
|
||
};
|
||
const updatePayload = {
|
||
owner_id: oauthData && oauthData.owner_id !== undefined ? oauthData.owner_id : null,
|
||
access_token: oauthData && oauthData.access_token !== undefined ? oauthData.access_token : null,
|
||
refresh_token: oauthData && oauthData.refresh_token !== undefined ? oauthData.refresh_token : null,
|
||
token_expires_at: toDateFromUnixSeconds(oauthData && oauthData.expires_at),
|
||
refresh_token_expires_at: toDateFromUnixSeconds(oauthData && oauthData.refresh_token_expires_at),
|
||
auth_expire_at: toDateFromUnixSeconds(oauthData && oauthData.expires_at),
|
||
scope: oauthData && oauthData.scope !== undefined ? oauthData.scope : null,
|
||
status: 1,
|
||
};
|
||
|
||
if (oauthData && oauthData.owner_name) {
|
||
updatePayload.shop_name = oauthData.owner_name;
|
||
}
|
||
|
||
return updatePayload;
|
||
}
|
||
|
||
/**
|
||
* 按仓库、平台与授权标识查找已授权的旧店铺记录。
|
||
* @param {import('sequelize').Model} shop 当前预申请店铺记录。
|
||
* @param {object|null|undefined} oauthData 拼多多授权返回数据。
|
||
* @param {import('sequelize').Transaction} transaction 当前事务对象。
|
||
* @return {Promise<import('sequelize').Model|null>} 命中的已授权店铺记录。
|
||
*/
|
||
async findAuthorizedPddOauthShop(shop, oauthData, transaction) {
|
||
const { Op } = this.app.Sequelize;
|
||
const ownerId = oauthData && oauthData.owner_id !== undefined && oauthData.owner_id !== null
|
||
? String(oauthData.owner_id).trim()
|
||
: '';
|
||
const ownerName = oauthData && oauthData.owner_name !== undefined && oauthData.owner_name !== null
|
||
? String(oauthData.owner_name).trim()
|
||
: '';
|
||
const matchConditions = [];
|
||
|
||
if (ownerId) {
|
||
matchConditions.push({ owner_id: oauthData.owner_id });
|
||
}
|
||
|
||
if (ownerName) {
|
||
matchConditions.push({ shop_name: ownerName });
|
||
}
|
||
|
||
if (!matchConditions.length) {
|
||
return null;
|
||
}
|
||
|
||
return await this.ctx.model.Shop.findOne({
|
||
where: {
|
||
warehouse_id: shop.warehouse_id,
|
||
platform_code: shop.platform_code,
|
||
status: 1,
|
||
id: {
|
||
[Op.ne]: shop.id,
|
||
},
|
||
[Op.or]: matchConditions,
|
||
},
|
||
transaction,
|
||
});
|
||
}
|
||
|
||
/**
|
||
* 将拼多多授权成功后的关键字段回写到店铺记录。
|
||
* @param {import('sequelize').Model} shop 店铺模型实例。
|
||
* @param {object|null|undefined} oauthData 拼多多授权返回数据。
|
||
* @return {Promise<import('sequelize').Model>} 已保存的店铺模型实例。
|
||
*/
|
||
async updatePddOauthShop(shop, oauthData) {
|
||
const updatePayload = this.buildPddOauthShopUpdatePayload(oauthData);
|
||
const saveFields = [
|
||
'owner_id',
|
||
'shop_name',
|
||
'access_token',
|
||
'refresh_token',
|
||
'token_expires_at',
|
||
'refresh_token_expires_at',
|
||
'auth_expire_at',
|
||
'scope',
|
||
'status',
|
||
];
|
||
|
||
return await this.ctx.model.transaction(async transaction => {
|
||
const authorizedShop = await this.findAuthorizedPddOauthShop(shop, oauthData, transaction);
|
||
|
||
if (authorizedShop) {
|
||
authorizedShop.set(updatePayload);
|
||
await authorizedShop.save({
|
||
fields: saveFields,
|
||
transaction,
|
||
});
|
||
await shop.destroy({ transaction });
|
||
|
||
return authorizedShop;
|
||
}
|
||
|
||
shop.set(updatePayload);
|
||
await shop.save({
|
||
fields: saveFields,
|
||
transaction,
|
||
});
|
||
|
||
return shop;
|
||
});
|
||
}
|
||
|
||
/**
|
||
* 处理平台授权回调请求,解析 query 中的 code 与 state。
|
||
* @return {Promise<void>} 无返回值。
|
||
*/
|
||
async platformOauthCallback() {
|
||
const {
|
||
ctx,
|
||
app,
|
||
} = this;
|
||
const code = typeof ctx.query.code === 'string' ? ctx.query.code.trim() : '';
|
||
const state = typeof ctx.query.state === 'string' ? ctx.query.state.trim() : '';
|
||
const reservationCodePrefix = app.config.platformOauthReservationCodePrefix || '';
|
||
const parsedState = state ? this.parsePlatformOauthState(state, reservationCodePrefix) : null;
|
||
let errorMessage = '';
|
||
let shop = null;
|
||
|
||
if (!code) {
|
||
errorMessage = 'code不能为空';
|
||
} else if (!state) {
|
||
errorMessage = 'state不能为空';
|
||
} else if (!parsedState) {
|
||
errorMessage = 'state解析失败';
|
||
} else {
|
||
switch (parsedState.platformCode) {
|
||
case 'PDD':
|
||
{
|
||
const pddResult = await this.pdd(code);
|
||
|
||
if (pddResult.success === false) {
|
||
errorMessage = pddResult.message;
|
||
break;
|
||
}
|
||
|
||
shop = await ctx.model.Shop.findOne({
|
||
where: {
|
||
auth_random_code: parsedState.authRandomCode,
|
||
},
|
||
});
|
||
|
||
if (shop && String(shop.platform_code || '') === parsedState.platformCode) {
|
||
const oauthData = pddResult.result && pddResult.result.data
|
||
? pddResult.result.data
|
||
: pddResult.result;
|
||
|
||
shop = await this.updatePddOauthShop(shop, oauthData);
|
||
}
|
||
}
|
||
break;
|
||
default:
|
||
errorMessage = `暂未接入该平台授权回调处理`;
|
||
break;
|
||
}
|
||
}
|
||
|
||
const viewData = this.buildPlatformOauthCallbackViewData({
|
||
code,
|
||
state,
|
||
parsedState,
|
||
shop,
|
||
errorMessage,
|
||
});
|
||
|
||
ctx.status = viewData.resultLevel === 'error' ? 400 : 200;
|
||
await ctx.render('platform_oauth_callback.html', viewData);
|
||
}
|
||
/**
|
||
* 处理奇门统一入口请求,完成参数校验、XML 解析、仓库编码提取与方法分发。
|
||
* @return {Promise<void>} 无返回值。
|
||
*/
|
||
async qimen() {
|
||
const {
|
||
ctx,
|
||
service,
|
||
} = this;
|
||
const startTime = Date.now();
|
||
const logId = 'QL-' + Date.now() + '-' + crypto.randomBytes(3).toString('hex');
|
||
ctx.qimenLogId = logId;
|
||
|
||
// 初始化日志数据
|
||
const logData = {
|
||
log_id: logId,
|
||
from_key: '',
|
||
to_key: this.app.config.qimen.appKey,
|
||
method: '',
|
||
sign: '',
|
||
costomer_id: '',
|
||
v: '',
|
||
url: ctx.request.href,
|
||
created_at: new Date(),
|
||
body: '',
|
||
result: '',
|
||
use_time: 0,
|
||
};
|
||
const getParams = ctx.query;
|
||
// 记录基础日志信息
|
||
logData.from_key = getParams.app_key || '';
|
||
logData.method = getParams.method || '';
|
||
logData.sign = getParams.sign || '';
|
||
logData.costomer_id = getParams.customerId || getParams.customer_id || '';
|
||
logData.v = getParams.v || '';
|
||
try {
|
||
|
||
// 验证必要参数
|
||
if (!this.validateQimenParams(getParams)) {
|
||
const errorMsg = '参数缺失或错误';
|
||
const response = this.errorResponse(errorMsg, 'xml');
|
||
ctx.body = response;
|
||
ctx.type = 'application/xml';
|
||
return;
|
||
}
|
||
|
||
// 处理method参数
|
||
const method = getParams.method;
|
||
const methods = method.split('.');
|
||
const actionName = methods.pop();
|
||
const className = methods.map((item, index) =>
|
||
(index === methods.length - 1 ? item : item)
|
||
).join('.');
|
||
|
||
const appkey = getParams.app_key;
|
||
const customerId = getParams.customerId;
|
||
|
||
// 获取XML数据
|
||
let xmlData = '';
|
||
if (ctx.request.rawBody) {
|
||
// 使用 rawBody 获取原始请求体
|
||
xmlData = ctx.request.rawBody;
|
||
} else {
|
||
// 如果没有 rawBody,尝试从流中读取
|
||
xmlData = 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);
|
||
});
|
||
}
|
||
|
||
// 确保 xmlData 是字符串
|
||
xmlData = xmlData ? String(xmlData) : '';
|
||
|
||
if (!xmlData || xmlData.trim() === '') {
|
||
throw new Error('XML数据为空');
|
||
}
|
||
|
||
// 解析XML数据
|
||
const xmlArray = await service.qimen.parseXmlToArray(xmlData);
|
||
xmlArray.app_key = appkey;
|
||
const warehouseCode = this.getQimenWarehouseCode(xmlArray);
|
||
|
||
if (!warehouseCode) {
|
||
const errorMsg = 'XML数据格式错误,无法提取有效的warehouseCode';
|
||
const responseFormat = getParams.format || 'xml';
|
||
const response = this.errorResponse(errorMsg, responseFormat);
|
||
ctx.body = response;
|
||
ctx.type = responseFormat === 'xml' ? 'application/xml' : 'application/json';
|
||
return;
|
||
}
|
||
|
||
logData.body = xmlData;
|
||
const erpName = await service.qimen.getErpName(appkey);
|
||
let api_info = {
|
||
warehouseCode: '',
|
||
ownerCode: '',
|
||
};
|
||
if (warehouseCode && customerId) {
|
||
// 验证接口是否存在且启用
|
||
api_info = await service.qimen.validateApi(appkey, customerId, warehouseCode);
|
||
if (!api_info) {
|
||
const errorMsg = `奇门${erpName}客户编码${customerId}仓库编码${warehouseCode}未绑定到你的货主或未启用,请联系仓库绑定`;
|
||
const response = this.errorResponse(errorMsg, 'xml');
|
||
ctx.body = response;
|
||
ctx.type = 'application/xml';
|
||
return;
|
||
}
|
||
if (api_info.contract_auth_status !== 2) {
|
||
const errorMsg = `货主与仓库签约状态异常,请到WMS核实签约状态${api_info.contract_auth_status}`;
|
||
const response = this.errorResponse(errorMsg, 'xml');
|
||
ctx.body = response;
|
||
ctx.type = 'application/xml';
|
||
return;
|
||
}
|
||
if (api_info.warehouse_status === 0) {
|
||
const errorMsg = '仓库状态异常,请联系仓库核实WMS状态';
|
||
const response = this.errorResponse(errorMsg, 'xml');
|
||
ctx.body = response;
|
||
ctx.type = 'application/xml';
|
||
return;
|
||
}
|
||
const currentTime = new Date();
|
||
const authEndTime = new Date(api_info.warehouse_auth_end);
|
||
const authEndTime2 = new Date(api_info.auth_end);
|
||
if (authEndTime2 < currentTime) {
|
||
const errorMsg = '与仓库合约过期,请到WMS重新发起仓库续约';
|
||
const response = this.errorResponse(errorMsg, 'xml');
|
||
ctx.body = response;
|
||
ctx.type = 'application/xml';
|
||
return;
|
||
}
|
||
if (authEndTime < currentTime) {
|
||
const errorMsg = '仓库订阅过期,请联系仓库核实状态';
|
||
const response = this.errorResponse(errorMsg, 'xml');
|
||
ctx.body = response;
|
||
ctx.type = 'application/xml';
|
||
return;
|
||
}
|
||
}
|
||
|
||
// 调用业务方法
|
||
const result = await service.qimen.callMethod(className, actionName, xmlArray, api_info.store_id,
|
||
api_info.warehouse_id, appkey, customerId, warehouseCode, getParams.format);
|
||
|
||
ctx.body = result;
|
||
ctx.type = getParams.format === 'xml' ? 'application/xml' : 'application/json';
|
||
} catch (error) {
|
||
const response = this.errorResponse('奇门接口错误: ' + error.message, ctx.query.format || 'xml');
|
||
ctx.body = response;
|
||
ctx.type = ctx.query.format === 'xml' ? 'application/xml' : 'application/json';
|
||
} finally {
|
||
// 统一写入日志文件队列
|
||
logData.use_time = Date.now() - startTime;
|
||
logData.result = typeof ctx.body === 'string' ? ctx.body : JSON.stringify(ctx.body);
|
||
if (logData.body && logData.body.length > 65535) {
|
||
logData.body = logData.body.substring(0, 65535);
|
||
}
|
||
if (logData.result && logData.result.length > 65535) {
|
||
logData.result = logData.result.substring(0, 65535);
|
||
}
|
||
// 日志落盘改为异步投递,避免阻塞主请求响应。
|
||
Promise.resolve(this.app.fileWriter.writeRecord('qimen-logs', logData)).catch(writeErr => {
|
||
ctx.logger.error('[qimen-log-sink] 写入文件失败: ' + writeErr.message);
|
||
ctx.logger.info('[qimen-log-sink] 日志数据: ', JSON.stringify(logData));
|
||
});
|
||
}
|
||
}
|
||
|
||
/**
|
||
* 归一化奇门字段值,过滤空白内容和占位符字符串。
|
||
* @param {string|number|null|undefined} value 待处理字段值。
|
||
* @return {string} 归一化后的字段值。
|
||
*/
|
||
normalizeQimenFieldValue(value) {
|
||
if (value === null || value === undefined) {
|
||
return '';
|
||
}
|
||
|
||
const normalizedValue = String(value).trim();
|
||
if (!normalizedValue || normalizedValue === 'warehouseCode') {
|
||
return '';
|
||
}
|
||
|
||
return normalizedValue;
|
||
}
|
||
|
||
/**
|
||
* 递归扫描奇门 XML 树,提取指定字段的有效值,只匹配字段名对应的节点。
|
||
* @param {Object|Array|string|number|null|undefined} node 待扫描节点。
|
||
* @param {string} fieldName 目标字段名。
|
||
* @param {Set<Object>} [visited=new Set()] 循环引用保护集合。
|
||
* @return {string} 找到的有效字段值。
|
||
*/
|
||
findQimenFieldValue(node, fieldName, visited = new Set()) {
|
||
if (node === null || node === undefined) {
|
||
return '';
|
||
}
|
||
|
||
if (typeof node !== 'object') {
|
||
return '';
|
||
}
|
||
|
||
if (visited.has(node)) {
|
||
return '';
|
||
}
|
||
|
||
visited.add(node);
|
||
|
||
if (Array.isArray(node)) {
|
||
for (const item of node) {
|
||
const value = this.findQimenFieldValue(item, fieldName, visited);
|
||
if (value) {
|
||
return value;
|
||
}
|
||
}
|
||
return '';
|
||
}
|
||
|
||
if (Object.prototype.hasOwnProperty.call(node, fieldName)) {
|
||
const directValue = this.normalizeQimenFieldValue(node[fieldName]);
|
||
if (directValue) {
|
||
return directValue;
|
||
}
|
||
|
||
const nestedValue = this.findQimenFieldValue(node[fieldName], fieldName, visited);
|
||
if (nestedValue) {
|
||
return nestedValue;
|
||
}
|
||
}
|
||
|
||
for (const [ key, value ] of Object.entries(node)) {
|
||
if (key === fieldName) {
|
||
continue;
|
||
}
|
||
|
||
if (value === null || value === undefined) {
|
||
continue;
|
||
}
|
||
|
||
if (typeof value !== 'object') {
|
||
continue;
|
||
}
|
||
|
||
const foundValue = this.findQimenFieldValue(value, fieldName, visited);
|
||
if (foundValue) {
|
||
return foundValue;
|
||
}
|
||
}
|
||
|
||
return '';
|
||
}
|
||
|
||
/**
|
||
* 从奇门请求体中提取有效的仓库编码,优先读取 request 下的固定路径,再回退到递归扫描。
|
||
* @param {Object} xmlArray 解析后的 XML 数据。
|
||
* @return {string} 有效的仓库编码。
|
||
*/
|
||
getQimenWarehouseCode(xmlArray) {
|
||
const request = xmlArray?.request || xmlArray || {};
|
||
|
||
const fixedPaths = [
|
||
request?.deliveryOrder?.warehouseCode,
|
||
request?.entryOrder?.warehouseCode,
|
||
request.warehouseCode,
|
||
];
|
||
|
||
for (const value of fixedPaths) {
|
||
const normalizedValue = this.normalizeQimenFieldValue(value);
|
||
if (normalizedValue) {
|
||
return normalizedValue;
|
||
}
|
||
}
|
||
|
||
return this.findQimenFieldValue(request, 'warehouseCode')
|
||
|| this.findQimenFieldValue(xmlArray, 'warehouseCode')
|
||
|| '';
|
||
}
|
||
|
||
validateParams(params) {
|
||
const required = [ 'method', 'v', 'format', 'timestamp' ];
|
||
|
||
for (const field of required) {
|
||
if (!params[field]) {
|
||
return false;
|
||
}
|
||
}
|
||
|
||
// 验证method格式
|
||
if (typeof params.method !== 'string' || !params.method.includes('.')) {
|
||
return false;
|
||
}
|
||
|
||
return true;
|
||
}
|
||
validateQimenParams(params) {
|
||
const required = [ 'app_key', 'method', 'v', 'format', 'sign_method', 'sign', 'timestamp' ];
|
||
|
||
for (const field of required) {
|
||
if (!params[field]) {
|
||
return false;
|
||
}
|
||
}
|
||
|
||
// 验证method格式
|
||
if (typeof params.method !== 'string' || !params.method.includes('.')) {
|
||
return false;
|
||
}
|
||
|
||
return true;
|
||
}
|
||
errorResponse(message, format = 'json') {
|
||
const timestamp = Math.floor(Date.now() / 1000);
|
||
|
||
if (format.toLowerCase() === 'xml') {
|
||
return `<?xml version="1.0" encoding="UTF-8"?>
|
||
<response>
|
||
<flag>failure</flag>
|
||
<code>0</code>
|
||
<message>${this.escapeXml(message)}</message>
|
||
</response>`;
|
||
}
|
||
|
||
return {
|
||
flag: false,
|
||
message,
|
||
code: 0,
|
||
timestamp,
|
||
};
|
||
}
|
||
|
||
escapeXml(unsafe) {
|
||
if (!unsafe) return '';
|
||
return unsafe.replace(/[<>&'"]/g, c => {
|
||
switch (c) {
|
||
case '<':
|
||
return '<';
|
||
case '>':
|
||
return '>';
|
||
case '&':
|
||
return '&';
|
||
case '\'':
|
||
return ''';
|
||
case '"':
|
||
return '"';
|
||
default:
|
||
return c;
|
||
}
|
||
});
|
||
}
|
||
|
||
async pda() {
|
||
const {
|
||
ctx,
|
||
service,
|
||
} = this;
|
||
ctx.query_count = 1;
|
||
const startTime = Date.now();
|
||
const logData = {
|
||
method: '',
|
||
v: '',
|
||
url: ctx.request.href,
|
||
created_at: new Date(),
|
||
body: '',
|
||
headers: JSON.stringify(ctx.headers),
|
||
result: '',
|
||
use_time: 0,
|
||
auth: '',
|
||
store_id: null,
|
||
};
|
||
try {
|
||
const getParams = ctx.query;
|
||
logData.method = getParams.method || '';
|
||
logData.v = getParams.v || '';
|
||
const requestCheck = service.system.validateRequestContext(getParams, ctx.headers);
|
||
if (!requestCheck.ok) {
|
||
const response = toFailure({
|
||
message: requestCheck.message,
|
||
httpStatus: requestCheck.status,
|
||
code: requestCheck.code,
|
||
});
|
||
logData.result = response;
|
||
service.system.saveLog(logData, startTime);
|
||
ctx.body = response;
|
||
ctx.status = requestCheck.status;
|
||
ctx.type = 'application/json';
|
||
return;
|
||
}
|
||
const authHeader = ctx.headers.authorization;
|
||
|
||
// 处理method参数
|
||
const method = getParams.method;
|
||
const methods = method.split('.');
|
||
const actionName = methods.pop();
|
||
const className = methods.map((item, index) =>
|
||
(index === methods.length - 1 ? item : item)
|
||
).join('.');
|
||
|
||
// 获取JSON数据
|
||
let jsonData = '';
|
||
if (ctx.request.rawBody) {
|
||
// 使用 rawBody 获取原始请求体
|
||
jsonData = ctx.request.rawBody;
|
||
} else {
|
||
// 如果没有 rawBody,尝试从流中读取
|
||
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 = jsonData ? String(jsonData) : '';
|
||
logData.body = jsonData;
|
||
if (!jsonData || jsonData.trim() === '') {
|
||
throw new Error('json数据为空');
|
||
}
|
||
try {
|
||
jsonData = JSON.parse(jsonData);
|
||
} catch (e) {
|
||
throw new Error('json数据解析错误');
|
||
}
|
||
// 调用业务方法
|
||
const { isLog, result } = await service.system.callMethod(className, actionName, jsonData, authHeader);
|
||
// 记录成功响应
|
||
logData.result = typeof result === 'string' ? result : JSON.stringify(result);
|
||
if (ctx.user) {
|
||
logData.auth = JSON.stringify(ctx.user);
|
||
logData.store_id = ctx.user.store_id;
|
||
}
|
||
if (isLog) {
|
||
service.system.saveLog(logData, startTime);
|
||
}
|
||
if (result.status && result.status !== 200) {
|
||
ctx.body = toFailure({
|
||
message: result.message || '请求失败',
|
||
httpStatus: result.status,
|
||
code: result.code,
|
||
data: result.data || null,
|
||
});
|
||
} else {
|
||
ctx.body = toSuccess(result.data);
|
||
}
|
||
ctx.type = 'application/json';
|
||
ctx.status = result.status || 200;
|
||
} catch (error) {
|
||
ctx.status = 500;
|
||
console.log(error);
|
||
const response = toFailure({
|
||
message: '接口错误: ' + error.message,
|
||
httpStatus: 500,
|
||
code: 500,
|
||
});
|
||
logData.result = typeof response === 'string' ? response : JSON.stringify(response);
|
||
service.system.saveLog(logData, startTime);
|
||
ctx.body = response;
|
||
ctx.type = 'application/json';
|
||
}
|
||
}
|
||
async system() {
|
||
const {
|
||
ctx,
|
||
service,
|
||
} = this;
|
||
ctx.query_count = 1;
|
||
const startTime = Date.now();
|
||
const logData = {
|
||
method: '',
|
||
v: '',
|
||
url: ctx.request.href,
|
||
created_at: new Date(),
|
||
body: '',
|
||
headers: JSON.stringify(ctx.headers),
|
||
result: '',
|
||
use_time: 0,
|
||
auth: '',
|
||
store_id: null,
|
||
};
|
||
try {
|
||
const getParams = ctx.query;
|
||
logData.method = getParams.method || '';
|
||
logData.v = getParams.v || '';
|
||
const requestCheck = service.system.validateRequestContext(getParams, ctx.headers);
|
||
if (!requestCheck.ok) {
|
||
const response = toFailure({
|
||
message: requestCheck.message,
|
||
httpStatus: requestCheck.status,
|
||
code: requestCheck.code,
|
||
});
|
||
logData.result = response;
|
||
service.system.saveLog(logData, startTime);
|
||
ctx.body = response;
|
||
ctx.status = requestCheck.status;
|
||
ctx.type = 'application/json';
|
||
return;
|
||
}
|
||
const authHeader = ctx.headers.authorization;
|
||
ctx.device = ctx.headers.device;
|
||
ctx.project = ctx.headers.project;
|
||
|
||
// 处理method参数
|
||
const method = getParams.method;
|
||
const methods = method.split('.');
|
||
const actionName = methods.pop();
|
||
const className = methods.map((item, index) =>
|
||
(index === methods.length - 1 ? item : item)
|
||
).join('.');
|
||
|
||
// 获取JSON数据
|
||
let jsonData = '';
|
||
if (ctx.request.rawBody) {
|
||
// 使用 rawBody 获取原始请求体
|
||
jsonData = ctx.request.rawBody;
|
||
} else {
|
||
// 如果没有 rawBody,尝试从流中读取
|
||
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 = jsonData ? String(jsonData) : '';
|
||
logData.body = jsonData;
|
||
if (!jsonData || jsonData.trim() === '') {
|
||
throw new Error('json数据为空');
|
||
}
|
||
try {
|
||
jsonData = JSON.parse(jsonData);
|
||
} catch (e) {
|
||
throw new Error('json数据解析错误');
|
||
}
|
||
// 调用业务方法
|
||
const { isLog, result } = await service.system.callMethod(className, actionName, jsonData, authHeader);
|
||
// 记录成功响应
|
||
logData.result = typeof result === 'string' ? result : JSON.stringify(result);
|
||
if (ctx.user) {
|
||
logData.auth = JSON.stringify(ctx.user);
|
||
logData.store_id = ctx.user.store_id;
|
||
}
|
||
if (isLog) {
|
||
service.system.saveLog(logData, startTime);
|
||
}
|
||
if (result.status && result.status !== 200) {
|
||
ctx.body = toFailure({
|
||
message: result.message || '请求失败',
|
||
httpStatus: result.status,
|
||
code: result.code,
|
||
data: result.data || null,
|
||
});
|
||
} else {
|
||
ctx.body = toSuccess(result.data);
|
||
}
|
||
ctx.type = 'application/json';
|
||
ctx.status = result.status || 200;
|
||
} catch (error) {
|
||
ctx.status = 500;
|
||
console.log(error);
|
||
const response = toFailure({
|
||
message: '接口错误: ' + error.message,
|
||
httpStatus: 500,
|
||
code: 500,
|
||
});
|
||
logData.result = typeof response === 'string' ? response : JSON.stringify(response);
|
||
service.system.saveLog(logData, startTime);
|
||
ctx.body = response;
|
||
ctx.type = 'application/json';
|
||
}
|
||
}
|
||
}
|
||
|
||
module.exports = HomeController;
|