Base.php 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  1. <?php
  2. namespace app\common\service\qrcode;
  3. use app\common\library\easywechat\AppWx;
  4. /**
  5. * 二维码服务基类
  6. */
  7. class Base
  8. {
  9. /**
  10. * 构造方法
  11. */
  12. public function __construct()
  13. {
  14. }
  15. /**
  16. * 保存小程序码到文件
  17. */
  18. protected function saveQrcode($app_id, $scene, $page)
  19. {
  20. // 文件目录
  21. $dirPath = root_path('public') . "/temp/{$app_id}/image_wx";
  22. !is_dir($dirPath) && mkdir($dirPath, 0755, true);
  23. // 文件名称
  24. $fileName = 'qrcode_' . md5($app_id . $scene . $page) . '.png';
  25. // 文件路径
  26. $savePath = "{$dirPath}/{$fileName}";
  27. if (file_exists($savePath)) return $savePath;
  28. // 小程序配置信息
  29. $app = AppWx::getApp($app_id);
  30. // 请求api获取小程序码
  31. $response = $app->app_code->getUnlimit($scene, [
  32. 'page' => $page,
  33. 'width' => 430
  34. ]);
  35. // 保存小程序码到文件
  36. if ($response instanceof \EasyWeChat\Kernel\Http\StreamResponse) {
  37. $response->saveAs($dirPath, $fileName);
  38. }
  39. return $savePath;
  40. }
  41. /**
  42. * 保存普通二维码到文件
  43. */
  44. protected function saveMpQrcode(\Endroid\QrCode\QrCode $qrcode, $app_id, $scene, $source)
  45. {
  46. // 文件目录
  47. $dirPath = root_path('public') ."/temp/{$app_id}/{$source}";
  48. !is_dir($dirPath) && mkdir($dirPath, 0755, true);
  49. // 文件名称
  50. $fileName = 'qrcode_' . md5($app_id . $scene) . '.png';
  51. // 文件路径
  52. $savePath = "{$dirPath}/{$fileName}";
  53. if (file_exists($savePath)) return $savePath;
  54. // 保存二维码到文件
  55. $qrcode->writeFile($savePath);
  56. return $savePath;
  57. }
  58. /**
  59. * 获取网络图片到临时目录
  60. */
  61. protected function saveTempImage($app_id, $url, $mark = 'temp')
  62. {
  63. $dirPath = root_path('public') . "temp/{$app_id}/{$mark}";
  64. !is_dir($dirPath) && mkdir($dirPath, 0755, true);
  65. $savePath = $dirPath . '/' . $mark . '_' . md5($url) . '.png';
  66. if (file_exists($savePath)) return $savePath;
  67. $ch = curl_init($url);
  68. curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
  69. curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
  70. curl_setopt($ch, CURLOPT_BINARYTRANSFER, 1);
  71. $img = curl_exec($ch);
  72. curl_close($ch);
  73. $fp = fopen($savePath, 'w');
  74. fwrite($fp, $img);
  75. fclose($fp);
  76. return $savePath;
  77. }
  78. }