💎一站式轻松地调用各大LLM模型接口,支持GPT4、智谱、星火、月之暗面及文生图 广告
1、下载他的基类、并添加上命名空间、改一下类名和文件名 ![](https://img.kancloud.cn/7f/b3/7fb3b8d0f36a992a6e4794c1ec342cc9_567x487.png) 下面封装的方法有打印小票、添加打印机、删除打印机 ``` <?php namespace feieyun; class HttpClient { // Request vars var $host; var $port; var $path; var $method; var $postdata = ''; var $cookies = array(); var $referer; var $accept = 'text/xml,application/xml,application/xhtml+xml,text/html,text/plain,image/png,image/jpeg,image/gif,*/*'; var $accept_encoding = 'gzip'; var $accept_language = 'en-us'; var $user_agent = 'Incutio HttpClient v0.9'; var $timeout = 20; var $use_gzip = true; var $persist_cookies = true; var $persist_referers = true; var $debug = false; var $handle_redirects = true; var $max_redirects = 5; var $headers_only = false; var $username; var $password; var $status; var $headers = array(); var $content = ''; var $errormsg; var $redirect_count = 0; var $cookie_host = ''; function __construct($host, $port=80) { $this->host = $host; $this->port = $port; } function get($path, $data = false) { $this->path = $path; $this->method = 'GET'; if ($data) { $this->path .= '?'.$this->buildQueryString($data); } return $this->doRequest(); } function post($path, $data) { $this->path = $path; $this->method = 'POST'; $this->postdata = $this->buildQueryString($data); return $this->doRequest(); } function buildQueryString($data) { $querystring = ''; if (is_array($data)) { foreach ($data as $key => $val) { if (is_array($val)) { foreach ($val as $val2) { $querystring .= urlencode($key).'='.urlencode($val2).'&'; } } else { $querystring .= urlencode($key).'='.urlencode($val).'&'; } } $querystring = substr($querystring, 0, -1); // Eliminate unnecessary & } else { $querystring = $data; } return $querystring; } function doRequest() { if (!$fp = @fsockopen($this->host, $this->port, $errno, $errstr, $this->timeout)) { switch($errno) { case -3: $this->errormsg = 'Socket creation failed (-3)'; case -4: $this->errormsg = 'DNS lookup failure (-4)'; case -5: $this->errormsg = 'Connection refused or timed out (-5)'; default: $this->errormsg = 'Connection failed ('.$errno.')'; $this->errormsg .= ' '.$errstr; $this->debug($this->errormsg); } return false; } socket_set_timeout($fp, $this->timeout); $request = $this->buildRequest(); $this->debug('Request', $request); fwrite($fp, $request); $this->headers = array(); $this->content = ''; $this->errormsg = ''; $inHeaders = true; $atStart = true; while (!feof($fp)) { $line = fgets($fp, 4096); if ($atStart) { $atStart = false; if (!preg_match('/HTTP\/(\\d\\.\\d)\\s*(\\d+)\\s*(.*)/', $line, $m)) { $this->errormsg = "Status code line invalid: ".htmlentities($line); $this->debug($this->errormsg); return false; } $http_version = $m[1]; $this->status = $m[2]; $status_string = $m[3]; $this->debug(trim($line)); continue; } if ($inHeaders) { if (trim($line) == '') { $inHeaders = false; $this->debug('Received Headers', $this->headers); if ($this->headers_only) { break; } continue; } if (!preg_match('/([^:]+):\\s*(.*)/', $line, $m)) { continue; } $key = strtolower(trim($m[1])); $val = trim($m[2]); if (isset($this->headers[$key])) { if (is_array($this->headers[$key])) { $this->headers[$key][] = $val; } else { $this->headers[$key] = array($this->headers[$key], $val); } } else { $this->headers[$key] = $val; } continue; } $this->content .= $line; } fclose($fp); if (isset($this->headers['content-encoding']) && $this->headers['content-encoding'] == 'gzip') { $this->debug('Content is gzip encoded, unzipping it'); $this->content = substr($this->content, 10); $this->content = gzinflate($this->content); } if ($this->persist_cookies && isset($this->headers['set-cookie']) && $this->host == $this->cookie_host) { $cookies = $this->headers['set-cookie']; if (!is_array($cookies)) { $cookies = array($cookies); } foreach ($cookies as $cookie) { if (preg_match('/([^=]+)=([^;]+);/', $cookie, $m)) { $this->cookies[$m[1]] = $m[2]; } } $this->cookie_host = $this->host; } if ($this->persist_referers) { $this->debug('Persisting referer: '.$this->getRequestURL()); $this->referer = $this->getRequestURL(); } if ($this->handle_redirects) { if (++$this->redirect_count >= $this->max_redirects) { $this->errormsg = 'Number of redirects exceeded maximum ('.$this->max_redirects.')'; $this->debug($this->errormsg); $this->redirect_count = 0; return false; } $location = isset($this->headers['location']) ? $this->headers['location'] : ''; $uri = isset($this->headers['uri']) ? $this->headers['uri'] : ''; if ($location || $uri) { $url = parse_url($location.$uri); return $this->get($url['path']); } } return true; } function buildRequest() { $headers = array(); $headers[] = "{$this->method} {$this->path} HTTP/1.0"; $headers[] = "Host: {$this->host}"; $headers[] = "User-Agent: {$this->user_agent}"; $headers[] = "Accept: {$this->accept}"; if ($this->use_gzip) { $headers[] = "Accept-encoding: {$this->accept_encoding}"; } $headers[] = "Accept-language: {$this->accept_language}"; if ($this->referer) { $headers[] = "Referer: {$this->referer}"; } if ($this->cookies) { $cookie = 'Cookie: '; foreach ($this->cookies as $key => $value) { $cookie .= "$key=$value; "; } $headers[] = $cookie; } if ($this->username && $this->password) { $headers[] = 'Authorization: BASIC '.base64_encode($this->username.':'.$this->password); } if ($this->postdata) { $headers[] = 'Content-Type: application/x-www-form-urlencoded'; $headers[] = 'Content-Length: '.strlen($this->postdata); } $request = implode("\r\n", $headers)."\r\n\r\n".$this->postdata; return $request; } function getStatus() { return $this->status; } function getContent() { return $this->content; } function getHeaders() { return $this->headers; } function getHeader($header) { $header = strtolower($header); if (isset($this->headers[$header])) { return $this->headers[$header]; } else { return false; } } function getError() { return $this->errormsg; } function getCookies() { return $this->cookies; } function getRequestURL() { $url = 'https://'.$this->host; if ($this->port != 80) { $url .= ':'.$this->port; } $url .= $this->path; return $url; } function setUserAgent($string) { $this->user_agent = $string; } function setAuthorization($username, $password) { $this->username = $username; $this->password = $password; } function setCookies($array) { $this->cookies = $array; } function useGzip($boolean) { $this->use_gzip = $boolean; } function setPersistCookies($boolean) { $this->persist_cookies = $boolean; } function setPersistReferers($boolean) { $this->persist_referers = $boolean; } function setHandleRedirects($boolean) { $this->handle_redirects = $boolean; } function setMaxRedirects($num) { $this->max_redirects = $num; } function setHeadersOnly($boolean) { $this->headers_only = $boolean; } function setDebug($boolean) { $this->debug = $boolean; } function quickGet($url) { $bits = parse_url($url); $host = $bits['host']; $port = isset($bits['port']) ? $bits['port'] : 80; $path = isset($bits['path']) ? $bits['path'] : '/'; if (isset($bits['query'])) { $path .= '?'.$bits['query']; } $client = new HttpClient($host, $port); if (!$client->get($path)) { return false; } else { return $client->getContent(); } } function quickPost($url, $data) { $bits = parse_url($url); $host = $bits['host']; $port = isset($bits['port']) ? $bits['port'] : 80; $path = isset($bits['path']) ? $bits['path'] : '/'; $client = new HttpClient($host, $port); if (!$client->post($path, $data)) { return false; } else { return $client->getContent(); } } function debug($msg, $object = false) { if ($this->debug) { print '<div style="border: 1px solid red; padding: 0.5em; margin: 0.5em;"><strong>HttpClient Debug:</strong> '.$msg; if ($object) { ob_start(); print_r($object); $content = htmlentities(ob_get_contents()); ob_end_clean(); print '<pre>'.$content.'</pre>'; } print '</div>'; } } } ?> ``` 2、建立一个接口使用类, ``` <?php namespace feieyun; use feieyun\HttpClient; class Feieyun { protected $USER='2547895205@qq.com';//*必填*:飞鹅云后台注册账号 protected $UKEY='m4XcfzbLwRpZXL3Z';//*必填*: 飞鹅云后台注册账号后生成的UKEY 【备注:这不是填打印机的KEY】 protected $SN; //*必填*:打印机编号,必须要在管理后台里添加打印机或调用API接口添加之后,才能调用API //以下参数不需要修改 protected $IP='api.feieyun.cn';//接口IP或域名 protected $PORT=80;//接口IP端口 protected $PATH='/Api/Open/';//接口IP或域名 public function __construct($SN="",$USER = '',$UKEY='') { if(!empty($SN)){ $this->SN = $SN; } if(!empty($USER)){ $this->USER = $USER; } if(!empty($USER)){ $this->UKEY = $UKEY; } } public function batchDel($snlistData){ $snlist=""; $snlistDataCount=count($snlistData); $i=0; foreach ($snlistData as $key => $value) { $i++; if($i>=$snlistDataCount){ $snlist .= "{$value}"; }else{ $snlist .= "{$value}-"; } } // var_dump($printerContent);die; $this->printerDelList($snlist); } //添加打印机 /* 使用案例 $printerConten => 打印机编号sn(必填) # 打印机识别码key(必填) # 备注名称(选填) # 流量卡号码(选填),多台打印机请换行(\n)添加新打印机信息,每次最多100台。 $printerData=[ ["Sn"=>"921555411","KEY"=>"amnkatm5","remark"=>"测试","carnum"=>""], // ["Sn"=>"921555412","KEY"=>"amnkatm2","remark"=>"测试2","carnum"=>""], ]; $Feieyun=new Feieyun(); $Feieyun->batchAdd($printerData); */ public function batchAdd($printerData){ $printerContent=""; $printerDataCount=count($printerData); $i=0; foreach ($printerData as $key => $value) { $i++; $SN=$value["Sn"]; $KEY=$value["KEY"]; $remark=$value["remark"]; $carnum=$value["carnum"]; if($i>=$printerDataCount){ $printerContent .= "{$SN}#{$KEY}#{$remark}#{$carnum}"; }else{ $printerContent .= "{$SN}#{$KEY}#{$remark}#{$carnum}\n"; } } // var_dump($printerContent);die; $this->printerAddlist($printerContent); } // $title,$goods,$note,$extension public function printReceipts($title,$goods,$note,$extension){ /* 使用案例 $Feieyun=new Feieyun("921555411"); $title="测试标题api".time(); $note="测试备注api".time(); $goods=[ ["name"=>"测试商品","price"=>"10.00","num"=>3], ["name"=>"测试商品品","price"=>"10.00","num"=>3], ["name"=>"测试商品3测试商品2测试商品2","price"=>"10.00","num"=>3], ]; $extension =[ ["name"=>"测试","value"=>"10.00" ], ["name"=>"测试商品1","value"=>"10.00" ], ["name"=>"时间","value"=>date("Y-m-d") ], ]; $Feieyun->printReceipts($title,$goods,$note,$extension); */ $content = '<CB>'.$title.'</CB><BR>'; $content .= '名称      单价 数量 金额<BR>'; $content .= '--------------------------------<BR>'; $total_price=0; foreach ($goods as $key => $value) { $numprice=$value['price']*$value['num']; $total_price=$total_price+$numprice; if(mb_strlen($value['name'])>=8){ $name=mb_substr( $value['name'],0,6,"utf-8" ) ; $content .= $name."... {$value['price']} {$value['num']} {$numprice}<BR>"; }else{ $emptynum=8-mb_strlen($value['name']); $content .= $value['name'].str_repeat(' ',$emptynum)." {$value['price']} {$value['num']} {$numprice}<BR>"; } } $content .= "备注:{$note}<BR>"; $content .= '--------------------------------<BR>'; $content .= "合计:{$total_price}元<BR>"; foreach ($extension as $key => $value) { $content .= "{$value['name']}:{$value['value']}<BR>"; } // $content .= '<QR>http://www.feieyun.com</QR>';//把二维码字符串用标签套上即可自动生成二维码 //提示: //SN => 打印机编号 //$content => 打印内容,不能超过5000字节 //$times => 打印次数,默认为1。 //打开注释可测试 $this->printMsg($this->SN,$content,1);//该接口只能是小票机使用,如购买的是标签机请使用下面方法3,调用打印 } /** * [批量添加打印机接口 Open_printerAddlist] * @param [string] $printerContent [打印机的sn#key] * @return [string] [接口返回值] */ public function printerAddlist($printerContent){ $time = time(); //请求时间 $msgInfo = array( 'user'=>$this->USER, 'stime'=>$time, 'sig'=>$this->signature($time), 'apiname'=>'Open_printerAddlist', 'printerContent'=>$printerContent ); $client = new HttpClient($this->IP,$this->PORT); if(!$client->post($this->PATH,$msgInfo)){ return 'error'; }else{ $result = $client->getContent(); return json_encode($result); } } /** * 打印订单[接口 Open_printMsg] * @param [string] $sn [打印机编号sn] * @param [string] $content [打印内容] * @param [string] $times [打印联数] * @return [string] [接口返回值] */ public function printMsg($sn,$content,$times){ $time = time(); //请求时间 $msgInfo = array( 'user'=>$this->USER, 'stime'=>$time, 'sig'=>$this->signature($time), 'apiname'=>'Open_printMsg', 'sn'=>$sn, 'content'=>$content, 'times'=>$times//打印次数 ); $client = new HttpClient($this->IP,$this->PORT); if(!$client->post($this->PATH,$msgInfo)){ return 'error'; }else{ //服务器返回的JSON字符串,建议要当做日志记录起来 $result = $client->getContent(); return json_encode($result); } } /** * 标签机打印订单[接口 Open_printLabelMsg] * @param [string] $sn [打印机编号sn] * @param [string] $content [打印内容] * @param [string] $times [打印联数] * @return [string] [接口返回值] */ public function printLabelMsg($sn,$content,$times){ $time = time(); //请求时间 $msgInfo = array( 'user'=>$this->USER, 'stime'=>$time, 'sig'=>$this->signature($time), 'apiname'=>'Open_printLabelMsg', 'sn'=>$sn, 'content'=>$content, 'times'=>$times//打印次数 ); $client = new HttpClient($this->IP,$this->PORT); if(!$client->post($this->PATH,$msgInfo)){ return 'error'; }else{ //服务器返回的JSON字符串,建议要当做日志记录起来 $result = $client->getContent(); return json_encode($result); } } /** * 批量删除[打印机 Open_printerDelList] * @param [string] $snlist [打印机编号,多台打印机请用减号“-”连接起来] * @return [string] [接口返回值] */ public function printerDelList($snlist){ $time = time(); //请求时间 $msgInfo = array( 'user'=>$this->USER, 'stime'=>$time, 'sig'=>$this->signature($time), 'apiname'=>'Open_printerDelList', 'snlist'=>$snlist ); $client = new HttpClient($this->IP,$this->PORT); if(!$client->post($this->PATH,$msgInfo)){ return 'error'; }else{ $result = $client->getContent(); return json_encode($result); } } /** * 修改打印机信息[接口 Open_printerEdit] * @param [string] $sn [打印机编号] * @param [string] $name [打印机备注名称] * @param [string] $phonenum [打印机流量卡号码,可以不传参,但是不能为空字符串] * @return [string] [接口返回值] */ public function printerEdit($sn,$name,$phonenum){ $time = time(); //请求时间 $msgInfo = array( 'user'=>$this->USER, 'stime'=>$time, 'sig'=>$this->signature($time), 'apiname'=>'Open_printerEdit', 'sn'=>$sn, 'name'=>$name, 'phonenum'=>$phonenum ); $client = new HttpClient($this->IP,$this->PORT); if(!$client->post($this->PATH,$msgInfo)){ return 'error'; }else{ $result = $client->getContent(); return json_encode($result); } } /** * 清空待打印订单[接口 Open_delPrinterSqs] * @param [string] $sn [打印机编号] * @return [string] [接口返回值] */ public function delPrinterSqs($sn){ $time = time(); //请求时间 $msgInfo = array( 'user'=>$this->USER, 'stime'=>$time, 'sig'=>$this->signature($time), 'apiname'=>'Open_delPrinterSqs', 'sn'=>$sn ); $client = new HttpClient($this->IP,$this->PORT); if(!$client->post($this->PATH,$msgInfo)){ return 'error'; }else{ $result = $client->getContent(); return json_encode($result); } } /** * 查询订单是否打印成功[接口 Open_queryOrderState] * @param [string] $orderid [调用打印机接口成功后,服务器返回的JSON中的编号 例如:123456789_20190919163739_95385649] * @return [string] [接口返回值] */ public function queryOrderState($orderid){ $time = time(); //请求时间 $msgInfo = array( 'user'=>$this->USER, 'stime'=>$time, 'sig'=>$this->signature($time), 'apiname'=>'Open_queryOrderState', 'orderid'=>$orderid ); $client = new HttpClient($this->IP,$this->PORT); if(!$client->post($this->PATH,$msgInfo)){ return 'error'; }else{ $result = $client->getContent(); return json_encode($result); } } /** * [查询指定打印机某天的订单统计数接口 Open_queryOrderInfoByDate] * @param [string] $sn [打印机的编号] * @param [string] $date [查询日期,格式YY-MM-DD,如:2019-09-20] * @return [string] [接口返回值] */ public function queryOrderInfoByDate($sn,$date){ $time = time(); //请求时间 $msgInfo = array( 'user'=>$this->USER, 'stime'=>$time, 'sig'=>$this->signature($time), 'apiname'=>'Open_queryOrderInfoByDate', 'sn'=>$sn, 'date'=>$date ); $client = new HttpClient($this->IP,$this->PORT); if(!$client->post($this->PATH,$msgInfo)){ return 'error'; }else{ $result = $client->getContent(); return json_encode($result); } } /** * 获取某台打印机状态[接口 Open_queryPrinterStatus] * @param [string] $sn [打印机编号] * @return [string] [接口返回值] */ public function queryPrinterStatus($sn){ $time = time(); //请求时间 $msgInfo = array( 'user'=>$this->USER, 'stime'=>$time, 'sig'=>$this->signature($time), 'apiname'=>'Open_queryPrinterStatus', 'sn'=>$sn ); $client = new HttpClient($this->IP,$this->PORT); if(!$client->post($this->PATH,$msgInfo)){ return 'error'; }else{ $result = $client->getContent(); return json_encode($result); } } /** * [signature 生成签名] * @param [string] $time [当前UNIX时间戳,10位,精确到秒] * @return [string] [接口返回值] */ public function signature($time){ return sha1($this->USER.$this->UKEY.$time);//公共参数,请求公钥 } } //****************************************方法3 标签机专用打印订单接口**************************************************** //***接口返回值说明*** //正确例子:{"msg":"ok","ret":0,"data":"123456789_20160823165104_1853029628","serverExecutedTime":6} //错误例子:{"msg":"错误信息.","ret":非零错误码,"data":null,"serverExecutedTime":5} //标签说明: // $content = "<DIRECTION>1</DIRECTION>";//设定打印时出纸和打印字体的方向,n 0 或 1,每次设备重启后都会初始化为 0 值设置,1:正向出纸,0:反向出纸, // $content .= "<TEXT x='9' y='10' font='12' w='1' h='2' r='0'>#001 五号桌 1/3</TEXT><TEXT x='80' y='80' font='12' w='2' h='2' r='0'>可乐鸡翅</TEXT><TEXT x='9' y='180' font='12' w='1' h='1' r='0'>张三先生 13800138000</TEXT>";//40mm宽度标签纸打印例子,打开注释调用标签打印接口打印 //提示: //SN => 打印机编号 //$content => 打印内容,不能超过5000字节 //$times => 打印次数,默认为1。 //打开注释可测试 // printLabelMsg(SN,$content,1);//打开注释调用标签机打印接口进行打印,该接口只能是标签机使用,其它型号打印机请勿使用该接口 //************************************方法5 修改打印机信息接口************************************************ //***接口返回值说明*** //成功:{"msg":"ok","ret":0,"data":true,"serverExecutedTime":5} //错误:{"msg":"参数错误 : 参数值不能传空字符,\"\"、\"null\"、\"undefined\".","ret":-2,"data":null,"serverExecutedTime":1} //提示: //SN => 打印机编号 //$name => 打印机备注名称 //$phonenum => 打印机流量卡号码 //打开注释可测试 //$name = "飞鹅云打印机"; //$phonenum = "01234567891011121314"; // printerEdit(SN,$name,$phonenum); //************************************方法6 清空待打印订单接口************************************************ //***接口返回值说明*** //成功:{"msg":"ok","ret":0,"data":true,"serverExecutedTime":4} //错误:{"msg":"验证失败 : 打印机编号和用户不匹配.","ret":1002,"data":null,"serverExecutedTime":3} //错误:{"msg":"参数错误 : 参数值不能传空字符,\"\"、\"null\"、\"undefined\".","ret":-2,"data":null,"serverExecutedTime":2} //提示: //SN => 打印机编号 //打开注释可测试 // delPrinterSqs(SN); //*********************************方法7 查询订单是否打印成功接口********************************************* //***接口返回值说明*** //正确例子: //已打印:{"msg":"ok","ret":0,"data":true,"serverExecutedTime":6} //未打印:{"msg":"ok","ret":0,"data":false,"serverExecutedTime":6} //提示: //$orderid => 订单ID,由方法1接口Open_printMsg返回。 //打开注释可测试 //$orderid = "123456789_20160823165104_1853029628";//订单ID,从方法1返回值中获取 //queryOrderState($orderid); //*****************************方法8 查询指定打印机某天的订单统计数接口***************************************** //***接口返回值说明*** //正确例子: //{"msg":"ok","ret":0,"data":{"print":6,"waiting":1},"serverExecutedTime":9} //错误:{"msg":"验证失败 : 打印机编号和用户不匹配.","ret":1002,"data":null,"serverExecutedTime":3} //提示: //$date => 查询日期,格式YY-MM-DD,如:2016-09-20 //打开注释可测试 // $date = "2016-09-20"; // queryOrderInfoByDate(SN,$date); //***********************************方法9 获取某台打印机状态接口*********************************************** //***接口返回值说明*** //正确例子: //{"msg":"ok","ret":0,"data":"离线","serverExecutedTime":9} //{"msg":"ok","ret":0,"data":"在线,工作状态正常","serverExecutedTime":9} //{"msg":"ok","ret":0,"data":"在线,工作状态不正常","serverExecutedTime":9} //提示: //SN => 填打印机编号 //打开注释可测试 // queryPrinterStatus(SN); ?> ``` 3、使用 ``` use feieyun\Feieyun; /*打印*/ public function index() { $Feieyun=new Feieyun("921555411"); $title="测试标题api".time(); $note="测试备注api".time(); $goods=[ ["name"=>"测试商品","price"=>"10.00","num"=>3], ["name"=>"测试商品品","price"=>"10.00","num"=>3], ["name"=>"测试商品3测试商品2测试商品2","price"=>"10.00","num"=>3], ]; $extension =[ ["name"=>"测试","value"=>"10.00" ], ["name"=>"测试商品1","value"=>"10.00" ], ["name"=>"时间","value"=>date("Y-m-d") ], ]; $Feieyun->printReceipts($title,$goods,$note,$extension); } //*************************************批量添加打印机接口************************************************* //提示: //$printerConten => 打印机编号sn(必填) # 打印机识别码key(必填) # 备注名称(选填) # 流量卡号码(选填), 每次最多100台。 public function add() { $printerData=[ ["Sn"=>"921555411","KEY"=>"amnkatm5","remark"=>"测试","carnum"=>""], // ["Sn"=>"921555412","KEY"=>"amnkatm2","remark"=>"测试2","carnum"=>""], ]; $Feieyun=new Feieyun(); $Feieyun->batchAdd($printerData); } //************************************* 批量删除打印机接口************************************************* //提示: //$printerConten => 打印机编号sn(必填) , 每次最多100台 。 public function del() { $printerData=[ 921555411, ]; $Feieyun=new Feieyun(); $Feieyun->batchDel($printerData); } ```