GiftCardQrCodeService.php 10 KB

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