GiftCardQrCodeService.php 9.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265
  1. <?php
  2. namespace app\common\service;
  3. use app\common\service\storage\Driver;
  4. use app\common\service\ConfigService;
  5. use app\common\service\WeChatConfigService;
  6. use EasyWeChat\Factory;
  7. use think\facade\Log;
  8. /**
  9. * 礼品卡二维码生成服务
  10. */
  11. class GiftCardQrCodeService
  12. {
  13. /**
  14. * @notes 生成礼品卡小程序二维码并上传到七牛云
  15. * @param string $cardNo 礼品卡卡号
  16. * @param string $cardPass 礼品卡密码
  17. * @return string|false 返回二维码文件路径或false
  18. */
  19. public static function generateAndUploadQrCode($cardNo, $cardPass)
  20. {
  21. try {
  22. // 小程序页面路径(使用首页,通过场景值处理)
  23. $page = 'pages/card-exchange/card-exchange?cardPass='.$cardPass;
  24. // 优化场景值格式,确保不超过32字符限制
  25. $scene = $cardNo . '_' . $cardPass;
  26. // 如果场景值超过32字符,使用base64编码压缩
  27. if (strlen($scene) > 32) {
  28. $scene = $cardPass;
  29. $scene = base64_encode($cardNo . '|' . $cardPass);
  30. if (strlen($scene) > 32) {
  31. $scene = substr($scene, 0, 32);
  32. }
  33. }
  34. // 生成小程序码
  35. $config = WeChatConfigService::getMnpConfig();
  36. $app = Factory::miniProgram($config);
  37. $accessToken = $app->access_token->getToken()['access_token'];
  38. outFileLog($accessToken,'qr_code','$accessToken');
  39. $url = "https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token={$accessToken}";
  40. $data = [
  41. 'scene' => $scene,
  42. 'page' => $page,
  43. 'width' => 280,
  44. 'auto_color' => false,
  45. 'line_color' => ['r' => 0, 'g' => 0, 'b' => 0],
  46. 'is_hyaline' => false
  47. ];
  48. Log::info('生成小程序码参数', [
  49. 'scene' => $scene,
  50. 'scene_length' => strlen($scene),
  51. 'page' => $page,
  52. 'cardPass' => $cardPass,
  53. ]);
  54. $ch = curl_init();
  55. curl_setopt($ch, CURLOPT_URL, $url);
  56. curl_setopt($ch, CURLOPT_POST, true);
  57. curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data));
  58. curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
  59. curl_setopt($ch, CURLOPT_HTTPHEADER, [
  60. 'Content-Type: application/json; charset=utf-8'
  61. ]);
  62. curl_setopt($ch, CURLOPT_BINARYTRANSFER, true);
  63. $response = curl_exec($ch);
  64. outFileLog($response,'qr_code','$response');
  65. $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
  66. curl_close($ch);
  67. outFileLog($httpCode,'qr_code','$httpCode');
  68. if ($httpCode === 200) {
  69. // 检查是否为JSON错误响应
  70. $jsonData = json_decode($response, true);
  71. outFileLog($jsonData,'qr_code','$jsonData');
  72. if ($jsonData && isset($jsonData['errcode'])) {
  73. Log::error('微信API错误', $jsonData);
  74. return false;
  75. }
  76. // 创建保存目录
  77. $saveDir = 'resource/image/gift_card/qr_code/';
  78. if (!is_dir($saveDir)) {
  79. mkdir($saveDir, 0755, true);
  80. }
  81. $fileName = 'gift_card_' . $cardNo . '_' . time() . '.png';
  82. $localPath = $saveDir . $fileName;
  83. // 保存二进制数据到本地
  84. $result = file_put_contents($localPath, $response);
  85. if ($result === false) {
  86. Log::error('保存二维码文件失败', ['path' => $localPath]);
  87. return false;
  88. }
  89. // 验证文件是否为有效的PNG图片
  90. $imageInfo = getimagesize($localPath);
  91. if ($imageInfo === false || $imageInfo['mime'] !== 'image/png') {
  92. Log::error('生成的文件不是有效的PNG图片', [
  93. 'path' => $localPath,
  94. 'imageInfo' => $imageInfo
  95. ]);
  96. if (file_exists($localPath)) {
  97. unlink($localPath);
  98. }
  99. return false;
  100. }
  101. Log::info('二维码文件保存成功', [
  102. 'localPath' => $localPath,
  103. 'fileSize' => filesize($localPath)
  104. ]);
  105. // 上传到七牛云
  106. $remotePath = 'gift_card/qr_code/' . $fileName;
  107. outFileLog($remotePath,'qr_code','$remotePath');
  108. $uploadResult = self::uploadToQiniu($localPath, $remotePath);
  109. outFileLog($uploadResult,'qr_code','$uploadResult');
  110. if ($uploadResult) {
  111. Log::info('二维码上传七牛云成功', [
  112. 'localPath' => $localPath,
  113. 'remotePath' => $remotePath
  114. ]);
  115. // 删除本地临时文件
  116. if (file_exists($localPath)) {
  117. unlink($localPath);
  118. }
  119. return $remotePath;
  120. } else {
  121. Log::error('上传到七牛云失败', [
  122. 'localPath' => $localPath,
  123. 'remotePath' => $remotePath
  124. ]);
  125. // 保留本地文件作为备份
  126. return false;
  127. }
  128. } else {
  129. Log::error('HTTP请求失败', [
  130. 'code' => $httpCode,
  131. 'response' => substr($response, 0, 500)
  132. ]);
  133. return false;
  134. }
  135. } catch (\Exception $e) {
  136. Log::error('生成礼品卡二维码失败', [
  137. 'error' => $e->getMessage(),
  138. 'trace' => $e->getTraceAsString()
  139. ]);
  140. return false;
  141. }
  142. }
  143. /**
  144. * @notes 上传文件到七牛云
  145. * @param string $localPath 本地文件路径
  146. * @param string $remotePath 远程文件路径
  147. * @return bool
  148. */
  149. private static function uploadToQiniu($localPath, $remotePath)
  150. {
  151. try {
  152. // 检查本地文件是否存在
  153. if (!file_exists($localPath)) {
  154. Log::error('本地文件不存在', ['path' => $localPath]);
  155. return false;
  156. }
  157. $config = [
  158. 'default' => ConfigService::get('storage', 'default', 'local'),
  159. 'engine' => ConfigService::get('storage_engine')
  160. ];
  161. Log::info('存储配置', $config);
  162. if ($config['default'] === 'qiniu') {
  163. $storageDriver = new Driver($config);
  164. // 使用绝对路径进行上传
  165. $absolutePath = realpath($localPath);
  166. $result = $storageDriver->fetch($absolutePath, $remotePath);
  167. if (!$result) {
  168. $error = $storageDriver->getError();
  169. Log::error('七牛云上传失败', [
  170. 'error' => $error,
  171. 'localPath' => $absolutePath,
  172. 'remotePath' => $remotePath
  173. ]);
  174. return false;
  175. }
  176. Log::info('七牛云上传成功', [
  177. 'localPath' => $absolutePath,
  178. 'remotePath' => $remotePath
  179. ]);
  180. return true;
  181. } else {
  182. // 如果不是七牛云存储,返回本地路径
  183. Log::info('使用本地存储', ['path' => $localPath]);
  184. return true;
  185. }
  186. } catch (\Exception $e) {
  187. Log::error('上传到七牛云失败', [
  188. 'error' => $e->getMessage(),
  189. 'localPath' => $localPath,
  190. 'remotePath' => $remotePath
  191. ]);
  192. return false;
  193. }
  194. }
  195. /**
  196. * @notes 批量生成二维码
  197. * @param array $giftCards 礼品卡数组
  198. * @return array
  199. */
  200. public static function batchGenerateQrCode($giftCards)
  201. {
  202. $result = [
  203. 'success' => 0,
  204. 'failed' => 0,
  205. 'total' => count($giftCards),
  206. 'details' => []
  207. ];
  208. foreach ($giftCards as $card) {
  209. $qrCodePath = self::generateAndUploadQrCode($card['card_no'], $card['card_pass']);
  210. if ($qrCodePath) {
  211. // 更新数据库中的二维码路径
  212. \app\common\model\GiftCardInfo::where('id', $card['id'])
  213. ->update(['qr_code_path' => $qrCodePath]);
  214. $result['success']++;
  215. $result['details'][] = [
  216. 'card_no' => $card['card_no'],
  217. 'status' => 'success',
  218. 'qr_code_path' => $qrCodePath
  219. ];
  220. } else {
  221. $result['failed']++;
  222. $result['details'][] = [
  223. 'card_no' => $card['card_no'],
  224. 'status' => 'failed',
  225. 'error' => '生成或上传失败'
  226. ];
  227. }
  228. }
  229. return $result;
  230. }
  231. }