Base.php 2.2 KB

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