api接口教程(php).doc_第1页
api接口教程(php).doc_第2页
api接口教程(php).doc_第3页
api接口教程(php).doc_第4页
api接口教程(php).doc_第5页
已阅读5页,还剩24页未读 继续免费阅读

下载本文档

版权说明:本文档由用户提供并上传,收益归属内容提供方,若内容存在侵权,请进行举报或认领

文档简介

urlencode($key) ,num=urlencode($num) ,show=urlencode($show) ,);foreach($fields as $key=$value)$fields_string .= $key.=.$value.& ;/把变量组装成username=mayuchao&password=123456&成功了mayuchao密码laoma 这个格式rtrim($fields_string ,&) ; /从末端开始去掉删除多余&符号$ch = curl_init() ; / 开启一个curl对话curl_setopt($ch, CURLOPT_URL,$url) ; /把要对话的url地址设置好curl_setopt($ch, CURLOPT_POST,count($fields) ; /把要发送的变量数量设置好curl_setopt($ch, CURLOPT_POSTFIELDS,$fields_string) ; /把要post的变量url组装好化后设置好curl_exec($ch) ; /执行上面设置好的一个curl操作,把变量数据发送完后,返回的是ok.php页面获得post变量执行后的结果curl_close($ch) ; /关闭curl对话?secretKey;foreach ($params as $k = $v)if( != substr($v, 0, 1)$stringToBeSigned .= $k$v;unset($k, $v);$stringToBeSigned .= $this-secretKey;return strtoupper(md5($stringToBeSigned);protected function curl($url, $postFields = null)$ch = curl_init();curl_setopt($ch, CURLOPT_URL, $url);curl_setopt($ch, CURLOPT_FAILONERROR, false);curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);if (is_array($postFields) & 0 $v)if( != substr($v, 0, 1)/判断是不是文件上传$postBodyString .= $k= . urlencode($v) . &; else /文件上传用multipart/form-data,否则用www-form-urlencoded$postMultipart = true;unset($k, $v);curl_setopt($ch, CURLOPT_POST, true);if ($postMultipart)curl_setopt($ch, CURLOPT_POSTFIELDS, $postFields);elsecurl_setopt($ch, CURLOPT_POSTFIELDS, substr($postBodyString,0,-1);$reponse = curl_exec($ch);if (curl_errno($ch)throw new Exception(curl_error($ch),0);else$httpStatusCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);if (200 != $httpStatusCode)throw new Exception($reponse,$httpStatusCode);curl_close($ch);return $reponse;protected function logCommunicationError($apiName, $requestUrl, $errorCode, $responseTxt)$localIp = isset($_SERVERSERVER_ADDR) ? $_SERVERSERVER_ADDR : CLI;$logger = new LtLogger;$logger-conflog_file = rtrim(TOP_SDK_WORK_DIR, /) . / . logs/top_comm_err_ . $this-appkey . _ . date(Y-m-d) . .log;$logger-confseparator = _;$logData = array(date(Y-m-d H:i:s),$apiName,$this-appkey,$localIp,PHP_OS,$this-sdkVersion,$requestUrl,$errorCode,str_replace(n,$responseTxt);$logger-log($logData);public function execute($request, $session = null)if($this-checkRequest) try $request-check(); catch (Exception $e) $result-code = $e-getCode();$result-msg = $e-getMessage();return $result;/组装系统参数$sysParamsapp_key = $this-appkey;$sysParamsv = $this-apiVersion;$sysParamsformat = $this-format;$sysParamssign_method = $this-signMethod;$sysParamsmethod = $request-getApiMethodName();$sysParamstimestamp = date(Y-m-d H:i:s);$sysParamspartner_id = $this-sdkVersion;if (null != $session)$sysParamssession = $session;/获取业务参数$apiParams = $request-getApiParas();/签名$sysParamssign = $this-generateSign(array_merge($apiParams, $sysParams);/系统参数放入GET请求串$requestUrl = $this-gatewayUrl . ?;foreach ($sysParams as $sysParamKey = $sysParamValue)$requestUrl .= $sysParamKey= . urlencode($sysParamValue) . &;$requestUrl = substr($requestUrl, 0, -1);/发起HTTP请求try$resp = $this-curl($requestUrl, $apiParams);catch (Exception $e)$this-logCommunicationError($sysParamsmethod,$requestUrl,HTTP_ERROR_ . $e-getCode(),$e-getMessage();$result-code = $e-getCode();$result-msg = $e-getMessage();return $result;/解析TOP返回结果$respWellFormed = false;if (json = $this-format)$respObject = json_decode($resp);if (null != $respObject)$respWellFormed = true;foreach ($respObject as $propKey = $propValue)$respObject = $propValue;else if(xml = $this-format)$respObject = simplexml_load_string($resp);if (false != $respObject)$respWellFormed = true;/返回的HTTP文本不是标准JSON或者XML,记下错误日志if (false = $respWellFormed)$this-logCommunicationError($sysParamsmethod,$requestUrl,HTTP_RESPONSE_NOT_WELL_FORMED,$resp);$result-code = 0;$result-msg = HTTP_RESPONSE_NOT_WELL_FORMED;return $result;/如果TOP返回了错误码,记录到业务错误日志中if (isset($respObject-code)$logger = new LtLogger;$logger-conflog_file = rtrim(TOP_SDK_WORK_DIR, /) . / . logs/top_biz_err_ . $this-appkey . _ . date(Y-m-d) . .log;$logger-log(array(date(Y-m-d H:i:s),$resp);return $respObject;public function exec($paramsArray)if (!isset($paramsArraymethod)trigger_error(No api name passed);$inflector = new LtInflector;$inflector-confseparator = .;$requestClassName = ucfirst($inflector-camelize(substr($paramsArraymethod, 7) . Request;if (!class_exists($requestClassName)trigger_error(No such api: . $paramsArraymethod);$session = isset($paramsArraysession) ? $paramsArraysession : null;$req = new $requestClassName;foreach($paramsArray as $paraKey = $paraValue)$inflector-confseparator = _;$setterMethodName = $inflector-camelize($paraKey);$inflector-confseparator = .;$setterMethodName = set . $inflector-camelize($setterMethodName);if (method_exists($req, $setterMethodName)$req-$setterMethodName($paraValue);return $this-execute($req, $session);?以下为引用的内容:/ 创建两个cURL资源$ch1 = curl_init();$ch2 = curl_init();/ 指定URL和适当的参数curl_setopt($ch1, CURLOPT_URL, /);curl_setopt($ch1, CURLOPT_HEADER, 0);curl_setopt($ch2, CURLOPT_URL, /);curl_setopt($ch2, CURLOPT_HEADER, 0);/ 创建cURL批处理句柄$mh = curl_multi_init();/ 加上前面两个资源句柄curl_multi_add_handle($mh,$ch1);curl_multi_add_handle($mh,$ch2);/ 预定义一个状态变量$active = null;/ 执行批处理do $mrc = curl_multi_exec($mh, $active); while ($mrc = CURLM_CALL_MULTI_PERFORM);while ($active & $mrc = CURLM_OK) if (curl_multi_select($mh) != -1) do $mrc = curl_multi_exec($mh, $active); while ($mrc = CURLM_CALL_MULTI_PERFORM); / 关闭各个句柄curl_multi_remove_handle($mh, $ch1);curl_multi_remove_handle($mh, $ch2);curl_multi_close($mh); 这里要做的就是打开多个cURL句柄并指派给一个批处理句柄。然后你就只需在一个while循环里等它执行完毕。这个示例中有两个主要循环。第一个 do-while 循环重复调用 curl_multi_exec() 。这个函数是无隔断(non-blocking)的,但会尽可能少地执行。它返回一个状态值,只要这个值等于常量 CURLM_CALL_MULTI_PERFORM ,就代表还有一些刻不容缓的工作要做(例如,把对应URL的http头信息发送出去)。也就是说,我们需要不断调用该函数,直到返回值发生改变。而接下来的 while 循环,只在 $active 变量为 true 时继续。这一变量之前作为第二个参数传给了 curl_multi_exec() ,代表只要批处理句柄中是否还有活动连接。接着,我们调用 curl_multi_select() ,在活动连接(例如接受服务器响应)出现之前,它都是被“屏蔽”的。这个函数成功执行后,我们又会进入另一个 do-while 循环,继续下一条URL?php/*Snoopy - the PHP net clientAuthor: Monte Ohrt Copyright (c): 1999-2000 ispi, all rights reservedVersion: 1.01 * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USAYou may contact the author of Snoopy by e-mail at:Or, write to:Monte OhrtCTO, ispi237 S. 70th suite 220Lincoln, NE 68510The latest version of Snoopy can be obtained from:/*/class Snoopy/* Public variables */* user definable vars */var $host=;/ host name we are connecting tovar $port=80;/ port we are connecting tovar $proxy_host=;/ proxy host to usevar $proxy_port=;/ proxy port to usevar $proxy_user=;/ proxy user to usevar $proxy_pass=;/ proxy password to usevar $agent=Snoopy v1.2.3;/ agent we masquerade asvar$referer=;/ referer info to passvar $cookies=array();/ array of cookies to pass/ $cookiesusername=joe;var$rawheaders=array();/ array of raw headers/ $rawheadersContent-type=text/html;var $maxredirs=5;/ http redirection depth maximum. 0 = disallowvar $lastredirectaddr=;/ contains address of last redirected addressvar$offsiteok=true;/ allows redirection off-sitevar $maxframes=0;/ frame content depth maximum. 0 = disallowvar $expandlinks=true;/ expand links to fully qualified URLs./ this only applies to fetchlinks()/ submitlinks(), and submittext()var $passcookies=true;/ pass set cookies back through redirects/ NOTE: this currently does not respect/ dates, domains or paths.var$user=;/ user for http authenticationvar$pass=;/ password for http authentication/ http accept typesvar $accept=image/gif, image/x-xbitmap, image/jpeg, image/pjpeg, */*;var $results=;/ where the content is putvar $error=;/ error messages sent herevar$response_code=;/ response code returned from servervar$headers=array();/ headers returned from server sent herevar$maxlength=500000;/ max return data length (body)var $read_timeout=0;/ timeout on read operations, in seconds/ supported only since PHP 4 Beta 4/ set to 0 to disallow timeoutsvar $timed_out=false;/ if a read operation timed outvar$status=0;/ http request statusvar $temp_dir=/tmp;/ temporary directory that the webserver/ has permission to write to./ under Windows, this should be C:tempvar$curl_path=/usr/local/bin/curl;/ Snoopy will use cURL for fetching/ SSL content if a full system path to/ the cURL binary is supplied here./ set to false if you do not have/ cURL installed. See http:/curl.haxx.se/ for details on installing cURL./ Snoopy does *not* use the cURL/ library functions built into php,/ as these functions are not stable/ as of this Snoopy release./* Private variables */var$_maxlinelen=4096;/ max line length (headers)var $_httpmethod=GET;/ default http request methodvar $_httpversion=HTTP/1.0;/ default http request versionvar $_submit_method=POST;/ default submit methodvar $_submit_type=application/x-www-form-urlencoded;/ default submit typevar $_mime_boundary= ;/ MIME boundary for multipart/form-data submit typevar $_redirectaddr=false;/ will be set if page fetched is a redirectvar $_redirectdepth=0;/ increments on an http redirectvar $_frameurls= array();/ frame src urlsvar $_framedepth=0;/ increments on frame depthvar $_isproxy=false;/ set if using a proxy servervar $_fp_timeout=30;/ timeout for socket connection/*=Function:fetchPurpose:fetch the contents of a web page(and possibly other protocols in thefuture like ftp, nntp, gopher, etc.)Input:$URIthe location of the page to fetchOutput:$this-resultsthe output text from the fetch=*/function fetch($URI)/preg_match(|(:+):/(:/+)(:d+)*(.*)|,$URI,$URI_PARTS);$URI_PARTS = parse_url($URI);if (!empty($URI_PARTSuser)$this-user = $URI_PARTSuser;if (!empty($URI_PARTSpass)$this-pass = $URI_PARTSpass;if (empty($URI_PARTSquery)$URI_PARTSquery = ;if (empty($URI_PARTSpath)$URI_PARTSpath = ;switch(strtolower($URI_PARTSscheme)case http:$this-host = $URI_PARTShost;if(!empty($URI_PARTSport)$this-port = $URI_PARTSport;if($this-_connect($fp)if($this-_isproxy)/ using proxy, send entire URI$this-_httprequest($URI,$fp,$URI,$this-_httpmethod);else$path = $URI_PARTSpath.($URI_PARTSquery ? ?.$URI_PARTSquery : );/ no proxy, send only the path$this-_httprequest($path, $fp, $URI, $this-_httpmethod);$this-_disconnect($fp);if($this-_redirectaddr)/* url was redirected, check if weve hit the max depth */if($this-maxredirs $this-_redirectdepth)/ only follow redirect if its on this site, or offsiteok is trueif(preg_match(|http:/.preg_quote($this-host).|i,$this-_redirectaddr) | $this-offsiteok)/* follow the redirect */$this-_redirectdepth+;$this-lastredirectaddr=$this-_redirectaddr;$this-fetch($this-_redirectaddr);if($this-_framedepth maxframes & count($this-_frameurls) 0)$frameurls = $this-_frameurls;$this-_frameurls = array();while(list(,$frameurl) = each($frameurls)if($this-_framedepth maxframes)$this-fetch($frameurl);$this-_framedepth+;elsebreak;elsereturn false;return true;break;case https:if(!$this-curl_path)return false;if(function_exists(is_executable) if (!is_executable($this-curl_path) return false;$this-host = $URI_PARTShost;if(!empty($URI_PARTSport)$this-port = $URI_PARTSport;if($this-_isproxy)/ using proxy, send entire URI$this-_httpsrequest($URI,$URI,$this-_httpmethod);else$path = $URI_PARTSpath.($URI_PARTSquery ? ?.$URI_PARTSquery : );/ no proxy, send only the path$this-_httpsrequest($path, $URI, $this-_httpmethod);if($this-_redirectaddr)/* url was redirected, check if weve hit the max depth */if($this-maxredirs $this-_redirectdepth)/ only follow redirect if its on this site, or offsiteok is trueif(preg_match(|http:/.preg_quote($this-host).|i,$this-_redirectaddr) | $this-offsiteok)/* follow the redirect */$this-_red

温馨提示

  • 1. 本站所有资源如无特殊说明,都需要本地电脑安装OFFICE2007和PDF阅读器。图纸软件为CAD,CAXA,PROE,UG,SolidWorks等.压缩文件请下载最新的WinRAR软件解压。
  • 2. 本站的文档不包含任何第三方提供的附件图纸等,如果需要附件,请联系上传者。文件的所有权益归上传用户所有。
  • 3. 本站RAR压缩包中若带图纸,网页内容里面会有图纸预览,若没有图纸预览就没有图纸。
  • 4. 未经权益所有人同意不得将文件中的内容挪作商业或盈利用途。
  • 5. 人人文库网仅提供信息存储空间,仅对用户上传内容的表现方式做保护处理,对用户上传分享的文档内容本身不做任何修改或编辑,并不能对任何下载内容负责。
  • 6. 下载文件中如有侵权或不适当内容,请与我们联系,我们立即纠正。
  • 7. 本站不保证下载资源的准确性、安全性和完整性, 同时也不承担用户因使用这些下载资源对自己和他人造成任何形式的伤害或损失。

评论

0/150

提交评论