unknown 1 месяц назад
Родитель
Сommit
17815869ea
2 измененных файлов с 21 добавлено и 206 удалено
  1. 21 19
      application/api/controller/ProductController.php
  2. 0 187
      application/service/AIGatewayService.php

+ 21 - 19
application/api/controller/ProductController.php

@@ -90,7 +90,7 @@ class ProductController extends Controller
 
 
    
    
     /**
     /**
-     * 添加产品接口(示例)
+     * 添加产品接口
      * POST /api/product/productAdd
      * POST /api/product/productAdd
      * 
      * 
      * @return \think\response\Json
      * @return \think\response\Json
@@ -108,24 +108,25 @@ class ProductController extends Controller
 
 
         $productImgPath = '';
         $productImgPath = '';
         if (!empty($data['image'])) {
         if (!empty($data['image'])) {
-            $base64Data = $data['image'];
-            if (preg_match('/data:image\/(png|jpg|jpeg);base64,([A-Za-z0-9+\/=]+)/i', $base64Data, $m)) {
-                $imageType = strtolower($m[1]);
-                $imageData = base64_decode($m[2]);
-                if ($imageData !== false && strlen($imageData) >= 100) {
-                    $productCode = $data['code'];
-                    $prefix = strlen($productCode) >= 4 ? substr($productCode, 0, -4) : $productCode;
-                    $safeName = preg_replace('/[\\\\\/:*?"<>|]/u', '_', $data['name']);
-                    $ext = ($imageType === 'jpeg') ? 'jpg' : $imageType;
-                    $fileName = $safeName . '.' . $ext;
-                    $saveDir = str_replace('\\', '/', ROOT_PATH . 'public/uploads/merchant/' . $prefix . '/' . $productCode . '/oldimg/');
-                    if (!is_dir($saveDir)) {
-                        mkdir($saveDir, 0755, true);
-                    }
-                    if (file_put_contents($saveDir . $fileName, $imageData)) {
-                        $productImgPath = 'uploads/merchant/' . $prefix . '/' . $productCode . '/oldimg/' . $fileName;
-                        Common::uploadLocalFileToOss($saveDir . $fileName, $productImgPath);
-                    }
+            $sourcePath = $data['image'];
+            $sourceFullPath = ROOT_PATH . 'public/' . ltrim($sourcePath, '/');
+            
+            if (is_file($sourceFullPath)) {
+                $productCode = $data['code'];
+                $prefix = strlen($productCode) >= 4 ? substr($productCode, 0, -4) : $productCode;
+                $safeName = preg_replace('/[\\\\\/:*?"<>|]/u', '_', $data['name']);
+                $ext = pathinfo($sourceFullPath, PATHINFO_EXTENSION);
+                $fileName = $safeName . '.' . $ext;
+                $saveDir = str_replace('\\', '/', ROOT_PATH . 'public/uploads/merchant/' . $prefix . '/' . $productCode . '/oldimg/');
+                
+                if (!is_dir($saveDir)) {
+                    mkdir($saveDir, 0755, true);
+                }
+                
+                $targetFullPath = $saveDir . $fileName;
+                if (rename($sourceFullPath, $targetFullPath)) {
+                    $productImgPath = 'uploads/merchant/' . $prefix . '/' . $productCode . '/oldimg/' . $fileName;
+                    Common::uploadLocalFileToOss($targetFullPath, $productImgPath);
                 }
                 }
             }
             }
         }
         }
@@ -133,6 +134,7 @@ class ProductController extends Controller
         $res = [
         $res = [
             'product_name' => $data['name'],
             'product_name' => $data['name'],
             'product_code' => $data['code'],
             'product_code' => $data['code'],
+            'merchant_id' => strlen($productCode) >= 4 ? substr($productCode, 0, -4) : $productCode,
             'product_img' => $productImgPath,
             'product_img' => $productImgPath,
             'createTime' => date('Y-m-d H:i:s'),
             'createTime' => date('Y-m-d H:i:s'),
             'create_name' => '系统摄像头',
             'create_name' => '系统摄像头',

+ 0 - 187
application/service/AIGatewayService.php

@@ -539,193 +539,6 @@ class AIGatewayService{
         return '1. 等待几分钟后重试 2. 检查API服务提供商状态 3. 联系服务提供商确认服务可用性';
         return '1. 等待几分钟后重试 2. 检查API服务提供商状态 3. 联系服务提供商确认服务可用性';
     }
     }
 
 
-//    /**
-//     * 通用 API 调用方法(支持重试机制)
-//     *
-//     * @param string $url     接口地址
-//     * @param string $apiKey  授权密钥(Bearer Token)
-//     * @param array  $data    请求数据(JSON 格式)
-//     *
-//     * 功能说明:
-//     * - 使用 cURL 发送 POST 请求到指定 API 接口
-//     * - 设置请求头和超时时间等参数
-//     * - 支持最多重试 2 次,当接口调用失败时自动重试
-//     * - 返回成功时解析 JSON 响应为数组
-//     *
-//     * 异常处理:
-//     * - 若全部重试失败,将抛出异常并包含最后一次错误信息
-//     *
-//     * @return array 接口响应数据(成功时返回解析后的数组)
-//     * @throws \Exception 接口请求失败时抛出异常
-//     */
-//    public static function callApi($data,$model,$timeout = 60)
-//    {
-//        $maxRetries = 0;  // 减少重试次数为0,避免不必要的等待
-//        $attempt = 0;
-//        $lastError = '';
-//        $httpCode = 0;
-//        $apiErrorDetail = '';
-//
-//        $ai_model = Db::name("ai_model")
-//            ->where('model_name',$model)
-//            ->select();
-//        $num = 0;
-//        while ($attempt <= $maxRetries) {
-//            try {
-//                if(!$ai_model[$num]){
-//                    throw new \Exception("请求发送失败: " . $curlError);
-//                }
-//                $ch = curl_init();
-//                curl_setopt_array($ch, [
-//                    CURLOPT_URL => $ai_model[$num]['api_url'],
-//                    CURLOPT_RETURNTRANSFER => true,
-//                    CURLOPT_POST => true,
-//                    CURLOPT_POSTFIELDS => json_encode($data, JSON_UNESCAPED_UNICODE),
-//                    CURLOPT_HTTPHEADER => [
-//                        'Content-Type: application/json',
-//                        'Authorization: Bearer ' . $ai_model[$num]['api_key']
-//                    ],
-//                    CURLOPT_TIMEOUT => (int) $timeout,
-//                    CURLOPT_SSL_VERIFYPEER => false,
-//                    CURLOPT_SSL_VERIFYHOST => false,
-//                    CURLOPT_CONNECTTIMEOUT => 15,  // 减少连接超时时间为15秒
-//                    CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
-//                    CURLOPT_FAILONERROR => false
-//                ]);
-//
-//                $response = curl_exec($ch);
-//                $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
-//                $curlError = curl_error($ch);
-//
-//                if ($response === false) {
-//                    // 尝试从curl错误信息中提取HTTP状态码
-//                    if (preg_match('/HTTP\/[0-9.]+\s+([0-9]+)/', $curlError, $matches)) {
-//                        $httpCode = (int)$matches[1];
-//                    }
-//                    throw new \Exception("请求发送失败: " . $curlError);
-//                }
-//
-//                $result = json_decode($response, true);
-//
-//                // 检查API返回的错误
-//                if (isset($result['error'])) {
-//                    $apiErrorDetail = $result['error']['message'] ?? '';
-//                    $errorType = $result['error']['type'] ?? '';
-//                    $errorCode = $result['error']['code'] ?? '';
-//
-//                    // 常见错误类型映射
-//                    $errorMessages = [
-//                        'invalid_request_error' => '请求参数错误',
-//                        'authentication_error' => '认证失败',
-//                        'rate_limit_error' => '请求频率过高',
-//                        'insufficient_quota' => '额度不足',
-//                        'billing_not_active' => '账户未开通付费',
-//                        'content_policy_violation' => '内容违反政策',
-//                        'model_not_found' => '模型不存在或无可用渠道'
-//                    ];
-//
-//                    // 优先使用errorCode进行映射,如果没有则使用errorType
-//                    $friendlyMessage = $errorMessages[$errorCode] ?? ($errorMessages[$errorType] ?? 'API服务错误');
-//
-//                    // 构建详细的错误信息,包含错误代码、类型和详细描述
-//                    $detailedError = "{$friendlyMessage}";
-//                    if ($errorCode) {
-//                        $detailedError .= " (错误代码: {$errorCode})";
-//                    }
-//                    if ($apiErrorDetail) {
-//                        $detailedError .= ": {$apiErrorDetail}";
-//                    }
-//
-//                    throw new \Exception($detailedError);
-//                }
-//
-//                if ($httpCode !== 200) {
-//                    // HTTP状态码映射
-//                    $statusMessages = [
-//                        400 => '请求参数不合法',
-//                        401 => 'API密钥无效或权限不足',
-//                        403 => '访问被拒绝',
-//                        404 => 'API端点不存在',
-//                        429 => '请求过于频繁,请稍后再试',
-//                        500 => '服务器内部错误',
-//                        503 => '服务暂时不可用'
-//                    ];
-//
-//                    $statusMessage = $statusMessages[$httpCode] ?? "HTTP错误({$httpCode})";
-//                    throw new \Exception($statusMessage);
-//                }
-//
-//                curl_close($ch);
-//                return $result;
-//
-//            } catch (\Exception $e) {
-//                $lastError = $e->getMessage();
-//                $attempt++;
-//                $num++;
-//                if ($attempt <= $maxRetries) {
-//                    sleep(pow(2, $attempt));
-//                } else {
-//                    // 最终失败时的详细错误信息
-//                    $errorDetails = [
-//                        '错误原因' => self::getErrorCause($httpCode, $apiErrorDetail),
-//                        '解决方案' => self::getErrorSolution($httpCode),
-//                        '请求参数' => json_encode($data, JSON_UNESCAPED_UNICODE),
-//                        'HTTP状态码' => $httpCode,
-//                        '重试次数' => $attempt
-//                    ];
-//
-//                    // 构建最终的错误信息,优先显示原始的详细错误消息
-//                    $finalError = "API请求失败\n";
-//                    $finalError .= "失败说明: " . $lastError . "\n"; // 使用原始的详细错误消息
-//                    $finalError .= "建议解决方案: " . $errorDetails['解决方案'] . "\n";
-//                    $finalError .= "技术详情: HTTP {$httpCode} - " . $errorDetails['错误原因'];
-//
-//                    throw new \Exception($finalError);
-//                }
-//            }
-//        }
-//    }
-//
-//    private static function getErrorCause($httpCode, $apiErrorDetail)
-//    {
-//        $causeMap = [
-//            400 => '参数格式错误/必填参数缺失',
-//            401 => 'API Key无效/过期/无权限',
-//            429 => '超出接口调用频率限制',
-//            500 => '服务端内部故障',
-//            503 => '服务维护/算力不足',
-//            'model_not_found' => '模型渠道未开通/无可用资源',
-//            'invalid_size' => '模型尺寸参数不符合要求',
-//            CURLE_OPERATION_TIMEDOUT => '请求超时(模型处理耗时超过设置值)'
-//        ];
-//
-//        if (strpos($apiErrorDetail, 'No available capacity') !== false) {
-//            return '模型算力不足,无可用资源';
-//        } elseif (strpos($apiErrorDetail, 'size is invalid') !== false) {
-//            return '模型尺寸参数无效';
-//        } elseif (isset($causeMap[$httpCode])) {
-//            return $causeMap[$httpCode];
-//        }
-//        return $apiErrorDetail ?: '未知原因';
-//    }
-//
-//    private static function getErrorSolution($httpCode)
-//    {
-//        $solutionMap = [
-//            400 => '1. 检查参数是否完整 2. 确认参数类型(如seconds为字符串) 3. 验证尺寸/模型名是否合法',
-//            401 => '1. 检查API Key是否正确 2. 确认Key未过期/有对应模型权限',
-//            429 => '1. 降低请求频率 2. 等待1-5分钟后重试',
-//            500 => '1. 等待几分钟后重试 2. 联系API服务商排查',
-//            503 => '1. 等待算力释放 2. 联系服务商扩容',
-//            CURLE_OPERATION_TIMEDOUT => '1. 延长超时时间 2. 检查模型生成耗时 3. 重试请求'
-//        ];
-//
-//        if (isset($solutionMap[$httpCode])) {
-//            return $solutionMap[$httpCode];
-//        }
-//        return '1. 等待几分钟后重试 2. 检查API服务提供商状态 3. 联系服务提供商确认服务可用性';
-//    }
-
     /**
     /**
      * 获取图片的base64数据和MIME类型
      * 获取图片的base64数据和MIME类型
      * @return array 包含base64数据和MIME类型的数组
      * @return array 包含base64数据和MIME类型的数组