liufumingren e8605149c0 初始化
2026-08-06 17:04:35 +08:00

370 lines
12 KiB
PHP
Raw Permalink 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.

<?php
namespace app\index\controller\wms;
class Qimen extends Main
{
protected $noNeedLogin = '*';
protected $noNeedRight = '*';
protected $layout = '';
public function _initialize()
{
parent::_initialize();
$this->ApiAppModel = new \app\common\model\wms_new\ApiApp;
}
public function index(){
$startTime = round(microtime(true) * 1000);
$logData = [
'app_key' => '',
'method' => '',
'request_id' => '',
'sign' => '',
'costomer_id' => '',
'v' => '',
'url' => $this->request->url(true),
'create_time' => date('Y-m-d H:i:s'),
'body' => '',
'result' => '',
'use_time' => 0
];
try {
$getParams = $this->request->get();
// 记录基础日志信息
$logData['app_key'] = $getParams['app_key'] ?? '';
$logData['method'] = $getParams['method'] ?? '';
$logData['request_id'] = $getParams['request_id'] ?? '';
$logData['sign'] = $getParams['sign'] ?? '';
$logData['costomer_id'] = $getParams['customerId'] ?? $getParams['customer_id'] ?? '';
$logData['v'] = $getParams['v'] ?? '';
// 验证必要参数
if (!$this->validateParams($getParams)) {
$errorMsg = '参数缺失或错误';
$Response = $this->errorResponse($errorMsg, 'xml');
$logData['result'] = $Response;
$this->saveLog($logData,$startTime);
return $Response;
}
// 处理method参数
$className = "";
$actionName = "";
$classNames = [];
$method = $getParams['method'];
$methods = explode('.', $method);
foreach ($methods as $key => $method_tmp){
if($key<count($methods)-1){
if($key==count($methods)-2){
$method_tmp = ucfirst($method_tmp);
}
array_push($classNames,$method_tmp);
}else{
$actionName = $method_tmp;
}
}
$className = implode("\\",$classNames);
$appkey = $getParams['app_key'];
$customerId = $getParams['customerId'];
// 获取并解析XML数据
$xmlData = file_get_contents('php://input');
if (empty($xmlData)) {
throw new \Exception('XML数据为空');
}
$logData['body'] = $xmlData;
// 验证接口是否存在且启用
if (!$this->validateApi($appkey, $customerId)) {
$errorMsg = '接口不存在或未启用';
$Response = $this->errorResponse($errorMsg, 'xml');
$logData['result'] = $Response;
$this->saveLog($logData,$startTime);
return $Response;
}
$xmlArray = $this->parseXmlToArray($xmlData);
$xmlArray['app_key'] = $appkey;
// 只传入XML数据给业务类,GET参数仅用于路由
$res = $this->callMethod($className, $actionName, $xmlArray, $getParams['format']);
// 记录成功响应
$logData['result'] = is_string($res) ? $res : json_encode($res, JSON_UNESCAPED_UNICODE);
$this->saveLog($logData,$startTime);
return $res;
} catch (\Exception $e) {
// 记录错误日志
$errorMsg = '奇门接口错误: ' . $e->getMessage();
\think\Log::error($errorMsg);
// 记录错误结果
$Response = $this->errorResponse($errorMsg, 'xml');
$logData['result'] = $Response;
$this->saveLog($logData,$startTime);
return $Response;
}
}
/**
* 验证接口是否存在且启用
*/
private function validateApi($appkey, $customerId)
{
try {
// 查询接口配置
$apiConfig = $this->ApiAppModel
->where('qimen_app_key', $appkey)
->where('qimen_customer_id', $customerId)
->where('is_enabled', 1)
->find();
if (!$apiConfig) {
return false;
}
// 这里可以根据需要添加更详细的接口方法验证
// 比如验证特定的method是否在允许的范围内
return true;
} catch (\Exception $e) {
\think\Log::error('验证接口配置失败: ' . $e->getMessage());
return false;
}
}
/**
* 保存日志到数据库
*/
private function saveLog($logData,$startTime)
{
$QimenLogModel = new \app\common\model\wms_new\QimenLog;
try {
if (!empty($logData['app_key'])) {
$apiConfig = $this->ApiAppModel
->where('qimen_app_key', $logData['app_key'])
->find();
}
// 限制日志内容长度,避免数据库字段过长
if (strlen($logData['body']) > 65535) {
$logData['body'] = substr($logData['body'], 0, 65535);
}
if (strlen($logData['result']) > 65535) {
$logData['result'] = substr($logData['result'], 0, 65535);
}
$logData['use_time'] = round(microtime(true) * 1000)-$startTime;
// 插入日志记录
$QimenLogModel->insert($logData);
} catch (\Exception $e) {
// 日志记录失败不影响主流程,但需要记录错误
\think\Log::error('保存奇门接口日志失败: ' . $e->getMessage());
}
}
private function parseXmlToArray($xmlString)
{
// 禁用libxml错误,使用自定义错误处理
libxml_use_internal_errors(true);
// 清理XML字符串,移除BOM和空白字符
$xmlString = $this->cleanXmlString($xmlString);
// 检查XML是否为空
if (empty(trim($xmlString))) {
throw new \Exception('XML数据为空');
}
// 加载XML字符串
$xml = simplexml_load_string($xmlString, 'SimpleXMLElement', LIBXML_NOCDATA);
if ($xml === false) {
$errors = libxml_get_errors();
$errorMsg = 'XML解析错误: ';
foreach ($errors as $error) {
$errorMsg .= $error->message . '; ';
}
libxml_clear_errors();
throw new \Exception($errorMsg);
}
// 转换为JSON再转数组,保持多层结构
$json = json_encode($xml);
$array = json_decode($json, true);
return $array;
}
private function cleanXmlString($xmlString)
{
// 移除UTF-8 BOM
$bom = pack('H*', 'EFBBBF');
$xmlString = preg_replace("/^$bom/", '', $xmlString);
// 移除XML声明前面的空白字符
$xmlString = ltrim($xmlString);
// 如果XML声明不在开头,尝试找到并移动到开头
if (preg_match('/<\?xml[^?>]+\?>/', $xmlString, $matches)) {
$xmlDeclaration = $matches[0];
// 移除原有的XML声明
$xmlString = preg_replace('/<\?xml[^?>]+\?>/', '', $xmlString);
// 将XML声明放到开头
$xmlString = $xmlDeclaration . "\n" . trim($xmlString);
}
return trim($xmlString);
}
private function validateParams($params)
{
$required = ['app_key', 'method', 'v', 'format', 'sign_method', 'sign', 'timestamp'];
foreach ($required as $field) {
if (empty($params[$field])) {
return false;
}
}
// 验证method格式 - 添加类型检查
if (!is_string($params['method']) || strpos($params['method'], '.') === false) {
return false;
}
return true;
}
private function callMethod($className, $actionName, $xmlData, $format = 'xml')
{
try {
// 构建类名
$class = "app\\index\\library\\qimen\\" . $className;
// 检查类是否存在
if (!class_exists($class)) {
throw new \Exception("类 {$className} 不存在");
}
// 实例化类
$instance = new $class();
// 检查方法是否存在
if (!method_exists($instance, $actionName)) {
throw new \Exception("方法 {$actionName} 不存在");
}
// 调用方法,只传入XML数据
$result = $instance->$actionName($xmlData);
// 根据format参数返回相应格式
$res = $this->formatResponse($result, $format);
return $res;
} catch (\Exception $e) {
return $this->errorResponse($e->getMessage(), $format);
}
}
private function formatResponse($data, $format)
{
switch (strtolower($format)) {
case 'xml':
return $this->xmlResponse($data);
case 'json':
default:
return json([
'success' => true,
'data' => $data,
'timestamp' => time()
]);
}
}
private function xmlResponse($data)
{
$xml = "<response>\n";
// 处理固定字段
if (isset($data['flag'])) {
$xml .= "<flag>{$data['flag']}</flag>\n";
} else {
$xml .= "<flag>success</flag>\n";
}
if (isset($data['code'])) {
$xml .= "<code>{$data['code']}</code>\n";
} else {
$xml .= "<code>1</code>\n";
}
if (isset($data['message'])) {
$xml .= "<message>{$data['message']}</message>\n";
} else {
$xml .= "<message>操作成功</message>\n";
}
// 添加其他数据字段,支持多层级
foreach ($data as $key => $value) {
if (!in_array($key, ['flag', 'code', 'message'])) {
$xml .= $this->buildXmlNode($key, $value);
}
}
$xml .= "</response>";
return $xml;
}
/**
* 构建XML节点 - 支持多层级
*/
private function buildXmlNode($key, $value, $level = 0)
{
$indent = str_repeat(" ", $level);
$xml = "";
if (is_array($value)) {
// 如果是数字索引数组,使用 <item> 包装
if (array_keys($value) === range(0, count($value) - 1)) {
$xml .= "{$indent}<{$key}>\n";
foreach ($value as $item) {
if (is_array($item)) {
$xml .= $this->buildXmlNode('item', $item, $level + 1);
} else {
$xml .= " {$indent}<item>{$item}</item>\n";
}
}
$xml .= "{$indent}</{$key}>\n";
} else {
// 关联数组
$xml .= "{$indent}<{$key}>\n";
foreach ($value as $subKey => $subValue) {
$xml .= $this->buildXmlNode($subKey, $subValue, $level + 1);
}
$xml .= "{$indent}</{$key}>\n";
}
} else {
// 简单值
$xml .= "{$indent}<{$key}>{$value}</{$key}>\n";
}
return $xml;
}
private function errorResponse($message, $format = 'json')
{
switch (strtolower($format)) {
case 'xml':
$xml = "<response>\n";
$xml .= "<success>false</success>\n";
$xml .= "<error>" . $message . "</error>\n";
$xml .= "<timestamp>" . time() . "</timestamp>\n";
$xml .= "</response>";
return $xml;
case 'json':
default:
return json([
'success' => false,
'error' => $message,
'timestamp' => time()
]);
}
}
}