MiniQrcode.php 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. <?php
  2. namespace addons\service\library;
  3. use app\api\model\service\ProjectConfigure;
  4. use think\Cache;
  5. use fast\Random;
  6. class MiniQrcode
  7. {
  8. protected $appid;
  9. protected $secret;
  10. protected $accessUrl = 'https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=';
  11. protected $url = "https://api.weixin.qq.com/wxa/getwxacode?access_token=";
  12. public function __construct()
  13. {
  14. $serviceConfig = \app\api\model\service\ProjectConfigure::getProjectConfig();
  15. $this->appid = $serviceConfig['userappid'];
  16. $this->secret = $serviceConfig['usersecret'];
  17. }
  18. // 获取ACCESS_TOKEN
  19. public function getAccessToken()
  20. {
  21. $key = 'user_wx_access_token';
  22. $token = Cache::get($key);
  23. if(!$token)
  24. {
  25. $url = $this->accessUrl . $this->appid . '&secret=' . $this->secret;
  26. $res = json_decode(\fast\Http::get($url), true);
  27. $token = $res['access_token'];
  28. Cache::set($key,$token,7000);
  29. }
  30. return $token;
  31. }
  32. // 生成小程序二维码
  33. public function createMiniProgramQRCode($path, $width = 430,$scene='')
  34. {
  35. $accessToken = $this->getAccessToken();
  36. $url = $this->url.$accessToken;
  37. $data = json_encode(['scene'=>$scene,'path' => $path, 'width' => $width]);
  38. $ch = curl_init($url);
  39. curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
  40. curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
  41. curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
  42. curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
  43. curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
  44. curl_setopt($ch, CURLOPT_TIMEOUT, 30);
  45. curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json', 'Content-Length: ' . strlen($data)));
  46. $result = curl_exec($ch);
  47. if (curl_errno($ch)) {
  48. curl_close($ch);
  49. return false;
  50. }
  51. $path ='/public/uploads/qrcode/'.date("Y-m-d").'/';
  52. if (!is_dir(ROOT_PATH.$path))
  53. {
  54. mkdir(ROOT_PATH.$path,0777,true);
  55. }
  56. $file = "/uploads/qrcode/".date("Y-m-d").'/'.time().Random::alnum().".png";
  57. $fileName = $_SERVER['DOCUMENT_ROOT'].$file;
  58. file_put_contents($fileName, $result);
  59. curl_close($ch);
  60. return $file;
  61. }
  62. }