Thinkphp引入phpqrcode.php类库文件,实现对外的二维码生成接口

    xiaoxiao2023-10-27  144

    1、先下载phpqrcode.php类库

    下载链接:https://sourceforge.net/projects/phpqrcode/,下载成功后解压出来,我们只要phpqrcode文件夹里的phpqrcode.php即可。

    2、加载类库,调用类库方法

    方式一:把phpqrcode.php放到extend目录下,在controller控制器中引入该类库,引入方法如下:

    <?php namespace app\index\controller; use think\Cache; use think\Controller; use think\Db; use think\Session; use think\Request; /**引入类库(extend/phpqrcode.php)*/ import('phpqrcode', EXTEND_PATH); /* *二维码生成API接口(对外) */ class Qr extends Jcb{ public function api(){ if(!isset($_GET['text'])){ header("Content-type: text/html; charset=utf-8"); echo '参数错误.'; exit; } $text = strtoupper(trim($_GET['text'])); //访问频率 if(Cache::get($text)){ header("Content-type: text/html; charset=utf-8"); echo '请求频率太快,5秒内仅允许一次刷新';exit; }else{ Cache::set($text,'1',$this->config['visit-interval']); } $errorCorrectionLevel =intval(2) ;//容错级别 $matrixPointSize = intval(4); //生成图片大小 $margin =1;//外边距离(白边) //调用类库里的类QRcode下的png接口方法 \QRcode::png($text,false, $errorCorrectionLevel, $matrixPointSize, 1); die; } }

    方式二:在vendor目录下,创建phpqrcode目录,并且把phpqrcode.php文件放进去,Vendor引用方式如下:

    <?php namespace app\index\controller; use think\Cache; use think\Controller; use think\Db; use think\Session; use think\Request; /* *二维码生成API接口(对外) */ class Qr extends Jcb{ public function api(){ if(!isset($_GET['text'])){ header("Content-type: text/html; charset=utf-8"); echo '参数错误.'; exit; } $text = strtoupper(trim($_GET['text'])); //访问频率 if(Cache::get($text)){ header("Content-type: text/html; charset=utf-8"); echo '请求频率太快,5秒内仅允许一次刷新';exit; }else{ Cache::set($text,'1',$this->config['visit-interval']); } //引入类库 Vendor('phpqrcode.phpqrcode'); $errorCorrectionLevel =intval(2) ;//容错级别 $matrixPointSize = intval(4); //生成图片大小 $margin =1;//外边距离(白边) //实例类库里的QRcode类对象 $qr = new \QRcode(); $qr->png($text,false, $errorCorrectionLevel, $matrixPointSize, 1); die; } }

    3、以上代码就实现是生成二维码的功能,接口调用效果如下:

    最新回复(0)