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($keyvalidateApi($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 = "\n"; // 处理固定字段 if (isset($data['flag'])) { $xml .= "{$data['flag']}\n"; } else { $xml .= "success\n"; } if (isset($data['code'])) { $xml .= "{$data['code']}\n"; } else { $xml .= "1\n"; } if (isset($data['message'])) { $xml .= "{$data['message']}\n"; } else { $xml .= "操作成功\n"; } // 添加其他数据字段,支持多层级 foreach ($data as $key => $value) { if (!in_array($key, ['flag', 'code', 'message'])) { $xml .= $this->buildXmlNode($key, $value); } } $xml .= ""; return $xml; } /** * 构建XML节点 - 支持多层级 */ private function buildXmlNode($key, $value, $level = 0) { $indent = str_repeat(" ", $level); $xml = ""; if (is_array($value)) { // 如果是数字索引数组,使用 包装 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}\n"; } } $xml .= "{$indent}\n"; } else { // 关联数组 $xml .= "{$indent}<{$key}>\n"; foreach ($value as $subKey => $subValue) { $xml .= $this->buildXmlNode($subKey, $subValue, $level + 1); } $xml .= "{$indent}\n"; } } else { // 简单值 $xml .= "{$indent}<{$key}>{$value}\n"; } return $xml; } private function errorResponse($message, $format = 'json') { switch (strtolower($format)) { case 'xml': $xml = "\n"; $xml .= "false\n"; $xml .= "" . $message . "\n"; $xml .= "" . time() . "\n"; $xml .= ""; return $xml; case 'json': default: return json([ 'success' => false, 'error' => $message, 'timestamp' => time() ]); } } }