REAPI/extend/sdk/taobao/top/TopClient.php

387 lines
12 KiB
PHP
Raw Normal View History

2024-09-29 15:43:18 +08:00
<?php
class TopClient
{
public $appkey;
public $secretKey;
// public $gatewayUrl = "http://gw.api.taobao.com/router/rest";
public $gatewayUrl = "https://eco.taobao.com/router/rest";
public $format = "xml";
public $connectTimeout;
public $readTimeout;
/** <20>Ƿ<EFBFBD><C7B7><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>check**/
public $checkRequest = true;
protected $signMethod = "md5";
protected $apiVersion = "2.0";
protected $sdkVersion = "top-sdk-php-20180326";
public function getAppkey()
{
return $this->appkey;
}
public function __construct($appkey = "",$secretKey = ""){
$this->appkey = $appkey;
$this->secretKey = $secretKey ;
}
protected function generateSign($params)
{
ksort($params);
$stringToBeSigned = $this->secretKey;
foreach ($params as $k => $v)
{
if(!is_array($v) && "@" != substr($v, 0, 1))
{
$stringToBeSigned .= "$k$v";
}
}
unset($k, $v);
$stringToBeSigned .= $this->secretKey;
return strtoupper(md5($stringToBeSigned));
}
public 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);
// curl_setopt($ch, CURLOPT_ENCODING, "GBK");
if ($this->readTimeout) {
curl_setopt($ch, CURLOPT_TIMEOUT, $this->readTimeout);
}
if ($this->connectTimeout) {
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $this->connectTimeout);
}
curl_setopt ( $ch, CURLOPT_USERAGENT, "top-sdk-php" );
//https <20><><EFBFBD><EFBFBD>
if(strlen($url) > 5 && strtolower(substr($url,0,5)) == "https" ) {
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
}
if (is_array($postFields) && 0 < count($postFields))
{
$postBodyString = "";
$postMultipart = false;
foreach ($postFields as $k => $v)
{
if("@" != substr($v, 0, 1))//<2F>ж<EFBFBD><D0B6>Dz<EFBFBD><C7B2><EFBFBD><EFBFBD>ļ<EFBFBD><C4BC>ϴ<EFBFBD>
{
$postBodyString .= "$k=" . urlencode($v) . "&";
}
else//<2F>ļ<EFBFBD><C4BC>ϴ<EFBFBD><CFB4><EFBFBD>multipart/form-data<74><61><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>www-form-urlencoded
{
$postMultipart = true;
if(class_exists('\CURLFile')){
$postFields[$k] = new \CURLFile(substr($v, 1));
}
}
}
unset($k, $v);
curl_setopt($ch, CURLOPT_POST, true);
if ($postMultipart)
{
if (class_exists('\CURLFile')) {
curl_setopt($ch, CURLOPT_SAFE_UPLOAD, true);
} else {
if (defined('CURLOPT_SAFE_UPLOAD')) {
curl_setopt($ch, CURLOPT_SAFE_UPLOAD, false);
}
}
curl_setopt($ch, CURLOPT_POSTFIELDS, $postFields);
}
else
{
$header = array("content-type: application/x-www-form-urlencoded; charset=UTF-8");
curl_setopt($ch,CURLOPT_HTTPHEADER,$header);
curl_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);
// var_dump($reponse);die;
if (200 !== $httpStatusCode)
{
// var_dump(1);die;
throw new Exception($reponse,$httpStatusCode);
}
}
curl_close($ch);
return $reponse;
}
public function curl_with_memory_file($url, $postFields = null, $fileFields = null)
{
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_FAILONERROR, false);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
if ($this->readTimeout) {
curl_setopt($ch, CURLOPT_TIMEOUT, $this->readTimeout);
}
if ($this->connectTimeout) {
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $this->connectTimeout);
}
curl_setopt ( $ch, CURLOPT_USERAGENT, "top-sdk-php" );
//https <20><><EFBFBD><EFBFBD>
if(strlen($url) > 5 && strtolower(substr($url,0,5)) == "https" ) {
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
}
//<2F><><EFBFBD>ɷָ<C9B7><D6B8><EFBFBD>
$delimiter = '-------------' . uniqid();
//<2F>Ƚ<EFBFBD>post<73><74><EFBFBD><EFBFBD>ͨ<EFBFBD><CDA8><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>ַ<EFBFBD><D6B7><EFBFBD>
$data = '';
if($postFields != null){
foreach ($postFields as $name => $content) {
$data .= "--" . $delimiter . "\r\n";
$data .= 'Content-Disposition: form-data; name="' . $name . '"';
//multipart/form-data <20><><EFBFBD><EFBFBD>Ҫurlencode<64><65><EFBFBD>μ<EFBFBD> http:stackoverflow.com/questions/6603928/should-i-url-encode-post-data
$data .= "\r\n\r\n" . $content . "\r\n";
}
unset($name,$content);
}
//<2F><><EFBFBD>ϴ<EFBFBD><CFB4><EFBFBD><EFBFBD>ļ<EFBFBD><C4BC><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>ַ<EFBFBD><D6B7><EFBFBD>
if($fileFields != null){
foreach ($fileFields as $name => $file) {
$data .= "--" . $delimiter . "\r\n";
$data .= 'Content-Disposition: form-data; name="' . $name . '"; filename="' . $file['name'] . "\" \r\n";
$data .= 'Content-Type: ' . $file['type'] . "\r\n\r\n";//<2F><><EFBFBD>˸<EFBFBD><CBB8>ĵ<EFBFBD><C4B5><EFBFBD><EFBFBD><EFBFBD>
$data .= $file['content'] . "\r\n";
}
unset($name,$file);
}
//<2F><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>ķָ<C4B7><D6B8><EFBFBD>
$data .= "--" . $delimiter . "--";
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_HTTPHEADER , array(
'Content-Type: multipart/form-data; boundary=' . $delimiter,
'Content-Length: ' . strlen($data))
);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
$reponse = curl_exec($ch);
unset($data);
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($_SERVER["SERVER_ADDR"]) ? $_SERVER["SERVER_ADDR"] : "CLI";
$logger = new TopLogger;
$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-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,$bestUrl = null)
{
$result = new ResultSet();
if($this->checkRequest) {
try {
$request->check();
} catch (Exception $e) {
$result->code = $e->getCode();
$result->msg = $e->getMessage();
return $result;
}
}
//<2F><>װϵͳ<CFB5><CDB3><EFBFBD><EFBFBD>
$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-d H:i:s");
if (null != $session)
{
$sysParams["session"] = $session;
}
$apiParams = array();
//<2F><>ȡҵ<C8A1><D2B5><EFBFBD><EFBFBD><EFBFBD><EFBFBD>
$apiParams = $request->getApiParas();
//ϵͳ<CFB5><CDB3><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>GET<45><54><EFBFBD><EFBFBD><EFBFBD><EFBFBD>
if($bestUrl){
$requestUrl = $bestUrl."?";
$sysParams["partner_id"] = $this->getClusterTag();
}else{
$requestUrl = $this->gatewayUrl."?";
$sysParams["partner_id"] = $this->sdkVersion;
}
//ǩ<><C7A9>
$sysParams["sign"] = $this->generateSign(array_merge($apiParams, $sysParams));
foreach ($sysParams as $sysParamKey => $sysParamValue)
{
// if(strcmp($sysParamKey,"timestamp") != 0)
$requestUrl .= "$sysParamKey=" . urlencode($sysParamValue) . "&";
}
$fileFields = array();
foreach ($apiParams as $key => $value) {
if(is_array($value) && array_key_exists('type',$value) && array_key_exists('content',$value) ){
$value['name'] = $key;
$fileFields[$key] = $value;
unset($apiParams[$key]);
}
}
// $requestUrl .= "timestamp=" . urlencode($sysParams["timestamp"]) . "&";
$requestUrl = substr($requestUrl, 0, -1);
// print_r($requestUrl);
// print_r($apiParams);
// die;
//<2F><><EFBFBD><EFBFBD>HTTP<54><50><EFBFBD><EFBFBD>
try
{
if(count($fileFields) > 0){
$resp = $this->curl_with_memory_file($requestUrl, $apiParams, $fileFields);
}else{
$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;
}
unset($apiParams);
unset($fileFields);
//<2F><><EFBFBD><EFBFBD>TOP<4F><50><EFBFBD>ؽ<EFBFBD><D8BD><EFBFBD>
$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;
}
}
//<2F><><EFBFBD>ص<EFBFBD>HTTP<54>ı<EFBFBD><C4B1><EFBFBD><EFBFBD>DZ<EFBFBD>׼JSON<4F><4E><EFBFBD><EFBFBD>XML<4D><4C><EFBFBD><EFBFBD><EFBFBD>´<EFBFBD><C2B4><EFBFBD><EFBFBD><EFBFBD>־
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;
}
//<2F><><EFBFBD><EFBFBD>TOP<4F><50><EFBFBD><EFBFBD><EFBFBD>˴<EFBFBD><CBB4><EFBFBD><EFBFBD><EFBFBD><EBA3AC>¼<EFBFBD><C2BC>ҵ<EFBFBD><D2B5><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>־<EFBFBD><D6BE>
if (isset($respObject->code))
{
$logger = new TopLogger;
$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-d H:i:s"),
$resp
));
}
return $respObject;
}
public function exec($paramsArray)
{
if (!isset($paramsArray["method"]))
{
trigger_error("No api name passed");
}
$inflector = new LtInflector;
$inflector->conf["separator"] = ".";
$requestClassName = ucfirst($inflector->camelize(substr($paramsArray["method"], 7))) . "Request";
if (!class_exists($requestClassName))
{
trigger_error("No such api: " . $paramsArray["method"]);
}
$session = isset($paramsArray["session"]) ? $paramsArray["session"] : null;
$req = new $requestClassName;
foreach($paramsArray as $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);
}
private function getClusterTag()
{
return substr($this->sdkVersion,0,11)."-cluster".substr($this->sdkVersion,11);
}
}