易信通用封装核心类
? ? ? ? 網上微信的二次開發教程很多,通用的封裝類也很多,但是唯獨不好找到易信的通用類,雖然說易信的用戶少,但也算是通信陣營的一份子把,博主借鑒了易信公共平臺整合庫,但是在作者的基礎上做了修改,作者原來的是照搬微信的核心通用封裝類,不過里面API有些錯誤,易信是沒法調通的,所以我在作者重構了對應的代碼,目前在項目中是通過擴展類的形式,給ThinkPHP框架用的之前的。Github的那位作者,如果你能看到這篇文章,請給我留言啊,我還沒有提交給這份代碼呢。ligboy@gmail.com
? 本文轉自:迅捷互動網絡工作室???易信通用封裝核心類
<?php class?YixinChat?{/*?配置參數??*/?/*?靜態常量?*/const?MSGTYPE_TEXT?=?'text';const?MSGTYPE_IMAGE?=?'image';const?MSGTYPE_LOCATION?=?'location';const?MSGTYPE_LINK?=?'link';const?MSGTYPE_EVENT?=?'event';const?MSGTYPE_MUSIC?=?'music';const?MSGTYPE_NEWS?=?'news';const?MSGTYPE_VOICE?=?'voice';const?MSGTYPE_VIDEO?=?'video';const?MSGTYPE_GOODS?=?'goods';const?MSGTYPE_CARD?=?'card';const?API_URL_PREFIX?=?'https://api.yixin.im/cgi-bin';const?AUTH_URL?=?'/token?grant_type=client_credential&';const?MENU_CREATE_URL?=?'/menu/create?';const?MENU_GET_URL?=?'/menu/get?';const?MENU_DELETE_URL?=?'/menu/delete?';/*?私有參數?*/private?$_msg;private?$_funcflag?=?false;public?$_receive;private?$_logcallback?=?null;private?$token;private?$appid;private?$appsecret;private?$access_token;public?$debug?=??false;??//調試開關/***?初始化工作*?@param?array?$options??array('token'=>'易信接口密鑰');*/public?function?__construct($options=array()){if?(!empty($options)){$this->token?=?isset($options['token'])?$options['token']:'';$this->appid?=?isset($options['appid'])?$options['appid']:'';$this->appsecret?=?isset($options['appsecret'])?$options['appsecret']:'';$this->debug?=?isset($options['debug'])?$options['debug']:false;$this->_logcallback?=?isset($options['logcallback'])?$options['logcallback']:false;}}/***?驗證請求簽名操作*?@return?boolean*/private?function?checkSignature(){$signature?=?$_GET["signature"];$timestamp?=?$_GET["timestamp"];$nonce?=?$_GET["nonce"];$token?=?$this->token;$tmpArray?=?array($token,?$timestamp,?$nonce);sort($tmpArray);if(sha1(implode($tmpArray))?==?$signature){return?true;}else{return?false;}}/***?驗證當前請求是否有效(可選)*?@param?bool?$return?是否返回*?@return?bool|string*/public?function?valid($return=false){$echoStr?=?isset($_GET["echostr"])?$_GET["echostr"]:?'';if?($return){if?($echoStr){if?($this->checkSignature()){return?$echoStr;}else{return?false;}}else{return?$this->checkSignature();}}else{if?($echoStr){if?($this->checkSignature()){die($echoStr);}else{die('No?Access');}}else{if?($this->checkSignature()){return?true;}else{die('No?Access');}}}}/***?設置發送消息*?@param?array|string?$msg?消息數組*?@param?bool?$append?是否在原消息數組追加*?@return?array*/public?function?Message($msg?=?array(),$append?=?false){if(is_array($msg)){if?($append){$this->_msg?=?array_merge($this->_msg,$msg);}else{$this->_msg?=?$msg;}return?$this->_msg;}else{return?$this->_msg;}}/***?設置星標*?@param?$flag*?@return?$this*/public?function?setFuncFlag($flag)?{$this->_funcflag?=?$flag;return?$this;}/***?調試信息日志日記錄*?@param?$log*?@return?mixed|null*/private?function?log($log){if?($this->debug?&&?function_exists($this->_logcallback))?{if?(is_array($log))?$log?=?print_r($log,true);return?call_user_func($this->_logcallback,$log);}return?null;}/***?@name?獲取易信服務器發來的信息*?@return?mixed*/public?function?getRev(){$postStr?=?file_get_contents("php://input");$this->log($postStr);if?(!empty($postStr)){$this->_receive?=?(array)simplexml_load_string($postStr,?'SimpleXMLElement',?LIBXML_NOCDATA);}return?$this;}/***?獲取消息發送者*?@return?string?or?boolean*/public?function?getRevFrom(){if?($this->_receive){return?$this->_receive['FromUserName'];}else{return?false;}}/***?獲取消息接受者*?@return?string?or?boolean*/public?function?getRevTo(){if?($this->_receive){return?$this->_receive['ToUserName'];}else{return?false;}}/***?獲取接收消息的類型*/public?function?getRevType(){if?(isset($this->_receive['MsgType'])){return?$this->_receive['MsgType'];}else{return?false;}}/***?獲取消息ID*/public?function?getRevID()?{if?(isset($this->_receive['MsgId']))return?$this->_receive['MsgId'];elsereturn?false;}/***?獲取消息發送時間*/public?function?getRevCtime()?{if?(isset($this->_receive['CreateTime'])){return?$this->_receive['CreateTime'];}else{return?false;}}/***?獲取接收消息內容正文*/public?function?getRevContent(){if?(isset($this->_receive['Content'])){return?$this->_receive['Content'];}else?if?(isset($this->_receive['Url']))?//獲取語音地址,需申請開通{ return?array('Url'=>$this->_receive['Url'],'name'=>$this->_receive['name'],'mimeType'=>$this->_receive['mimeType']);}else?if?(isset($this->_receive['url']))?//獲取視頻地址,需申請開通{ return?array('url'=>$this->_receive['url'],'name'=>$this->_receive['name'],'mimeType'=>$this->_receive['mimeType']);}else{return?false;}}/***?獲取接收消息圖片*/public?function?getRevPic(){if?(isset($this->_receive['PicUrl'])){return?$this->_receive['PicUrl'];}else{return?false;}}/***?獲取接收消息鏈接*//**public?function?getRevLink(){if?(isset($this->_receive['Url'])){return?array('url'=>$this->_receive['Url'],'title'=>$this->_receive['Title'],'description'=>$this->_receive['Description']);}else{return?false;}}/***?獲取接收語音推送*?@return?array|bool*/public?function?getRevVoice(){if?($this->_receive['MsgType']=='audio'){return?array('Url'=>$this->_receive['Url'],'name'=>$this->_receive['name'],'mimeType'=>$this->_receive['mimeType']);}else{return?false;}}/***?獲取接收地理位置*?@return?array('x'=>'','y'=>'','scale'=>'','label'=>'')*/public?function?getRevGeo(){if?(isset($this->_receive['Location_X'])){return?array('x'=>$this->_receive['Location_X'],'y'=>$this->_receive['Location_Y'],'scale'=>$this->_receive['Scale'],'label'=>$this->_receive['Label']);}else{return?false;}}/***?獲取上報地理位置事件*/public?function?getRevEventGeo(){if?(isset($this->_receive['Latitude'])){return?array('x'=>$this->_receive['Latitude'],'y'=>$this->_receive['Longitude'],'precision'=>$this->_receive['Precision'],);}?elsereturn?false;}/***?獲取接收事件推送*?@return?array?成功返回事件數組,失敗返回false*/public?function?getRevEvent(){if?(isset($this->_receive['Event'])){$array['Event']?=?$this->_receive['Event'];}if?(isset($this->_receive['EventKey'])){$array['EventKey']?=?$this->_receive['EventKey'];}if?(isset($array)?&&?count($array)?>?0)?{return?$array;}?else?{return?false;}}/***?獲取掃描帶參數二維碼事件*?*?事件類型為以下兩種時則調用此方法有效*?Event ?事件類型,subscribe*?Event ?事件類型,scan*?*?@return:?array?|?false*?array?(*?????'EventKey'=>'',??事件類型subscribe時候,qrscene_為前綴,后面為二維碼的參數值;事件類型scan時候,是一個32位無符號整數*?????'Ticket'=>''*?)*/public?function?getRevScanInfo(){if(isset($this->_receive['Event'])){ return?array('EventKey'=>$this->_receive['EventKey'],'Ticket'=>$this->_receive['Ticket'],);} }/***?獲取接收TICKET*/public?function?getRevTicket(){if?(isset($this->_receive['Ticket'])){return?$this->_receive['Ticket'];}?elsereturn?false;}/***?獲取二維碼的場景值*/public?function?getRevSceneId?(){if?(isset($this->_receive['EventKey'])){return?str_replace('qrscene_','',$this->_receive['EventKey']);}?else{return?false;}}/***?XML特殊字符過濾*?@param?$str*?@return?string*/private?static?function?xmlSafeStr($str){return?'<![CDATA['.preg_replace("/[\\x00-\\x08\\x0b-\\x0c\\x0e-\\x1f]/",'',$str).']]>';}/***?數據XML編碼*?@param?mixed?$data?數據*?@return?string*/private?static?function?data_to_xml($data){$xml?=?'';foreach?($data?as?$key?=>?$val){is_numeric($key)?&&?$key?=?"item";$xml????.=??"<$key>";$xml????.=??(?is_array($val)?||?is_object($val))???self::data_to_xml($val)??:?self::xmlSafeStr($val);list($key,?)?=?explode('?',?$key);$xml????.=??"</$key>";}return?$xml;}/***?XML編碼*?@param?mixed?$data?數據*?@param?string?$root?根節點名*?@param?string?$item?數字索引的子節點名*?@param?string?$attr?根節點屬性*?@param?string?$id???數字索引子節點key轉換的屬性名*?@return?string*/private?function?xml_encode($data,?$root='xml',?$item='item',?$attr='',?$id='id'){if(is_array($attr)){$_attr?=?array();foreach?($attr?as?$key?=>?$value){$_attr[]?=?"{$key}=\"{$value}\"";}$attr?=?implode('?',?$_attr);}$attr?=?trim($attr);$attr?=?empty($attr)???''?:?"?{$attr}";$xml?=?null;$xml?.=?"<{$root}{$attr}>";$xml???.=?self::data_to_xml($data);$xml???.=?"</{$root}>";return?$xml;}/***?過濾文字回復\r\n換行符*?@param?string?$text*?@return?string|mixed*/private?function?_auto_text_filter($text)?{if?(!$this->_text_filter)?return?$text;return?str_replace("\r\n",?"\n",?$text);}/***********************************************************************************************************************************************************/ /***?設置回復消息*?Examle:?$obj->text('hello')->reply();*?@param?string?$text*?@return?$this*/public?function?text($text=''){$FuncFlag?=?$this->_funcflag???1?:?0;$msg?=?array('ToUserName'?=>?$this->getRevFrom(),'FromUserName'=>$this->getRevTo(),'MsgType'=>self::MSGTYPE_TEXT,'Content'=>$text,'CreateTime'=>time());$this->Message($msg);return?$this;}/***?設置回復音樂*?@param?string?$title*?@param?string?$desc*?@param?string?$musicurl*?@param?string?$hgmusicurl*?@return?$this*/public?function?music($title,$desc,$musicurl,$hgmusicurl='')?{$FuncFlag?=?$this->_funcflag???1?:?0;$msg?=?array('ToUserName'?=>?$this->getRevFrom(),'FromUserName'=>$this->getRevTo(),'CreateTime'=>time(),'MsgType'=>self::MSGTYPE_MUSIC,'Music'=>array('Title'=>$title,'Description'=>$desc,'MusicUrl'=>$musicurl,'HQMusicUrl'=>$hgmusicurl));$this->Message($msg);return?$this;}/***?設置回復圖文*?@param?array?$newsData*?@return?$this*?@example?數組結構:*??array(*?? 0=>array(*?? 'Title'=>'msg?title',*?? 'Description'=>'summary?text',*?? 'PicUrl'=>'http://www.domain.com/1.jpg',*?? 'Url'=>'http://www.domain.com/1.html'*?? ),*?? 1=>....*??)*/public?function?news($newsData=array()){$FuncFlag?=?$this->_funcflag???1?:?0;$count?=?count($newsData);$msg?=?array('ToUserName'?=>?$this->getRevFrom(),'FromUserName'=>$this->getRevTo(),'CreateTime'=>time(),'MsgType'=>self::MSGTYPE_NEWS,????????????'ArticleCount'=>$count,'Articles'=>$newsData);$this->Message($msg);return?$this;}/****?向易信服務器回復消息*?Example:?$this->text('msg?tips')->reply();*?@param?array|string?$msg?要發送的信息,?默認取$this->_msg*?@param?bool?$return?是否返回信息而輸出??默認:false*?@return?string*/public?function?reply($msg=array(),$return?=?false){if?(empty($msg)){$msg?=?$this->_msg;}$xmldata=??$this->xml_encode($msg);$this->log($xmldata);if?($return){return?$xmldata;}else{echo?$xmldata;}}private?static?function?getTextArea($text,$str_start,$str_end){if(empty($text)||empty($str_start)){return?false;}$start_pos=@strpos($text,$str_start);if($start_pos===false){return?false;}$end_pos=strpos($text,$str_end,?$start_pos);if($end_pos>$start_pos?&&?$end_pos!==false){$begin_pos=$start_pos+strlen($str_start);return?substr($text,?$begin_pos,$end_pos-$begin_pos);}else{return?false;}}/***?GET?請求*?@param?string?$url*/private?function?http_get($url){//$proxy_url?=?"http://10.1.255.24:8090";$oCurl?=?curl_init();if(stripos($url,"https://")!==FALSE){//curl_setopt($oCurl,?CURLOPT_PROXY,?$proxy_url);curl_setopt($oCurl,?CURLOPT_SSL_VERIFYPEER,?FALSE);curl_setopt($oCurl,?CURLOPT_SSL_VERIFYHOST,?FALSE);curl_setopt($oCurl,?CURLOPT_SSLVERSION,?1);?//CURL_SSLVERSION_TLSv1}curl_setopt($oCurl,?CURLOPT_URL,?$url);curl_setopt($oCurl,?CURLOPT_RETURNTRANSFER,?1?);$sContent?=?curl_exec($oCurl);$aStatus?=?curl_getinfo($oCurl);curl_close($oCurl);if(intval($aStatus["http_code"])==200){return?$sContent;}else{return?false;}}/***?POST?請求*?@param?string?$url*?@param?array?$param*?@param?boolean?$post_file?是否文件上傳*?@return?string?content*/private?function?http_post($url,$param,$post_file=false){//$proxy_url?=?"http://10.1.255.24:8090";$oCurl?=?curl_init();if(stripos($url,"https://")!==FALSE){//curl_setopt($oCurl,?CURLOPT_PROXY,?$proxy_url);curl_setopt($oCurl,?CURLOPT_SSL_VERIFYPEER,?FALSE);curl_setopt($oCurl,?CURLOPT_SSL_VERIFYHOST,?false);curl_setopt($oCurl,?CURLOPT_SSLVERSION,?1);?//CURL_SSLVERSION_TLSv1}if?(is_string($param)?||?$post_file)?{$strPOST?=?$param;}?else?{$aPOST?=?array();foreach($param?as?$key=>$val){$aPOST[]?=?$key."=".urlencode($val);}$strPOST?=??join("&",?$aPOST);}curl_setopt($oCurl,?CURLOPT_URL,?$url);curl_setopt($oCurl,?CURLOPT_RETURNTRANSFER,?1?);curl_setopt($oCurl,?CURLOPT_POST,true);curl_setopt($oCurl,?CURLOPT_POSTFIELDS,$strPOST);$sContent?=?curl_exec($oCurl);$aStatus?=?curl_getinfo($oCurl);curl_close($oCurl);if(intval($aStatus["http_code"])==200){return?$sContent;}else{return?false;}} /***?通用auth驗證方法,暫時僅用于菜單更新操作*?@param?string?$appid*?@param?string?$appsecret*/public?function?checkAuth($appid='',$appsecret=''){if?(!$appid?||?!$appsecret)?{$appid?=?$this->appid;$appsecret?=?$this->appsecret;} $result?=?$this->http_get(self::API_URL_PREFIX.self::AUTH_URL.'appid='.$appid.'&secret='.$appsecret);if?($result){$json?=?json_decode($result,true); if?(!$json?||?isset($json['errcode']))?{$this->errCode?=?$json['errcode'];$this->errMsg?=?$json['errmsg'];return?false;}$this->access_token?=?$json['access_token'];$expire?=?$json['expires_in']???intval($json['expires_in'])-100?:?3600;S('authname',$this->access_token,$expire);return?$this->access_token;}return?false;}/***?刪除驗證數據*?@param?string?$appid*/public?function?resetAuth($appid=''){if?(!$appid)?$appid?=?$this->appid;$this->access_token?=?'';$authname?=?'wechat_access_token'.$appid;S($authname,null);return?true;}/***?微信api不支持中文轉義的json結構?/JSON編碼*?@param?array?$arr*//**static?function?json_encode($arr)?{$parts?=?array?();$is_list?=?false;//Find?out?if?the?given?array?is?a?numerical?array$keys?=?array_keys?(?$arr?);$max_length?=?count?(?$arr?)?-?1;if?(($keys?[0]?===?0)?&&?($keys?[$max_length]?===?$max_length?))?{?//See?if?the?first?key?is?0?and?last?key?is?length?-?1$is_list?=?true;for($i?=?0;?$i?<?count?(?$keys?);?$i?++)?{?//See?if?each?key?correspondes?to?its?positionif?($i?!=?$keys?[$i])?{?//A?key?fails?at?position?check.$is_list?=?false;?//It?is?an?associative?array.break;}}}foreach?(?$arr?as?$key?=>?$value?)?{if?(is_array?(?$value?))?{?//Custom?handling?for?arraysif?($is_list)$parts?[]?=?self::json_encode?(?$value?);?else$parts?[]?=?'"'?.?$key?.?'":'?.?self::json_encode?(?$value?);?}?else?{$str?=?'';if?(!?$is_list)$str?=?'"'?.?$key?.?'":';//Custom?handling?for?multiple?data?typesif?(is_numeric?(?$value?)?&&?$value<2000000000)$str?.=?$value;?//Numberselseif?($value?===?false)$str?.=?'false';?//The?booleanselseif?($value?===?true)$str?.=?'true';else$str?.=?'"'?.?addslashes?(?$value?)?.?'"';?//All?other?things//?:TODO:?Is?there?any?more?datatype?we?should?be?in?the?lookout?for??(Object?)$parts?[]?=?$str;}}$json?=?implode?(?',',?$parts?);if?($is_list)return?'['?.?$json?.?']';?//Return?numerical?JSONreturn?'{'?.?$json?.?'}';?//Return?associative?JSON}**//***?創建菜單*?@param?array?$data?菜單數組數據*?example:*? array?(*? ????'button'?=>?array?(*? ??????0?=>?array?(*? ????????'name'?=>?'掃碼',*? ????????'sub_button'?=>?array?(*? ????????????0?=>?array?(*? ??'key'?=>?'rselfmenu_0_0',??? ?????????????*? ??????????????'name'?=>?'掃碼帶提示','type'?=>?'scancode_waitmsg'*? ????????????),*? ????????????1?=>?array?('key'?=>?'rselfmenu_0_1','name'?=>?'掃碼推事件',*? ??????????????'type'?=>?'scancode_push'?????*? ?????????????*? ????????????)*? ????????),*? ??????),*? ??????1?=>?array?(*? ????????'name'?=>?'發圖',*? ????????'sub_button'?=>?array?(*? ?????????????0?=>?array?(*? ??'key'?=>?'rselfmenu_0_0',??? ?????????????*? ??????????????'name'?=>?'掃碼帶提示','type'?=>?'scancode_waitmsg'*? ????????????),*? ????????????1?=>?array?('key'?=>?'rselfmenu_0_1','name'?=>?'掃碼推事件',*? ??????????????'type'?=>?'scancode_push'?????*? ?????????????*? ????????????)*? ????????),*? ??????),*? ??????2?=>?array?(*? ????????'key'?=>?'rselfmenu_0_1','name'?=>?'掃碼推事件',*? ??????????????'type'?=>?'scancode_push'?*? ??????),*? ????),*? );*?type可以選擇為以下2種*?1、click:點擊推事件*?2、view:跳轉URL*/public?function?createMenu($data){header("Content-type:text/html;charset=utf-8");if?(!$this->access_token?&&?!$this->checkAuth())?return?false;$result?=?$this->http_post(self::API_URL_PREFIX.self::MENU_CREATE_URL.'access_token='.$this->access_token,json_encode($data));if?($result){$json?=?json_decode($result,true); if?(!$json?||?!empty($json['errcode']))?{$this->errCode?=?$json['errcode'];$this->errMsg?=?$json['errmsg'];return?false;}return?true;}return?false;}/***?獲取菜單*?@return?array('menu'=>array(....s))*/public?function?getMenu(){header("Content-type:text/html;charset=utf-8");if?(!$this->access_token?&&?!$this->checkAuth())?return?false;$result?=?$this->http_get(self::API_URL_PREFIX.self::MENU_GET_URL.'access_token='.$this->access_token);if?($result){$json?=?json_decode($result,true);if?(!$json?||?isset($json['errcode']))?{$this->errCode?=?$json['errcode'];$this->errMsg?=?$json['errmsg'];return?false;}return?$json;}return?false;}/***?刪除菜單*?@return?boolean*/public?function?deleteMenu(){header("Content-type:text/html;charset=utf-8");if?(!$this->access_token?&&?!$this->checkAuth())?return?false;$result?=?$this->http_get(self::API_URL_PREFIX.self::MENU_DELETE_URL.'access_token='.$this->access_token);if?($result){$json?=?json_decode($result,true);if?(!$json?||?!empty($json['errcode']))?{$this->errCode?=?$json['errcode'];$this->errMsg?=?$json['errmsg'];return?false;}return?true;}return?false;} }/***?Rolling?Curl?Request?Class*?@author?Ligboy?(ligboy@gamil.com)*?@copyright*?@example***/ class?CurlHttp?{/*?單線程請求設置項?*//*?并發請求設置項?*/private?$limitCount?=?10;?//并發請求數量public?$returninfoswitch?=?false;??//是否返回請求信息,開啟后單項請求返回結果為:array('info'=>請求信息,?'result'=>返回內容,?'error'=>錯誤信息)//私有屬性private?$singlequeue?=?null;private?$rollqueue?=?null;private?$_requstItems?=?null;private?$_callback?=?null;private?$_result;private?$_referer?=?null;private?$_cookies?=?array();private?$_resheader;private?$_reqheader?=?array();private?$_resurl;private?$_redirect_url;private?$referer;private?$_singleoptions?=?array(CURLOPT_RETURNTRANSFER?=>?true,?????????//?return?web?pageCURLOPT_HEADER?????????=>?true,????????//?don't?return?headers //? CURLOPT_FOLLOWLOCATION?=>?true,?????????//?follow?redirectsCURLOPT_NOSIGNAL??????=>true,CURLOPT_ENCODING???????=>?"",???????????//?handle?all?encodingsCURLOPT_USERAGENT??????=>?"",???????????//?who?am?iCURLOPT_AUTOREFERER????=>?true,?????????//?set?referer?on?redirectCURLOPT_CONNECTTIMEOUT?=>?120,??????????//?timeout?on?connectCURLOPT_TIMEOUT????????=>?120,??????????//?timeout?on?responseCURLOPT_MAXREDIRS??????=>?10,???????????//?stop?after?10?redirectsCURLOPT_SSL_VERIFYHOST?=>?0,????????????//?don't?verify?sslCURLOPT_SSL_VERIFYPEER?=>?false,????????//);private?$_rolloptions?=?array(CURLOPT_RETURNTRANSFER?=>?true,?????????//?return?web?pageCURLOPT_HEADER?????????=>?false,????????//?don't?return?headers //? CURLOPT_FOLLOWLOCATION?=>?true,?????????//?follow?redirectsCURLOPT_NOSIGNAL??????=>true,CURLOPT_ENCODING???????=>?"",???????????//?handle?all?encodingsCURLOPT_USERAGENT??????=>?"",???????????//?who?am?iCURLOPT_AUTOREFERER????=>?true,?????????//?set?referer?on?redirectCURLOPT_CONNECTTIMEOUT?=>?120,??????????//?timeout?on?connectCURLOPT_TIMEOUT????????=>?120,??????????//?timeout?on?responseCURLOPT_MAXREDIRS??????=>?10,???????????//?stop?after?10?redirectsCURLOPT_SSL_VERIFYHOST?=>?0,????????????//?don't?verify?sslCURLOPT_SSL_VERIFYPEER?=>?false,????????//);function?singleInit($options?=?array())?{if?(!$this->singlequeue)?{$this->singlequeue?=?curl_init();}if?($options)?{$this->_singleoptions?=?array_merge($this->_singleoptions,?$options);}}function?rollInit($options?=?array())?{if(!$this->rollqueue){$this->rollqueue?=?curl_multi_init();}if?($options)?{$this->_rolloptions?=?array_merge($this->_rolloptions,?$options);}}/***?@name?返回Header數組*?@param?resource?$ch*?@param?$result*?@return?string*/private?function?getResRawHeader($ch,?$result)?{$ch_info?=?curl_getinfo($ch);$header_size?=?$ch_info["header_size"];$rawheader?=?substr($result,?0,?$ch_info['header_size']);return?$rawheader;}/***?@name?返回Header數組*?@param?resource?$ch*?@param?$result*?@return?string*/private?function?getResHeader($ch,?$result)?{$header?=?array();$rawheader?=?$this->getResRawHeader($ch,?$result);if(preg_match_all('/([^:\s]+):?(.*)/i',?$rawheader,?$header_match)){for($i=0;$i<count($header_match[0]);$i++){$header[$header_match[1][$i]]?=?$header_match[2][$i];}}return?$header;}/***?@name?返回網頁主體內容*?@param?resource?$ch*?@param?$result*?@return?string?網頁主體內容*/private?function?getResBody($ch,?$result)?{$ch_info?=?curl_getinfo($ch);$body?=?substr($result,?-$ch_info['download_content_length']);return?$body;}/***?@name?返回網頁主體內容*?@param?resource?$ch*?@param?$result*?@return?array?網頁主體內容*/private?function?getResCookies($ch,?$result)?{$rawheader?=?$this->getResRawHeader($ch,?$result);$cookies?=?array();if(preg_match_all('/Set-Cookie:(?:\s*)([^=]*?)=([^\;]*?);/i',?$rawheader,?$cookie_match)){for($i=0;$i<count($cookie_match[0]);$i++){$cookies[$cookie_match[1][$i]]?=?$cookie_match[2][$i];}}return?$cookies;}private?function?setReqCookies($ch,?$reqcookies?=?array())?{$reqCookiesString?=?"";if(!empty($reqcookies)){if(is_array($reqcookies)){foreach?($reqcookies?as?$key?=>?$val){$reqCookiesString?.=??$key."=".$val.";?";}curl_setopt($ch,?CURLOPT_COOKIE,?$reqCookiesString);}}elseif(!empty($this->_cookies))?{foreach?($this->_cookies?as?$key?=>?$val){$reqCookiesString?.=??$key."=".$val.";?";}curl_setopt($ch,?CURLOPT_COOKIE,?$reqCookiesString);}}private?function?setResCookies($ch)?{if(!empty($reqcookies)&&is_array($reqcookies)){$this->_cookies?=?array_merge($this->_cookies,?$reqcookies);}}/***?@param?unknown?$url*?@param?mixed?$postfields*?@param?string?$referer*?@param?array?$reqcookies*?@param?array?$reqheader*?@return?unknown*/function?post($url,?$postfields=null,?$referer=null,?$reqcookies=null,?$reqheader=array()){$this->singlequeue?=?curl_init($url);$options?=?array(CURLOPT_RETURNTRANSFER?=>?true,?????????//?return?web?pageCURLOPT_HEADER?????????=>?true,????????//?don't?return?headers //? CURLOPT_FOLLOWLOCATION?=>?true,?????????//?follow?redirectsCURLOPT_ENCODING???????=>?"",???????????//?handle?all?encodingsCURLOPT_USERAGENT??????=>?"",?????//?who?am?iCURLOPT_AUTOREFERER????=>?true,?????????//?set?referer?on?redirectCURLOPT_CONNECTTIMEOUT?=>?120,??????????//?timeout?on?connectCURLOPT_TIMEOUT????????=>?120,??????????//?timeout?on?responseCURLOPT_MAXREDIRS??????=>?10,???????????//?stop?after?10?redirectsCURLOPT_POST????????????=>?true,????????????//?i?am?sending?post?dataCURLOPT_SSL_VERIFYHOST?=>?0,????????????//?don't?verify?sslCURLOPT_SSL_VERIFYPEER?=>?false,????????//);curl_setopt_array($this->singlequeue,?$options);curl_setopt($this->singlequeue,?CURLOPT_POSTFIELDS,?$postfields);???//?this?are?my?post?varsif($referer){curl_setopt($this->singlequeue,?CURLOPT_REFERER,?$referer);}elseif?($this->referer){curl_setopt($this->singlequeue,?CURLOPT_REFERER,?$this->referer);}$this->setReqheader($this->singlequeue,?$reqheader);$this->setReqCookies($this->singlequeue,?$reqcookies);$result?=?curl_exec($this->singlequeue);$resCookies?=?$this->getResCookies($this->singlequeue,?$result);;if?(is_array($resCookies)&&!empty($resCookies))?{$this->_cookies?=?array_merge($this->_cookies?,$resCookies);}$resHeader?=?$this->getResHeader($this->singlequeue,?$result);if?(is_array($resHeader)&&!empty($resHeader))?{$this->_resheader?=?$resHeader;}$this->_result?=?$this->getResBody($this->singlequeue,?$result);curl_close($this->singlequeue);$this->singlequeue?=?null;return?$this->_result;}/***?@param?unknown?$url*?@param?unknown?$referer*?@param?null?$reqcookies*?@param?array?$reqheader*?@return?unknown*/function?get($url,?$referer=null,?$reqcookies=null,?$reqheader=array()){$this->singlequeue?=?curl_init($url);$options?=?array(CURLOPT_RETURNTRANSFER?=>?true,?????????//?return?web?pageCURLOPT_HEADER?????????=>?true,????????//?don't?return?headers //? CURLOPT_FOLLOWLOCATION?=>?true,?????????//?follow?redirectsCURLOPT_ENCODING???????=>?"",???????????//?handle?all?encodingsCURLOPT_USERAGENT??????=>?"",?????//?who?am?iCURLOPT_AUTOREFERER????=>?true,?????????//?set?referer?on?redirectCURLOPT_CONNECTTIMEOUT?=>?120,??????????//?timeout?on?connectCURLOPT_TIMEOUT????????=>?120,??????????//?timeout?on?responseCURLOPT_MAXREDIRS??????=>?10,???????????//?stop?after?10?redirectsCURLOPT_POST????????????=>?false,????????????//?i?am?sending?post?dataCURLOPT_SSL_VERIFYHOST?=>?0,????????????//?don't?verify?sslCURLOPT_SSL_VERIFYPEER?=>?false,????????//CURLOPT_REFERER????????=>$referer,);curl_setopt_array($this->singlequeue,?$options);if($referer){curl_setopt($this->singlequeue,?CURLOPT_REFERER,?$referer);}elseif?($this->referer){curl_setopt($this->singlequeue,?CURLOPT_REFERER,?$this->referer);}$this->setReqheader($this->singlequeue,?$reqheader);$this->setReqCookies($this->singlequeue,?$reqcookies);$result?=?curl_exec($this->singlequeue);$resCookies?=?$this->getResCookies($this->singlequeue,?$result);if?(is_array($resCookies)&&!empty($resCookies))?{$this->_cookies?=?array_merge($this->_cookies?,$resCookies);}$resHeader?=?$this->getResHeader($this->singlequeue,?$result);if?(is_array($resHeader))?{$this->_resheader?=?$resHeader;}$this->_result?=?$this->getResBody($this->singlequeue,?$result);curl_close($this->singlequeue);$this->singlequeue?=?null;return?$this->_result;}/***?并發行的curl方法*?@param?unknown?$requestArray*?@param?string?$callback*?@return?multitype:multitype:*/function?rollRequest($requestArray,?$callback=""){$this->_requstItems?=?$requestArray;$requestArrayKeys?=?array_keys($requestArray);$this->rollqueue?=?curl_multi_init();$map?=?array();for?($i=0;$i<$this->limitCount?&&?!empty($requestArrayKeys);$i++){$keyvalue?=?array_shift($requestArrayKeys);$this->addToRollQueue(?$requestArray,?$keyvalue,?$map?);}$responses?=?array();do?{while?(($code?=?curl_multi_exec($this->rollqueue,?$active))?==?CURLM_CALL_MULTI_PERFORM)?;if?($code?!=?CURLM_OK)?{?break;?}//?找到剛剛完成的任務句柄while?($done?=?curl_multi_info_read($this->rollqueue))?{//?處理當前句柄的信息、錯誤、和返回內容$info?=?curl_getinfo($done['handle']);$error?=?curl_error($done['handle']);if?($this->_callback){//調用callback函數處理當前句柄的返回內容,callback函數參數有:(返回內容,?隊列id)$result?=?call_user_func($this->_callback,?curl_multi_getcontent($done['handle']),?$map[(string)?$done['handle']]);}else{//如果callback為空,直接返回內容$result?=?curl_multi_getcontent($done['handle']);}if?($this->returninfoswitch)?{$responses[$map[(string)?$done['handle']]]?=?compact('info',?'error',?'result');}else{$responses[$map[(string)?$done['handle']]]?=?$result;}//?從隊列里移除上面完成處理的句柄curl_multi_remove_handle($this->rollqueue,?$done['handle']);curl_close($done['handle']);if?(!empty($requestArrayKeys)){$addkey?=?array_shift($requestArrayKeys);$this->addToRollQueue?(?$requestArray,?$addkey,?$map?);}}//?Block?for?data?in?/?output;?error?handling?is?done?by?curl_multi_execif?($active?>?0)?{curl_multi_select($this->rollqueue,?0.5);}}?while?($active);curl_multi_close($this->rollqueue);$this->rollqueue?=?null;return?$responses;}/***?@param?requestArray*?@param?map*?@param?keyvalue*/private?function?addToRollQueue($requestArray,?$keyvalue,?&$map)?{$ch?=?curl_init();curl_setopt_array($ch,?$this->_rolloptions);//檢查提交方式,并設置對應的設置,為空的話默認采用get方式if?("post"?===?$requestArray[$keyvalue]['method']){curl_setopt($ch,?CURLOPT_POST,?true);curl_setopt($ch,?CURLOPT_POSTFIELDS,?$requestArray[$keyvalue]['postfields']);}else{curl_setopt($ch,?CURLOPT_HTTPGET,?true);}if($requestArray[$keyvalue]['referer']){curl_setopt($ch,?CURLOPT_REFERER,?$requestArray[$keyvalue]['referer']);}elseif?($this->referer){curl_setopt($ch,?CURLOPT_REFERER,?$this->referer);}$this->setReqheader($ch,?$requestArray[$keyvalue]['header']);//cookies設置$this->setReqCookies($ch,?$requestArray[$keyvalue]['cookies']);curl_setopt($ch,?CURLOPT_URL,?$requestArray[$keyvalue]['url']);curl_setopt($ch,?CURLOPT_REFERER,?$requestArray[$keyvalue]['referer']);curl_multi_add_handle($this->rollqueue,?$ch);$map[(string)?$ch]?=?$keyvalue;}/***?返回當前并行數*?@return?the?$limitCount*/public?function?getRollLimitCount()?{return?$this->limitCount;}/***?設置并發性請求數量*?@param?number?$limitCount*?@return?$this*/public?function?setRollLimitCount($limitCount)?{$this->limitCount?=?$limitCount;return?$this;}/***?設置回調函數*?@param?field_type?$_callback*?@return?$this*/public?function?setCallback($_callback)?{$this->_callback?=?$_callback;return?$this;}public?function?getResult()?{return?$this->_result;}public?function?getRawHeader()?{return?$this->_resheader;}public?function?getCookies()?{return?$this->_cookies;}public?function?setCookies($_cookies)?{$this->_cookies?=?$_cookies;return?$this;}/***?@param?$header*?@return?$this*/public?function?setHeader($header)?{$this->_reqheader?=?array_merge($this->_reqheader,?$header);return?$this;}/***?@param?resource?$ch*?@param?array?$reqheader*?@return?$this*/private?function?setReqheader($ch,?$reqheader)?{$reqheader?=?array_merge($this->_reqheader,?$reqheader);if?(is_array($reqheader))?{$rawReqHeader?=?array();foreach?($reqheader?as?$key?=>?$value){$rawReqHeader[]?=?"$key:?$value";}curl_setopt($ch,?CURLOPT_HTTPHEADER,?$rawReqHeader);$this->_reqheader?=?array();}return?$this;} }/***?error?code*?僅用作類內部使用,不用于官方API接口的errCode碼*/ class?ErrorCode {public?static?$OK?=?0;public?static?$ValidateSignatureError?=?40001;public?static?$ParseXmlError?=?40002;public?static?$ComputeSignatureError?=?40003;public?static?$IllegalAesKey?=?40004;public?static?$ValidateAppidError?=?40005;public?static?$EncryptAESError?=?40006;public?static?$DecryptAESError?=?40007;public?static?$IllegalBuffer?=?40008;public?static?$EncodeBase64Error?=?40009;public?static?$DecodeBase64Error?=?40010;public?static?$GenReturnXmlError?=?40011;public?static?$errCode=array('0'=>'請求成功','40001'=>'驗證失敗','40002'=>'不合法的憑證類型','40003'=>'不合法的OpenID','40004'=>'不合法的媒體文件類型','40005'=>'不合法的文件類型','40006'=>'不合法的文件大小','40007'=>'不合法的媒體文件id','40008'=>'不合法的消息類型','40009'=>'不合法的圖片文件大小','40010'=>'不合法的語音文件大小','40011'=>'不合法的視頻文件大小','40012'=>'不合法的縮略圖文件大小','40013'=>'不合法的APPID','40014'=>'不合法的access_token','40015'=>'不合法的菜單類型','40016'=>'不合法的按鈕個數','40018'=>'不合法的按鈕名字長度','40019'=>'不合法的按鈕KEY長度','40020'=>'不合法的按鈕URL長度','40021'=>'不合法的菜單版本號','40022'=>'不合法的子菜單級數','40023'=>'不合法的子菜單按鈕個數','40024'=>'不合法的子菜單按鈕類型','40025'=>'不合法的子菜單按鈕名字長度','40026'=>'不合法的子菜單按鈕KEY長度','40027'=>'不合法的子菜單按鈕URL長度','40028'=>'不合法的自定義菜單使用用戶','40029'=>'access_token超時','40030'=>'refresh_token超時','40035'=>'不合法的參數','40038'=>'不合法的請求格式','40039'=>'不合法的URL長度','40050'=>'不合法的分組id','40051'=>'分組名字不合法','40052'=>'已有重復的分組名稱','40053'=>'不存在的分組名','40054'=>'不允許對黑名單分組群發','40998'=>'未授權的API','40999'=>'非法IP訪問','41001'=>'缺少access_token參數','41002'=>'缺少appid參數','41003'=>'缺少refresh_token參數','41004'=>'缺少secret參數','41005'=>'缺少多媒體文件數據','41006'=>'缺少media_id參數','41007'=>'缺少子菜單數據','41009'=>'缺少openid','42001'=>'access_token超時','42008'=>'用戶ID不一致','42009'=>'APPID不一致','43001'=>'需要GET請求','43002'=>'需要POST請求','43003'=>'需要HTTPS請求','43004'=>'需要接收者關注','44001'=>'多媒體文件為空','44002'=>'POST的數據包為空','44003'=>'圖文消息內容為空','44004'=>'文本消息內容為空','45001'=>'多媒體文件大小超過限制','45002'=>'消息內容超過限制','45003'=>'標題字段超過限制','45004'=>'描述字段超過限制','45005'=>'鏈接字段超過限制','45006'=>'圖片鏈接字段超過限制','45007'=>'語音播放時間超過限制','45008'=>'圖文消息超過限制','45009'=>'接口調用超過限制','45010'=>'創建菜單個數超過限制','45016'=>'系統分組,不允許修改','45017'=>'分組名字過長','45018'=>'分組數量超過上限','45019'=>'分組名稱為空','45020'=>'不存在的分組','45021'=>'群發消息量超過限制','45999'=>'接口調用超過每秒限制','46001'=>'不存在媒體數據','46002'=>'不存在的菜單版本','46003'=>'不存在的菜單數據','46004'=>'不存在的用戶','47001'=>'解析JSON/XML內容錯誤','48001'=>'api功能未授權','49000'=>'創建投票活動失敗(不合法的請求消息)','49001'=>'不合法的投票標題','49002'=>'不合法的投票說明','49003'=>'不合法的投票結果類型','49004'=>'不合法的投票選項個數','49005'=>'不合法的投票選項','49006'=>'不合法的投票選項類型','49007'=>'不合法的投票選擇范圍','49008'=>'不合法的投票截止時間','49009'=>'不合法的投票限制類型','49010'=>'不存在的投票活動','49011'=>'投票結果正在處理','49012'=>'投票已結束','49013'=>'投票未結束','50001'=>'該用戶沒有關注此公眾號','50002'=>'該用戶不允許公眾號獲取他的好友關系','50003'=>'識別條形碼失敗','50005'=>'無法識別該條形碼','50006'=>'無法打開所提供的圖片鏈接地址','50007'=>'next_openid未關注此公眾號','50008'=>'生成二維碼失敗(錯誤的請求內容)','50009'=>'生成二維碼失敗','50010'=>'不合法的ticket','51001'=>'不合法的mobile','52001'=>'無權訪問該動態或該動態不存在','52029'=>'發送的內容涉及敏感詞','60001'=>'請求參數中缺少key','60002'=>'公眾號不存在','60003'=>'公眾號狀態錯誤','60004'=>'用戶在黑名單中');public?static?function?getErrText($err)?{if?(isset(self::$errCode[$err]))?{return?self::$errCode[$err];}else?{return?false;};} }轉載于:https://my.oschina.net/cometlj/blog/367392
總結
- 上一篇: 推荐一个工具MediaCoder
- 下一篇: PCB板中静电放电的设计与解决方法