| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265 |
- <?php
- namespace app\common\service;
- use app\common\service\storage\Driver;
- use app\common\service\ConfigService;
- use app\common\service\WeChatConfigService;
- use EasyWeChat\Factory;
- use think\facade\Log;
- /**
- * 礼品卡二维码生成服务
- */
- class GiftCardQrCodeService
- {
- /**
- * @notes 生成礼品卡小程序二维码并上传到七牛云
- * @param string $cardNo 礼品卡卡号
- * @param string $cardPass 礼品卡密码
- * @return string|false 返回二维码文件路径或false
- */
- public static function generateAndUploadQrCode($cardNo, $cardPass)
- {
- try {
- // 小程序页面路径(使用首页,通过场景值处理)
- $page = 'pages/card-exchange/card-exchange?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'];
- outFileLog($accessToken,'qr_code','$accessToken');
- $url = "https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token={$accessToken}";
- $data = [
- '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,
- 'cardPass' => $cardPass,
- ]);
- $ch = curl_init();
- curl_setopt($ch, CURLOPT_URL, $url);
- curl_setopt($ch, CURLOPT_POST, true);
- curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data));
- curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
- curl_setopt($ch, CURLOPT_HTTPHEADER, [
- 'Content-Type: application/json; charset=utf-8'
- ]);
- curl_setopt($ch, CURLOPT_BINARYTRANSFER, true);
- $response = curl_exec($ch);
- outFileLog($response,'qr_code','$response');
- $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
- curl_close($ch);
- outFileLog($httpCode,'qr_code','$httpCode');
- if ($httpCode === 200) {
- // 检查是否为JSON错误响应
- $jsonData = json_decode($response, true);
- outFileLog($jsonData,'qr_code','$jsonData');
- if ($jsonData && isset($jsonData['errcode'])) {
- Log::error('微信API错误', $jsonData);
- return false;
- }
- // 创建保存目录
- $saveDir = 'resource/image/gift_card/qr_code/';
- if (!is_dir($saveDir)) {
- mkdir($saveDir, 0755, true);
- }
- $fileName = 'gift_card_' . $cardNo . '_' . time() . '.png';
- $localPath = $saveDir . $fileName;
- // 保存二进制数据到本地
- $result = file_put_contents($localPath, $response);
- if ($result === false) {
- Log::error('保存二维码文件失败', ['path' => $localPath]);
- return false;
- }
- // 验证文件是否为有效的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;
- }
- Log::info('二维码文件保存成功', [
- 'localPath' => $localPath,
- 'fileSize' => filesize($localPath)
- ]);
- // 上传到七牛云
- $remotePath = 'gift_card/qr_code/' . $fileName;
- outFileLog($remotePath,'qr_code','$remotePath');
- $uploadResult = self::uploadToQiniu($localPath, $remotePath);
- outFileLog($uploadResult,'qr_code','$uploadResult');
- if ($uploadResult) {
- Log::info('二维码上传七牛云成功', [
- 'localPath' => $localPath,
- 'remotePath' => $remotePath
- ]);
- // 删除本地临时文件
- if (file_exists($localPath)) {
- unlink($localPath);
- }
- return $remotePath;
- } else {
- Log::error('上传到七牛云失败', [
- 'localPath' => $localPath,
- 'remotePath' => $remotePath
- ]);
- // 保留本地文件作为备份
- return false;
- }
- } else {
- Log::error('HTTP请求失败', [
- 'code' => $httpCode,
- 'response' => substr($response, 0, 500)
- ]);
- return false;
- }
- } catch (\Exception $e) {
- Log::error('生成礼品卡二维码失败', [
- 'error' => $e->getMessage(),
- 'trace' => $e->getTraceAsString()
- ]);
- return false;
- }
- }
- /**
- * @notes 上传文件到七牛云
- * @param string $localPath 本地文件路径
- * @param string $remotePath 远程文件路径
- * @return bool
- */
- 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);
- // 使用绝对路径进行上传
- $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(),
- 'localPath' => $localPath,
- 'remotePath' => $remotePath
- ]);
- return false;
- }
- }
- /**
- * @notes 批量生成二维码
- * @param array $giftCards 礼品卡数组
- * @return array
- */
- public static function batchGenerateQrCode($giftCards)
- {
- $result = [
- 'success' => 0,
- 'failed' => 0,
- 'total' => count($giftCards),
- 'details' => []
- ];
- foreach ($giftCards as $card) {
- $qrCodePath = self::generateAndUploadQrCode($card['card_no'], $card['card_pass']);
- if ($qrCodePath) {
- // 更新数据库中的二维码路径
- \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' => '生成或上传失败'
- ];
- }
- }
- return $result;
- }
- }
|