api接口教程php.docx
《api接口教程php.docx》由会员分享,可在线阅读,更多相关《api接口教程php.docx(63页珍藏版)》请在冰豆网上搜索。
api接口教程php
php
/*************************************************
5PKAPI框架设计
ClientApi.php页面把变量post到service.php页面中
//简单的客户端调用服务端serviceapi接口的示例
/*
*例如客服端通过网址这样传值
http:
//www.szduomei_
*key由系统分发的key
*num要查询的然后通过该数据返回值
*show返回的数据例如:
1为josn,2为xml,3为html等
*/
/*************************************************/
//客户端调用API测试
$url='http:
//localhost/api/ServeiceAPI.php';
$key=2008214209;//需要post到ok.php页面的变量
$num="laoma";
$show=1;
$fields=array();//把所有变量进行数组化保存到数组fields中
'key'=>urlencode($key),
'num'=>urlencode($num),
'show'=>urlencode($show),
);
foreach($fieldsas$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对话
?
>
//简单的服务端提供api示例
*例如通过网址这样传值
$key=$_POST['key'];//获取传来的变量key
$num=$_POST['num'];//获取传来的变量knum
$show=$_POST['show'];//获取传来的变量show
functioncheckkey($key,$show)
if($key==2008214209)
returnget_data($num);
else
if($show==1)
return'josn数据';
elseif($show==2)
return'xml';
return'默认的格式';
if(!
empty($key))//简单验证key
checkkey($key,$show);
//检查key的有效性
//返回通过url过来的值查找对应的数据
functionget_data($num){
echo$key;
classTopClient
public$appkey;
public$secretKey;
public$gatewayUrl="
public$format="xml";
/**是否打开入参check**/
public$checkRequest=true;
protected$signMethod="md5";
protected$apiVersion="2.0";
protected$sdkVersion="top-sdk-php-20110909";
protectedfunctiongenerateSign($params)
ksort($params);
$stringToBeSigned=$this->secretKey;
foreach($paramsas$k=>$v)
if("@"!
=substr($v,0,1))
$stringToBeSigned.="$k$v";
unset($k,$v);
$stringToBeSigned.=$this->secretKey;
returnstrtoupper(md5($stringToBeSigned));
protectedfunctioncurl($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{$postBodyString="";$postMultipart=false;foreach($postFieldsas$k=>$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);}else{curl_setopt($ch,CURLOPT_POSTFIELDS,substr($postBodyString,0,-1));}}$reponse=curl_exec($ch);if(curl_errno($ch)){thrownewException(curl_error($ch),0);}else{$httpStatusCode=curl_getinfo($ch,CURLINFO_HTTP_CODE);if(200!==$httpStatusCode){thrownewException($reponse,$httpStatusCode);}}curl_close($ch);return$reponse;}protectedfunctionlogCommunicationError($apiName,$requestUrl,$errorCode,$responseTxt){$localIp=isset($_SERVER["SERVER_ADDR"])?$_SERVER["SERVER_ADDR"]:"CLI";$logger=newLtLogger;$logger->conf["log_file"]=rtrim(TOP_SDK_WORK_DIR,'\\/').'/'."logs/top_comm_err_".$this->appkey."_".date("Y-m-d").".log";$logger->conf["separator"]="^_^";$logData=array(date("Y-m-dH:i:s"),$apiName,$this->appkey,$localIp,PHP_OS,$this->sdkVersion,$requestUrl,$errorCode,str_replace("\n","",$responseTxt));$logger->log($logData);}publicfunctionexecute($request,$session=null){if($this->checkRequest){try{$request->check();}catch(Exception$e){$result->code=$e->getCode();$result->msg=$e->getMessage();return$result;}}//组装系统参数$sysParams["app_key"]=$this->appkey;$sysParams["v"]=$this->apiVersion;$sysParams["format"]=$this->format;$sysParams["sign_method"]=$this->signMethod;$sysParams["method"]=$request->getApiMethodName();$sysParams["timestamp"]=date("Y-m-dH:i:s");$sysParams["partner_id"]=$this->sdkVersion;if(null!=$session){$sysParams["session"]=$session;}//获取业务参数$apiParams=$request->getApiParas();//签名$sysParams["sign"]=$this->generateSign(array_merge($apiParams,$sysParams));//系统参数放入GET请求串$requestUrl=$this->gatewayUrl."?";foreach($sysParamsas$sysParamKey=>$sysParamValue){$requestUrl.="$sysParamKey=".urlencode($sysParamValue)."&";}$requestUrl=substr($requestUrl,0,-1);//发起HTTP请求try{$resp=$this->curl($requestUrl,$apiParams);}catch(Exception$e){$this->logCommunicationError($sysParams["method"],$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=$resp);if(null!==$respObject){$respWellFormed=true;foreach($respObjectas$propKey=>$propValue){$respObject=$propValue;}}}elseif("xml"==$this->format){$respObject=@simplexml_load_string($resp);if(false!==$respObject){$respWellFormed=true;}}//返回的HTTP文本不是标准JSON或者XML,记下错误日志if(false===$respWellFormed){$this->logCommunicationError($sysParams["method"],$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=newLtLogger;$logger->conf["log_file"]=rtrim(TOP_SDK_WORK_DIR,'\\/').'/'."logs/top_biz_err_".$this->appkey."_".date("Y-m-d").".log";$logger->log(array(date("Y-m-dH:i:s"),$resp));}return$respObject;}publicfunctionexec($paramsArray){if(!isset($paramsArray["method"])){trigger_error("Noapinamepassed");}$inflector=newLtInflector;$inflector->conf["separator"]=".";$requestClassName=ucfirst($inflector->camelize(substr($paramsArray["method"],7)))."Request";if(!class_exists($requestClassName)){trigger_error("Nosuchapi:".$paramsArray["method"]);}$session=isset($paramsArray["session"])?$paramsArray["session"]:null;$req=new$requestClassName;foreach($paramsArrayas$paraKey=>$paraValue){$inflector->conf["separator"]="_";$setterMethodName=$inflector->camelize($paraKey);$inflector->conf["separator"]=".";$setterMethodName="set".$inflector->camelize($setterMethodName);if(method_exists($req,$setterMethodName)){$req->$setterMethodName($paraValue);}}return$this->execute($req,$session);}}?> php$url="$ch=curl_init();curl_setopt($ch,CURLOPT_URL,$url);curl_setopt($ch,CURLOPT_RETURNTRANSFER,1);curl_setopt($ch,CURLOPT_USERPWD,"myusername:mypassword");curl_setopt($ch,CURLOPT_FOLLOWLOCATION,1);//HTTP认证:用户名和密码认证//发送用户名和密码//你可以允许其重定向//下面的选项让cURL在重定向后//也能发送用户名和密码curl_setopt($ch,CURLOPT_UNRESTRICTED_AUTH,1);$output=curl_exec($ch);curl_close($ch);?>以下为引用的内容://创建两个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循环,继续下一条URLphp/*************************************************Snoopy-thePHPnetclientAuthor:MonteOhrtCopyright(c):1999-2000ispi,allrightsreservedVersion:1.01*Thislibraryisfreesoftware;youcanredistributeitand/or*modifyitunderthetermsoftheGNULesserGeneralPublic*LicenseaspublishedbytheFreeSoftwareFoundation;either*version2.1oftheLicense,or(atyouroption)anylaterversion.**Thislibraryisdistributedinthehopethat
$postBodyString="";
$postMultipart=false;
foreach($postFieldsas$k=>$v)
=substr($v,0,1))//判断是不是文件上传
$postBodyString.="$k=".urlencode($v)."&";
else//文件上传用multipart/form-data,否则用www-form-urlencoded
$postMultipart=true;
curl_setopt($ch,CURLOPT_POST,true);
if($postMultipart)
curl_setopt($ch,CURLOPT_POSTFIELDS,$postFields);
curl_setopt($ch,CURLOPT_POSTFIELDS,substr($postBodyString,0,-1));
$reponse=curl_exec($ch);
if(curl_errno($ch))
thrownewException(curl_error($ch),0);
$httpStatusCode=curl_getinfo($ch,CURLINFO_HTTP_CODE);
if(200!
==$httpStatusCode)
thrownewException($reponse,$httpStatusCode);
curl_close($ch);
return$reponse;
protectedfunctionlogCommunicationError($apiName,$requestUrl,$errorCode,$responseTxt)
$localIp=isset($_SERVER["SERVER_ADDR"])?
$_SERVER["SERVER_ADDR"]:
"CLI";
$logger=newLtLogger;
$logger->conf["log_file"]=rtrim(TOP_SDK_WORK_DIR,'\\/').'/'."logs/top_comm_err_".$this->appkey."_".date("Y-m-d").".log";
$logger->conf["separator"]="^_^";
$logData=array(
date("Y-m-dH:
i:
s"),
$apiName,
$this->appkey,
$localIp,
PHP_OS,
$this->sdkVersion,
$requestUrl,
$errorCode,
str_replace("\n","",$responseTxt)
$logger->log($logData);
publicfunctionexecute($request,$session=null)
if($this->checkRequest){
try{
$request->check();
}catch(Exception$e){
$result->code=$e->getCode();
$result->msg=$e->getMessage();
return$result;
//组装系统参数
$sysParams["app_key"]=$this->appkey;
$sysParams["v"]=$this->apiVersion;
$sysParams["format"]=$this->format;
$sysParams["sign_method"]=$this->signMethod;
$sysParams["method"]=$request->getApiMethodName();
$sysParams["timestamp"]=date("Y-m-dH:
s");
$sysParams["partner_id"]=$this->sdkVersion;
if(null!
=$session)
$sysParams["session"]=$session;
//获取业务参数
$apiParams=$request->getApiParas();
//签名
$sysParams["sign"]=$this->generateSign(array_merge($apiParams,$sysParams));
//系统参数放入GET请求串
$requestUrl=$this->gatewayUrl."?
";
foreach($sysParamsas$sysParamKey=>$sysParamValue)
$requestUrl.="$sysParamKey=".urlencode($sysParamValue)."&";
$requestUrl=substr($requestUrl,0,-1);
//发起HTTP请求
try
$resp=$this->curl($requestUrl,$apiParams);
catch(Exception$e)
$this->logCommunicationError($sysParams["method"],$requestUrl,"HTTP_ERROR_".$e->getCode(),$e->getMessage());
//解析TOP返回结果
$respWellFormed=false;
if("json"==$this->format)
$respObject=$resp);
==$respObject)
$respWellFormed=true;
foreach($respObjectas$propKey=>$propValue)
$respObject=$propValue;
elseif("xml"==$this->format)
$respObject=@simplexml_load_string($resp);
if(false!
//返回的HTTP文本不是标准JSON或者XML,记下错误日志
if(false===$respWellFormed)
{$this->logCommunicationError($sysParams["method"],$requestUrl,"HTTP_RESPONSE_NOT_WELL_FORMED",$resp);
$result->code=0;
$result->msg="HTTP_RESPONSE_NOT_WELL_FORMED";
//如果TOP返回了错误码,记录到业务错误日志中
if(isset($respObject->code))
$logger->conf["log_file"]=rtrim(TOP_SDK_WORK_DIR,'\\/').'/'."logs/top_biz_err_".$this->appkey."_".date("Y-m-d").".log";
$logger->log(array(
$resp
));
return$respObject;
publicfunctionexec($paramsArray)
isset($paramsArray["method"]))
trigger_error("Noapinamepassed");
$inflector=newLtInflector;
$inflector->conf["separator"]=".";
$requestClassName=ucfirst($inflector->camelize(substr($paramsArray["method"],7)))."Request";
class_exists($requestClassName))
trigger_error("Nosuchapi:
".$paramsArray["method"]);
$session=isset($paramsArray["session"])?
$paramsArray["session"]:
null;
$req=new$requestClassName;
foreach($paramsArrayas$paraKey=>$paraValue)
$inflector->conf["separator"]="_";
$setterMethodName=$inflector->camelize($paraKey);
$setterMethodName="set".$inflector->camelize($setterMethodName);
if(method_exists($req,$setterMethodName))
$req->$setterMethodName($paraValue);
return$this->execute($req,$session);
$url="
curl_setopt($ch,CURLOPT_RETURNTRANSFER,1);
curl_setopt($ch,CURLOPT_USERPWD,"myusername:
mypassword");
curl_setopt($ch,CURLOPT_FOLLOWLOCATION,1);
//HTTP认证:
用户名和密码认证
//发送用户名和密码
//你可以允许其重定向
//下面的选项让cURL在重定向后
//也能发送用户名和密码
curl_setopt($ch,CURLOPT_UNRESTRICTED_AUTH,1);
$output=curl_exec($ch);
以下为引用的内容:
//创建两个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){
//关闭各个句柄
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
Snoopy-thePHPnetclient
Author:
MonteOhrt
Copyright(c):
1999-2000ispi,allrightsreserved
Version:
1.01
*Thislibraryisfreesoftware;youcanredistributeitand/or
*modifyitunderthetermsoftheGNULesserGeneralPublic
*LicenseaspublishedbytheFreeSoftwareFoundation;either
*version2.1oftheLicense,or(atyouroption)anylaterversion.
*
*Thislibraryisdistributedinthehopethat
copyright@ 2008-2022 冰豆网网站版权所有
经营许可证编号:鄂ICP备2022015515号-1