Base.php 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  1. <?php
  2. /**
  3. *
  4. * @copyright ©2020 点小铺
  5. * @author hanj
  6. * @link: https://dyuit.com
  7. * Created by VSCode
  8. */
  9. namespace app\common\service\qrcode;
  10. use app\common\library\wechat\Qrcode;
  11. use app\common\model\Wxapp as WxappModel;
  12. /**
  13. * 二维码服务基类
  14. * Class Base
  15. * @package app\common\service\qrcode
  16. */
  17. class Base
  18. {
  19. /**
  20. * 构造方法
  21. * Base constructor.
  22. */
  23. public function __construct()
  24. {
  25. }
  26. /**
  27. * 保存小程序码到文件
  28. * @param $wxapp_id
  29. * @param $scene
  30. * @param null $page
  31. * @return string
  32. * @throws \app\common\exception\BaseException
  33. * @throws \think\exception\DbException
  34. */
  35. protected function saveQrcode($wxapp_id, $scene, $page = null)
  36. {
  37. // 文件目录
  38. $dirPath = RUNTIME_PATH . 'image' . '/' . $wxapp_id;
  39. !is_dir($dirPath) && mkdir($dirPath, 0755, true);
  40. // 文件名称
  41. $fileName = 'qrcode_' . md5($wxapp_id . $scene . $page) . '.png';
  42. // 文件路径
  43. $savePath = "{$dirPath}/{$fileName}";
  44. if (file_exists($savePath)) return $savePath;
  45. // 小程序配置信息
  46. $wxConfig = WxappModel::getWxappCache($wxapp_id);
  47. // 请求api获取小程序码
  48. $Qrcode = new Qrcode($wxConfig['app_id'], $wxConfig['app_secret']);
  49. $content = $Qrcode->getQrcode($scene, $page);
  50. // 保存到文件
  51. file_put_contents($savePath, $content);
  52. return $savePath;
  53. }
  54. /**
  55. * 获取网络图片到临时目录
  56. * @param $wxapp_id
  57. * @param $url
  58. * @param string $mark
  59. * @return string
  60. */
  61. protected function saveTempImage($wxapp_id, $url, $mark = 'temp')
  62. {
  63. $dirPath = RUNTIME_PATH . 'image' . '/' . $wxapp_id;
  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. }