moonsflyer 6 месяцев назад
Родитель
Сommit
bd0a03f4e3
1 измененных файлов с 130 добавлено и 90 удалено
  1. 130 90
      app/common/service/GiftCardQrCodeService.php

+ 130 - 90
app/common/service/GiftCardQrCodeService.php

@@ -22,13 +22,23 @@ class GiftCardQrCodeService
     public static function generateAndUploadQrCode($cardNo, $cardPass)
     {
         try {
-            // 小程序页面路径,根据实际情况修改
+            // 小程序页面路径(使用首页,通过场景值处理)
             $page = 'pages/index/index';
-            $scene = "cardPass={$cardPass}";
+
+            // 优化场景值格式,确保不超过32字符限制
+            $scene = $cardNo . '_' . $cardPass;
+
+            // 如果场景值超过32字符,使用base64编码压缩
+            if (strlen($scene) > 32) {
+                $scene = $cardPass;
+                $scene = base64_encode($cardNo . '|' . $cardPass);
+                if (strlen($scene) > 32) {
+                    $scene = substr($scene, 0, 32);
+                }
+            }
 
             // 生成小程序码
             $config = WeChatConfigService::getMnpConfig();
-
             $app = Factory::miniProgram($config);
             $accessToken = $app->access_token->getToken()['access_token'];
 
@@ -38,8 +48,18 @@ class GiftCardQrCodeService
                 'scene' => $scene,
                 'page' => $page,
                 'width' => 280,
+                'auto_color' => false,
+                'line_color' => ['r' => 0, 'g' => 0, 'b' => 0],
+                'is_hyaline' => false
             ];
 
+            Log::info('生成小程序码参数', [
+                'scene' => $scene,
+                'scene_length' => strlen($scene),
+                'page' => $page,
+                'cardNo' => $cardNo
+            ]);
+
             $ch = curl_init();
             curl_setopt($ch, CURLOPT_URL, $url);
             curl_setopt($ch, CURLOPT_POST, true);
@@ -48,116 +68,92 @@ class GiftCardQrCodeService
             curl_setopt($ch, CURLOPT_HTTPHEADER, [
                 'Content-Type: application/json; charset=utf-8'
             ]);
-            // 重要:设置二进制传输模式
             curl_setopt($ch, CURLOPT_BINARYTRANSFER, true);
 
             $response = curl_exec($ch);
             $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
             curl_close($ch);
-
+            return $httpCode;
             if ($httpCode === 200) {
                 // 检查是否为JSON错误响应
                 $jsonData = json_decode($response, true);
-                return $jsonData;
                 if ($jsonData && isset($jsonData['errcode'])) {
                     Log::error('微信API错误', $jsonData);
                     return false;
                 }
 
-                // 保存二进制图片数据
+                // 创建保存目录
                 $saveDir = 'resource/image/gift_card/qr_code/';
-                if (!file_exists($saveDir)) {
-                    mkdir($saveDir, 0777, true);
+                if (!is_dir($saveDir)) {
+                    mkdir($saveDir, 0755, true);
                 }
 
                 $fileName = 'gift_card_' . $cardNo . '_' . time() . '.png';
                 $localPath = $saveDir . $fileName;
 
-                // 直接写入二进制数据
-                file_put_contents($localPath, $response);
-
-            } else {
-                Log::error('HTTP请求失败', ['code' => $httpCode]);
-                return false;
-            }
+                // 保存二进制数据到本地
+                $result = file_put_contents($localPath, $response);
 
+                if ($result === false) {
+                    Log::error('保存二维码文件失败', ['path' => $localPath]);
+                    return false;
+                }
 
-            $IMG = getQrCode($accessToken, $page.$scene, 'uploads/qrcode/', $cardPass);
-
-//            $result = $app->app_code->getUnlimited($page = 'pages/index/index', $width = 430);
-//            try {
-//                $accessToken = $app->access_token->getToken()['access_token'];
-//                $url = "https://api.weixin.qq.com/cgi-bin/wxaapp/createwxaqrcode?access_token={$accessToken}";
-//
-//                $data = [
-//                    'path' => $page . '?' . $scene,
-//                    'width' => 280
-//                ];
-//
-//                // 使用Guzzle HTTP客户端
-//                $client = new \GuzzleHttp\Client();
-//                $response = $client->post($url, [
-//                    'json' => $data,
-//                    'headers' => [
-//                        'Content-Type' => 'application/json'
-//                    ]
-//                ]);
-//                return $response;
-//                // 检查响应
-//                if ($response->getStatusCode() === 200) {
-//                    $body = $response->getBody();
-//                    // 这里$body就是二维码的二进制数据
-//                } else {
-//                    Log::error('微信API调用失败', ['status' => $response->getStatusCode()]);
-//                    return false;
-//                }
-//
-//            } catch (\Exception $e2) {
-//                Log::error('HTTP客户端调用失败', ['error' => $e2->getMessage()]);
-//                return false;
-//            }
-//
-//            if (!($response instanceof \EasyWeChat\Kernel\Http\StreamResponse)) {
-//                Log::error('生成小程序码失败', [
-//                    'response' => $response,
-//                    'response_type' => gettype($response),
-//                    'page' => $page,
-//                    'scene' => $scene
-//                ]);
-//                return false;
-//            }
-//            if (!($response instanceof \EasyWeChat\Kernel\Http\StreamResponse)) {
-//                Log::error('生成小程序码失败', ['response' => $response]);
-//                return false;
-//            }
-            return $IMG;
-            // 保存到本地临时目录
-            $saveDir = 'resource/image/gift_card/qr_code/';
-            if (!file_exists($saveDir)) {
-                mkdir($saveDir, 0777, true);
-            }
+                // 验证文件是否为有效的PNG图片
+                $imageInfo = getimagesize($localPath);
+                if ($imageInfo === false || $imageInfo['mime'] !== 'image/png') {
+                    Log::error('生成的文件不是有效的PNG图片', [
+                        'path' => $localPath,
+                        'imageInfo' => $imageInfo
+                    ]);
+                    if (file_exists($localPath)) {
+                        unlink($localPath);
+                    }
+                    return false;
+                }
 
-            $fileName = 'gift_card_' . $cardNo . '_' . time() . '.png';
-            $localPath = $saveDir . $fileName;
+                Log::info('二维码文件保存成功', [
+                    'localPath' => $localPath,
+                    'fileSize' => filesize($localPath)
+                ]);
 
-            // 保存小程序码到本地
-            $response->saveAs($saveDir, $fileName);
+                // 上传到七牛云
+                $remotePath = 'gift_card/qr_code/' . $fileName;
+                $uploadResult = self::uploadToQiniu($localPath, $remotePath);
 
-            // 上传到七牛云
-            $uploadPath = self::uploadToQiniu($localPath, 'gift_card/qr_code/' . $fileName);
+                if ($uploadResult) {
+                    Log::info('二维码上传七牛云成功', [
+                        'localPath' => $localPath,
+                        'remotePath' => $remotePath
+                    ]);
 
-            if ($uploadPath) {
-                // 删除本地临时文件
-                if (file_exists($localPath)) {
-                    unlink($localPath);
+                    // 删除本地临时文件
+                    if (file_exists($localPath)) {
+                        unlink($localPath);
+                    }
+                    return $remotePath;
+                } else {
+                    Log::error('上传到七牛云失败', [
+                        'localPath' => $localPath,
+                        'remotePath' => $remotePath
+                    ]);
+                    // 保留本地文件作为备份
+                    return false;
                 }
-                return 'gift_card/qr_code/' . $fileName;
-            }
 
-            return false;
+            } else {
+                Log::error('HTTP请求失败', [
+                    'code' => $httpCode,
+                    'response' => substr($response, 0, 500)
+                ]);
+                return false;
+            }
 
         } catch (\Exception $e) {
-            Log::error('生成礼品卡二维码失败', ['error' => $e->getMessage()]);
+            Log::error('生成礼品卡二维码失败', [
+                'error' => $e->getMessage(),
+                'trace' => $e->getTraceAsString()
+            ]);
             return false;
         }
     }
