Base.php 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293
  1. <?php
  2. namespace app\common\service\qrcode;
  3. use app\common\exception\BaseException;
  4. use app\common\library\wechat\Qrcode;
  5. use app\common\model\Wxapp as WxappModel;
  6. /**
  7. * 二维码服务基类
  8. * Class Base
  9. * @package app\common\service\qrcode
  10. */
  11. class Base
  12. {
  13. /**
  14. * 构造方法
  15. * Base constructor.
  16. */
  17. public function __construct()
  18. {
  19. }
  20. /**
  21. * 保存小程序码到文件
  22. * @param $wxappId
  23. * @param $scene
  24. * @param null $page
  25. * @return string
  26. * @throws \app\common\exception\BaseException
  27. * @throws \think\Exception
  28. * @throws \think\exception\DbException
  29. */
  30. protected function saveQrcode($wxappId, $scene, $page = null)
  31. {
  32. // 文件目录
  33. $dirPath = RUNTIME_PATH . 'image' . '/' . $wxappId;
  34. !is_dir($dirPath) && mkdir($dirPath, 0755, true);
  35. // 文件名称
  36. $fileName = 'qrcode_' . md5($wxappId . $scene . $page) . '.png';
  37. // 文件路径
  38. $savePath = "{$dirPath}/{$fileName}";
  39. if (file_exists($savePath)) return $savePath;
  40. // 小程序配置信息
  41. $wxConfig = WxappModel::getWxappCache($wxappId);
  42. // 请求api获取小程序码
  43. $Qrcode = new Qrcode($wxConfig['app_id'], $wxConfig['app_secret']);
  44. $content = $Qrcode->getQrcode($scene, $page);
  45. // 保存到文件
  46. file_put_contents($savePath, $content);
  47. return $savePath;
  48. }
  49. /**
  50. * 获取网络图片到临时目录
  51. * @param $wxappId
  52. * @param $url
  53. * @param string $mark
  54. * @return string
  55. * @throws BaseException
  56. */
  57. protected function saveTempImage($wxappId, $url, $mark = 'temp')
  58. {
  59. $dirPath = RUNTIME_PATH . 'image' . '/' . $wxappId;
  60. !is_dir($dirPath) && mkdir($dirPath, 0755, true);
  61. $savePath = $dirPath . '/' . $mark . '_' . md5($url) . '.png';
  62. if (file_exists($savePath)) return $savePath;
  63. $ch = curl_init($url);
  64. curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
  65. curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
  66. curl_setopt($ch, CURLOPT_BINARYTRANSFER, 1);
  67. $img = curl_exec($ch);
  68. if ($img === false) {
  69. $this->throwError('CURL错误:' . curl_error($ch));
  70. }
  71. curl_close($ch);
  72. $fp = fopen($savePath, 'w');
  73. fwrite($fp, $img);
  74. fclose($fp);
  75. return $savePath;
  76. }
  77. /**
  78. * 返回错误信息
  79. * @param $msg
  80. * @throws BaseException
  81. */
  82. private function throwError($msg)
  83. {
  84. throw new BaseException(['msg' => $msg]);
  85. }
  86. }