GiftCardQrCodeService.php 9.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276
  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';
  24. // 优化场景值格式,确保不超过32字符限制
  25. $scene = $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. // 调用微信接口获取二维码图片Buffer
  55. $response = self::httpRequest($url, json_encode($data), 'POST');
  56. // 检查响应是否为图片数据
  57. if (empty($response)) {
  58. Log::error('微信接口返回空响应');
  59. return false;
  60. }
  61. // 检查是否返回错误信息(JSON格式)
  62. $jsonData = json_decode($response, true);
  63. if (json_last_error() === JSON_ERROR_NONE && isset($jsonData['errcode'])) {
  64. Log::error('微信接口返回错误', $jsonData);
  65. return false;
  66. }
  67. // 生成本地临时文件名
  68. $tempDir = runtime_path() . 'temp' . DIRECTORY_SEPARATOR;
  69. if (!is_dir($tempDir)) {
  70. mkdir($tempDir, 0755, true);
  71. }
  72. $tempFileName = 'qrcode_' . $cardNo . '_' . time() . '.jpg';
  73. $tempFilePath = $tempDir . $tempFileName;
  74. // 将图片Buffer保存到本地临时文件
  75. if (file_put_contents($tempFilePath, $response) === false) {
  76. Log::error('保存临时文件失败', ['path' => $tempFilePath]);
  77. return false;
  78. }
  79. Log::info('临时文件保存成功', ['path' => $tempFilePath, 'size' => filesize($tempFilePath)]);
  80. // 生成七牛云存储路径
  81. $remotePath = 'gift_card_qrcode/' . date('Ymd') . '/' . $tempFileName;
  82. // 上传到七牛云
  83. if (self::uploadToQiniu($tempFilePath, $remotePath)) {
  84. // 删除临时文件
  85. unlink($tempFilePath);
  86. // 返回七牛云文件路径
  87. $config = ConfigService::get('storage', 'qiniu', []);
  88. $domain = rtrim($config['domain'] ?? '', '/');
  89. $fullUrl = $domain . '/' . $remotePath;
  90. Log::info('二维码生成并上传成功', [
  91. 'cardNo' => $cardNo,
  92. 'remotePath' => $remotePath,
  93. 'fullUrl' => $fullUrl
  94. ]);
  95. outFileLog($fullUrl,'qr_code','$fullUrl');
  96. return $fullUrl;
  97. } else {
  98. // 上传失败,删除临时文件
  99. if (file_exists($tempFilePath)) {
  100. unlink($tempFilePath);
  101. }
  102. return false;
  103. }
  104. } catch (\Exception $e) {
  105. Log::error('生成礼品卡二维码失败', [
  106. 'error' => $e->getMessage(),
  107. 'trace' => $e->getTraceAsString()
  108. ]);
  109. return false;
  110. }
  111. }
  112. public static function httpRequest($url, $data='', $method='GET'){
  113. $curl = curl_init();
  114. curl_setopt($curl, CURLOPT_URL, $url);
  115. curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, 0);
  116. curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, 0);
  117. curl_setopt($curl, CURLOPT_USERAGENT, $_SERVER['HTTP_USER_AGENT'] ?? 'Mozilla/5.0');
  118. curl_setopt($curl, CURLOPT_FOLLOWLOCATION, 1);
  119. curl_setopt($curl, CURLOPT_AUTOREFERER, 1);
  120. if($method=='POST') {
  121. curl_setopt($curl, CURLOPT_POST, 1);
  122. if ($data != '') {
  123. curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
  124. curl_setopt($curl, CURLOPT_HTTPHEADER, [
  125. 'Content-Type: application/json',
  126. 'Content-Length: ' . strlen($data)
  127. ]);
  128. }
  129. }
  130. curl_setopt($curl, CURLOPT_TIMEOUT, 30);
  131. curl_setopt($curl, CURLOPT_HEADER, 0);
  132. curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
  133. $result = curl_exec($curl);
  134. $httpCode = curl_getinfo($curl, CURLINFO_HTTP_CODE);
  135. $error = curl_error($curl);
  136. curl_close($curl);
  137. if ($error) {
  138. Log::error('CURL请求失败', ['error' => $error, 'url' => $url]);
  139. return false;
  140. }
  141. if ($httpCode !== 200) {
  142. Log::error('HTTP请求失败', ['code' => $httpCode, 'url' => $url]);
  143. return false;
  144. }
  145. return $result;
  146. }
  147. /**
  148. * @notes 上传文件到七牛云
  149. * @param string $localPath 本地文件路径
  150. * @param string $remotePath 远程文件路径
  151. * @return bool
  152. */
  153. private static function uploadToQiniu($localPath, $remotePath)
  154. {
  155. try {
  156. // 检查本地文件是否存在
  157. if (!file_exists($localPath)) {
  158. Log::error('本地文件不存在', ['path' => $localPath]);
  159. return false;
  160. }
  161. $config = [
  162. 'default' => ConfigService::get('storage', 'default', 'local'),
  163. 'engine' => ConfigService::get('storage_engine')
  164. ];
  165. Log::info('存储配置', $config);
  166. if ($config['default'] === 'qiniu') {
  167. $storageDriver = new Driver($config);
  168. // 使用绝对路径进行上传
  169. $absolutePath = realpath($localPath);
  170. $result = $storageDriver->fetch($absolutePath, $remotePath);
  171. if (!$result) {
  172. $error = $storageDriver->getError();
  173. Log::error('七牛云上传失败', [
  174. 'error' => $error,
  175. 'localPath' => $absolutePath,
  176. 'remotePath' => $remotePath
  177. ]);
  178. return false;
  179. }
  180. Log::info('七牛云上传成功', [
  181. 'localPath' => $absolutePath,
  182. 'remotePath' => $remotePath
  183. ]);
  184. return true;
  185. } else {
  186. // 如果不是七牛云存储,返回本地路径
  187. Log::info('使用本地存储', ['path' => $localPath]);
  188. return true;
  189. }
  190. } catch (\Exception $e) {
  191. Log::error('上传到七牛云失败', [
  192. 'error' => $e->getMessage(),
  193. 'localPath' => $localPath,
  194. 'remotePath' => $remotePath
  195. ]);
  196. return false;
  197. }
  198. }
  199. /**
  200. * @notes 批量生成二维码
  201. * @param array $giftCards 礼品卡数组
  202. * @return array
  203. */
  204. public static function batchGenerateQrCode($giftCards)
  205. {
  206. $result = [
  207. 'success' => 0,
  208. 'failed' => 0,
  209. 'total' => count($giftCards),
  210. 'details' => []
  211. ];
  212. foreach ($giftCards as $card) {
  213. $qrCodePath = self::generateAndUploadQrCode($card['card_no'], $card['card_pass']);
  214. if ($qrCodePath) {
  215. // 更新数据库中的二维码路径
  216. \app\common\model\GiftCardInfo::where('id', $card['id'])
  217. ->update(['qr_code_path' => $qrCodePath]);
  218. $result['success']++;
  219. $result['details'][] = [
  220. 'card_no' => $card['card_no'],
  221. 'status' => 'success',
  222. 'qr_code_path' => $qrCodePath
  223. ];
  224. } else {
  225. $result['failed']++;
  226. $result['details'][] = [
  227. 'card_no' => $card['card_no'],
  228. 'status' => 'failed',
  229. 'error' => '生成或上传失败'
  230. ];
  231. }
  232. }
  233. return $result;
  234. }
  235. }