| 1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768 |
- <?php
- namespace addons\service\library;
- use app\api\model\service\ProjectConfigure;
- use think\Cache;
- use fast\Random;
- class MiniQrcode
- {
- protected $appid;
- protected $secret;
- protected $accessUrl = 'https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=';
- protected $url = "https://api.weixin.qq.com/wxa/getwxacode?access_token=";
- public function __construct()
- {
- $serviceConfig = \app\api\model\service\ProjectConfigure::getProjectConfig();
- $this->appid = $serviceConfig['userappid'];
- $this->secret = $serviceConfig['usersecret'];
- }
- // 获取ACCESS_TOKEN
- public function getAccessToken()
- {
- $key = 'user_wx_access_token';
- $token = Cache::get($key);
- if(!$token)
- {
- $url = $this->accessUrl . $this->appid . '&secret=' . $this->secret;
- $res = json_decode(\fast\Http::get($url), true);
- $token = $res['access_token'];
- Cache::set($key,$token,7000);
- }
- return $token;
- }
- // 生成小程序二维码
- public function createMiniProgramQRCode($path, $width = 430,$scene='')
- {
- $accessToken = $this->getAccessToken();
- $url = $this->url.$accessToken;
- $data = json_encode(['scene'=>$scene,'path' => $path, 'width' => $width]);
- $ch = curl_init($url);
- curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
- curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
- curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
- curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
- curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
- curl_setopt($ch, CURLOPT_TIMEOUT, 30);
- curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json', 'Content-Length: ' . strlen($data)));
- $result = curl_exec($ch);
- if (curl_errno($ch)) {
- curl_close($ch);
- return false;
- }
- $path ='/public/uploads/qrcode/'.date("Y-m-d").'/';
- if (!is_dir(ROOT_PATH.$path))
- {
- mkdir(ROOT_PATH.$path,0777,true);
- }
- $file = "/uploads/qrcode/".date("Y-m-d").'/'.time().Random::alnum().".png";
- $fileName = $_SERVER['DOCUMENT_ROOT'].$file;
- file_put_contents($fileName, $result);
- curl_close($ch);
- return $file;
- }
- }
|