@@ -171,21 +167,54 @@ class GiftCardQrCodeService
     private static function uploadToQiniu($localPath, $remotePath)
     {
         try {
+            // 检查本地文件是否存在
+            if (!file_exists($localPath)) {
+                Log::error('本地文件不存在', ['path' => $localPath]);
+                return false;
+            }
+
             $config = [
                 'default' => ConfigService::get('storage', 'default', 'local'),
                 'engine' => ConfigService::get('storage_engine')
             ];
 
+            Log::info('存储配置', $config);
+
             if ($config['default'] === 'qiniu') {
                 $storageDriver = new Driver($config);
-                return $storageDriver->fetch($localPath, $remotePath);
-            }
 
-            // 如果不是七牛云存储,返回本地路径
-            return true;
+                // 使用绝对路径进行上传
+                $absolutePath = realpath($localPath);
+                $result = $storageDriver->fetch($absolutePath, $remotePath);
+
+                if (!$result) {
+                    $error = $storageDriver->getError();
+                    Log::error('七牛云上传失败', [
+                        'error' => $error,
+                        'localPath' => $absolutePath,
+                        'remotePath' => $remotePath
+                    ]);
+                    return false;
+                }
+
+                Log::info('七牛云上传成功', [
+                    'localPath' => $absolutePath,
+                    'remotePath' => $remotePath
+                ]);
+
+                return true;
+            } else {
+                // 如果不是七牛云存储,返回本地路径
+                Log::info('使用本地存储', ['path' => $localPath]);
+                return true;
+            }
 
         } catch (\Exception $e) {
-            Log::error('上传到七牛云失败', ['error' => $e->getMessage()]);
+            Log::error('上传到七牛云失败', [
+                'error' => $e->getMessage(),
+                'localPath' => $localPath,
+                'remotePath' => $remotePath
+            ]);
             return false;
         }
     }
@@ -200,7 +229,8 @@ class GiftCardQrCodeService
         $result = [
             'success' => 0,
             'failed' => 0,
-            'total' => count($giftCards)
+            'total' => count($giftCards),
+            'details' => []
         ];
 
         foreach ($giftCards as $card) {
@@ -211,8 +241,18 @@ class GiftCardQrCodeService
                 \app\common\model\GiftCardInfo::where('id', $card['id'])
                     ->update(['qr_code_path' => $qrCodePath]);
                 $result['success']++;
+                $result['details'][] = [
+                    'card_no' => $card['card_no'],
+                    'status' => 'success',
+                    'qr_code_path' => $qrCodePath
+                ];
             } else {
                 $result['failed']++;
+                $result['details'][] = [
+                    'card_no' => $card['card_no'],
+                    'status' => 'failed',
+                    'error' => '生成或上传失败'
+                ];
             }
         }