GiftCardQrCodeService.php 9.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281
  1. <?php
  2. namespace app\common\service;
  3. use app\common\service\storage\Driver;
  4. use app\common\service\ConfigService;
  5. // 使用BaconQrCode替代SimpleSoftwareIO
  6. use BaconQrCode\Renderer\ImageRenderer;
  7. use BaconQrCode\Renderer\Image\ImagickImageBackEnd;
  8. use BaconQrCode\Renderer\RendererStyle\RendererStyle;
  9. use BaconQrCode\Writer;
  10. use think\facade\Log;
  11. use app\common\service\WeChatConfigService;
  12. use EasyWeChat\Factory;
  13. use BaconQrCode\Renderer\Image\SvgImageBackEnd;
  14. use BaconQrCode\Renderer\Image\EpsImageBackEnd;
  15. /**
  16. * 礼品卡二维码生成服务
  17. */
  18. class GiftCardQrCodeService
  19. {
  20. /**
  21. * @notes 生成礼品卡小程序二维码并上传到七牛云
  22. * @param string $cardNo 礼品卡卡号
  23. * @param string $cardPass 礼品卡密码
  24. * @return string|false 返回二维码文件路径或false
  25. */
  26. public static function generateAndUploadQrCode($cardNo, $cardPass)
  27. {
  28. try {
  29. // Generate regular QR code with cardPass as content
  30. $qrContent = $cardPass;
  31. // Generate local temp file path
  32. $tempDir = runtime_path() . 'temp' . DIRECTORY_SEPARATOR;
  33. if (!is_dir($tempDir)) {
  34. mkdir($tempDir, 0755, true);
  35. }
  36. $tempFileName = 'qrcode_' . $cardNo . '_' . time() . '.png';
  37. $tempFilePath = $tempDir . $tempFileName;
  38. // 在生成部分
  39. $renderer = new ImageRenderer(
  40. new RendererStyle(430, 2),
  41. new ImagickImageBackEnd() // 如果没有Imagick,尝试其他BackEnd
  42. );
  43. $writer = new Writer($renderer);
  44. $qrCodeData = $writer->writeString($qrContent);
  45. // 保存到文件
  46. file_put_contents($tempFilePath, $qrCodeData);
  47. outFileLog($qrCodeData, 'qr_code', '$qrCodeData');
  48. Log::info('Regular QR code generated successfully', [
  49. 'cardNo' => $cardNo,
  50. 'scene' => $cardPass,
  51. 'tempPath' => $tempFilePath,
  52. 'size' => filesize($tempFilePath)
  53. ]);
  54. // Generate Qiniu cloud storage path
  55. $remotePath = 'gift_card_qrcode/' . date('Ymd') . '/' . $tempFileName;
  56. outFileLog($remotePath, 'qr_code', '$remotePath');
  57. // Upload to Qiniu cloud
  58. if (self::uploadToQiniu($tempFilePath, $remotePath)) {
  59. // Delete temp file
  60. // unlink($tempFilePath);
  61. // Return Qiniu cloud file path
  62. $config = ConfigService::get('storage', 'qiniu', []);
  63. $domain = rtrim($config['domain'] ?? '', '/');
  64. $fullUrl = $domain . '/' . $remotePath;
  65. outFileLog($fullUrl, 'qr_code', '$fullUrl');
  66. Log::info('Regular QR code generated and uploaded successfully', [
  67. 'cardNo' => $cardNo,
  68. 'remotePath' => $remotePath,
  69. 'fullUrl' => $fullUrl
  70. ]);
  71. return $fullUrl;
  72. } else {
  73. // Upload failed, delete temp file
  74. if (file_exists($tempFilePath)) {
  75. unlink($tempFilePath);
  76. }
  77. return false;
  78. }
  79. } catch (\Exception $e) {
  80. Log::error('Failed to generate regular QR code', [
  81. 'error' => $e->getMessage(),
  82. 'trace' => $e->getTraceAsString()
  83. ]);
  84. return false;
  85. }
  86. }
  87. public static function httpRequest($url, $data='', $method='GET'){
  88. $curl = curl_init();
  89. curl_setopt($curl, CURLOPT_URL, $url);
  90. curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, 0);
  91. curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, 0);
  92. curl_setopt($curl, CURLOPT_USERAGENT, $_SERVER['HTTP_USER_AGENT'] ?? 'Mozilla/5.0');
  93. curl_setopt($curl, CURLOPT_FOLLOWLOCATION, 1);
  94. curl_setopt($curl, CURLOPT_AUTOREFERER, 1);
  95. if($method=='POST') {
  96. curl_setopt($curl, CURLOPT_POST, 1);
  97. if ($data != '') {
  98. curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
  99. curl_setopt($curl, CURLOPT_HTTPHEADER, [
  100. 'Content-Type: application/json',
  101. 'Content-Length: ' . strlen($data)
  102. ]);
  103. }
  104. }
  105. curl_setopt($curl, CURLOPT_TIMEOUT, 30);
  106. curl_setopt($curl, CURLOPT_HEADER, 0);
  107. curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
  108. $result = curl_exec($curl);
  109. $httpCode = curl_getinfo($curl, CURLINFO_HTTP_CODE);
  110. $error = curl_error($curl);
  111. curl_close($curl);
  112. if ($error) {
  113. Log::error('CURL请求失败', ['error' => $error, 'url' => $url]);
  114. return false;
  115. }
  116. if ($httpCode !== 200) {
  117. Log::error('HTTP请求失败', ['code' => $httpCode, 'url' => $url]);
  118. return false;
  119. }
  120. return $result;
  121. }
  122. /**
  123. * @notes 上传文件到七牛云
  124. * @param string $localPath 本地文件路径
  125. * @param string $remotePath 远程文件路径
  126. * @return bool
  127. */
  128. private static function uploadToQiniu($localPath, $remotePath)
  129. {
  130. try {
  131. // 检查本地文件是否存在
  132. if (!file_exists($localPath)) {
  133. Log::error('本地文件不存在', ['path' => $localPath]);
  134. return false;
  135. }
  136. $config = [
  137. 'default' => ConfigService::get('storage', 'default', 'local'),
  138. 'engine' => ConfigService::get('storage_engine')
  139. ];
  140. Log::info('存储配置', $config);
  141. if ($config['default'] === 'qiniu') {
  142. $storageDriver = new Driver($config);
  143. // 使用绝对路径进行上传
  144. $absolutePath = realpath($localPath);
  145. $result = $storageDriver->fetch($absolutePath, $remotePath);
  146. if (!$result) {
  147. $error = $storageDriver->getError();
  148. Log::error('七牛云上传失败', [
  149. 'error' => $error,
  150. 'localPath' => $absolutePath,
  151. 'remotePath' => $remotePath
  152. ]);
  153. return false;
  154. }
  155. Log::info('七牛云上传成功', [
  156. 'localPath' => $absolutePath,
  157. 'remotePath' => $remotePath
  158. ]);
  159. return true;
  160. } else {
  161. // 如果不是七牛云存储,返回本地路径
  162. Log::info('使用本地存储', ['path' => $localPath]);
  163. return true;
  164. }
  165. } catch (\Exception $e) {
  166. Log::error('上传到七牛云失败', [
  167. 'error' => $e->getMessage(),
  168. 'localPath' => $localPath,
  169. 'remotePath' => $remotePath
  170. ]);
  171. return false;
  172. }
  173. }
  174. /**
  175. * @notes 批量生成二维码
  176. * @param array $giftCards 礼品卡数组
  177. * @return array
  178. */
  179. public static function batchGenerateQrCode($giftCards)
  180. {
  181. $result = [
  182. 'success' => 0,
  183. 'failed' => 0,
  184. 'total' => count($giftCards),
  185. 'details' => []
  186. ];
  187. foreach ($giftCards as $card) {
  188. $qrCodePath = self::generateAndUploadQrCode($card['card_no'], $card['card_pass']);
  189. if ($qrCodePath) {
  190. // 更新数据库中的二维码路径
  191. \app\common\model\GiftCardInfo::where('id', $card['id'])
  192. ->update(['qr_code_path' => $qrCodePath]);
  193. $result['success']++;
  194. $result['details'][] = [
  195. 'card_no' => $card['card_no'],
  196. 'status' => 'success',
  197. 'qr_code_path' => $qrCodePath
  198. ];
  199. } else {
  200. $result['failed']++;
  201. $result['details'][] = [
  202. 'card_no' => $card['card_no'],
  203. 'status' => 'failed',
  204. 'error' => '生成或上传失败'
  205. ];
  206. }
  207. }
  208. return $result;
  209. }
  210. }
  211. // 生成SVG格式然后转换为PNG
  212. $renderer = new ImageRenderer(
  213. new RendererStyle(430, 2),
  214. new SvgImageBackEnd()
  215. );
  216. $writer = new Writer($renderer);
  217. $svgString = $writer->writeString($qrContent);
  218. // 如果需要PNG格式,可以使用其他方法转换
  219. // 或者直接保存SVG格式
  220. file_put_contents($tempFilePath, $svgString);
  221. // 清理文件末尾的重复代码(删除第235-256行)
  222. // 在生成部分添加扩展检查
  223. try {
  224. // 检查Imagick扩展
  225. if (!extension_loaded('imagick')) {
  226. throw new \Exception('Imagick扩展未安装,无法生成二维码');
  227. }
  228. $renderer = new ImageRenderer(
  229. new RendererStyle(430, 2),
  230. new ImagickImageBackEnd()
  231. );
  232. $writer = new Writer($renderer);
  233. $qrCodeData = $writer->writeString($qrContent);
  234. file_put_contents($tempFilePath, $qrCodeData);
  235. // 移除调试代码
  236. // outFileLog($qrCodeData, 'qr_code', '$qrCodeData');
  237. } catch (\Exception $e) {
  238. Log::error('二维码生成失败', ['error' => $e->getMessage()]);
  239. return false;
  240. }