TopClient.php 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380
  1. <?php
  2. class TopClient
  3. {
  4. public $appkey;
  5. public $secretKey;
  6. public $gatewayUrl = "http://gw.api.taobao.com/router/rest";
  7. public $format = "xml";
  8. public $connectTimeout;
  9. public $readTimeout;
  10. /** 是否打开入参check**/
  11. public $checkRequest = true;
  12. protected $signMethod = "md5";
  13. protected $apiVersion = "2.0";
  14. protected $sdkVersion = "top-sdk-php-20151012";
  15. public function getAppkey()
  16. {
  17. return $this->appkey;
  18. }
  19. public function __construct($appkey = "",$secretKey = ""){
  20. $this->appkey = $appkey;
  21. $this->secretKey = $secretKey ;
  22. }
  23. protected function generateSign($params)
  24. {
  25. ksort($params);
  26. $stringToBeSigned = $this->secretKey;
  27. foreach ($params as $k => $v)
  28. {
  29. if(is_string($v) && "@" != substr($v, 0, 1))
  30. {
  31. $stringToBeSigned .= "$k$v";
  32. }
  33. }
  34. unset($k, $v);
  35. $stringToBeSigned .= $this->secretKey;
  36. return strtoupper(md5($stringToBeSigned));
  37. }
  38. public function curl($url, $postFields = null)
  39. {
  40. $ch = curl_init();
  41. curl_setopt($ch, CURLOPT_URL, $url);
  42. curl_setopt($ch, CURLOPT_FAILONERROR, false);
  43. curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
  44. if ($this->readTimeout) {
  45. curl_setopt($ch, CURLOPT_TIMEOUT, $this->readTimeout);
  46. }
  47. if ($this->connectTimeout) {
  48. curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $this->connectTimeout);
  49. }
  50. curl_setopt ( $ch, CURLOPT_USERAGENT, "top-sdk-php" );
  51. //https 请求
  52. if(strlen($url) > 5 && strtolower(substr($url,0,5)) == "https" ) {
  53. curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
  54. curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
  55. }
  56. if (is_array($postFields) && 0 < count($postFields))
  57. {
  58. $postBodyString = "";
  59. $postMultipart = false;
  60. foreach ($postFields as $k => $v)
  61. {
  62. if(!is_string($v))
  63. continue ;
  64. if("@" != substr($v, 0, 1))//判断是不是文件上传
  65. {
  66. $postBodyString .= "$k=" . urlencode($v) . "&";
  67. }
  68. else//文件上传用multipart/form-data,否则用www-form-urlencoded
  69. {
  70. $postMultipart = true;
  71. if(class_exists('\CURLFile')){
  72. $postFields[$k] = new \CURLFile(substr($v, 1));
  73. }
  74. }
  75. }
  76. unset($k, $v);
  77. curl_setopt($ch, CURLOPT_POST, true);
  78. if ($postMultipart)
  79. {
  80. if (class_exists('\CURLFile')) {
  81. curl_setopt($ch, CURLOPT_SAFE_UPLOAD, true);
  82. } else {
  83. if (defined('CURLOPT_SAFE_UPLOAD')) {
  84. curl_setopt($ch, CURLOPT_SAFE_UPLOAD, false);
  85. }
  86. }
  87. curl_setopt($ch, CURLOPT_POSTFIELDS, $postFields);
  88. }
  89. else
  90. {
  91. $header = array("content-type: application/x-www-form-urlencoded; charset=UTF-8");
  92. curl_setopt($ch,CURLOPT_HTTPHEADER,$header);
  93. curl_setopt($ch, CURLOPT_POSTFIELDS, substr($postBodyString,0,-1));
  94. }
  95. }
  96. $reponse = curl_exec($ch);
  97. if (curl_errno($ch))
  98. {
  99. throw new Exception(curl_error($ch),0);
  100. }
  101. else
  102. {
  103. $httpStatusCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
  104. if (200 !== $httpStatusCode)
  105. {
  106. throw new Exception($reponse,$httpStatusCode);
  107. }
  108. }
  109. curl_close($ch);
  110. return $reponse;
  111. }
  112. public function curl_with_memory_file($url, $postFields = null, $fileFields = null)
  113. {
  114. $ch = curl_init();
  115. curl_setopt($ch, CURLOPT_URL, $url);
  116. curl_setopt($ch, CURLOPT_FAILONERROR, false);
  117. curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
  118. if ($this->readTimeout) {
  119. curl_setopt($ch, CURLOPT_TIMEOUT, $this->readTimeout);
  120. }
  121. if ($this->connectTimeout) {
  122. curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $this->connectTimeout);
  123. }
  124. curl_setopt ( $ch, CURLOPT_USERAGENT, "top-sdk-php" );
  125. //https 请求
  126. if(strlen($url) > 5 && strtolower(substr($url,0,5)) == "https" ) {
  127. curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
  128. curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
  129. }
  130. //生成分隔符
  131. $delimiter = '-------------' . uniqid();
  132. //先将post的普通数据生成主体字符串
  133. $data = '';
  134. if($postFields != null){
  135. foreach ($postFields as $name => $content) {
  136. $data .= "--" . $delimiter . "\r\n";
  137. $data .= 'Content-Disposition: form-data; name="' . $name . '"';
  138. //multipart/form-data 不需要urlencode,参见 http:stackoverflow.com/questions/6603928/should-i-url-encode-post-data
  139. $data .= "\r\n\r\n" . $content . "\r\n";
  140. }
  141. unset($name,$content);
  142. }
  143. //将上传的文件生成主体字符串
  144. if($fileFields != null){
  145. foreach ($fileFields as $name => $file) {
  146. $data .= "--" . $delimiter . "\r\n";
  147. $data .= 'Content-Disposition: form-data; name="' . $name . '"; filename="' . $file['name'] . "\" \r\n";
  148. $data .= 'Content-Type: ' . $file['type'] . "\r\n\r\n";//多了个文档类型
  149. $data .= $file['content'] . "\r\n";
  150. }
  151. unset($name,$file);
  152. }
  153. //主体结束的分隔符
  154. $data .= "--" . $delimiter . "--";
  155. curl_setopt($ch, CURLOPT_POST, true);
  156. curl_setopt($ch, CURLOPT_HTTPHEADER , array(
  157. 'Content-Type: multipart/form-data; boundary=' . $delimiter,
  158. 'Content-Length: ' . strlen($data))
  159. );
  160. curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
  161. curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
  162. $reponse = curl_exec($ch);
  163. unset($data);
  164. if (curl_errno($ch))
  165. {
  166. throw new Exception(curl_error($ch),0);
  167. }
  168. else
  169. {
  170. $httpStatusCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
  171. if (200 !== $httpStatusCode)
  172. {
  173. throw new Exception($reponse,$httpStatusCode);
  174. }
  175. }
  176. curl_close($ch);
  177. return $reponse;
  178. }
  179. protected function logCommunicationError($apiName, $requestUrl, $errorCode, $responseTxt)
  180. {
  181. $localIp = isset($_SERVER["SERVER_ADDR"]) ? $_SERVER["SERVER_ADDR"] : "CLI";
  182. $logger = new TopLogger;
  183. $logger->conf["log_file"] = rtrim(TOP_SDK_WORK_DIR, '\\/') . '/' . "logs/top_comm_err_" . $this->appkey . "_" . date("Y-m-d") . ".log";
  184. $logger->conf["separator"] = "^_^";
  185. $logData = array(
  186. date("Y-m-d H:i:s"),
  187. $apiName,
  188. $this->appkey,
  189. $localIp,
  190. PHP_OS,
  191. $this->sdkVersion,
  192. $requestUrl,
  193. $errorCode,
  194. str_replace("\n","",$responseTxt)
  195. );
  196. $logger->log($logData);
  197. }
  198. public function execute($request, $session = null,$bestUrl = null)
  199. {
  200. $result = new ResultSet();
  201. if($this->checkRequest) {
  202. try {
  203. $request->check();
  204. } catch (Exception $e) {
  205. $result->code = $e->getCode();
  206. $result->msg = $e->getMessage();
  207. return $result;
  208. }
  209. }
  210. //组装系统参数
  211. $sysParams["app_key"] = $this->appkey;
  212. $sysParams["v"] = $this->apiVersion;
  213. $sysParams["format"] = $this->format;
  214. $sysParams["sign_method"] = $this->signMethod;
  215. $sysParams["method"] = $request->getApiMethodName();
  216. $sysParams["timestamp"] = date("Y-m-d H:i:s");
  217. if (null != $session)
  218. {
  219. $sysParams["session"] = $session;
  220. }
  221. $apiParams = array();
  222. //获取业务参数
  223. $apiParams = $request->getApiParas();
  224. //系统参数放入GET请求串
  225. if($bestUrl){
  226. $requestUrl = $bestUrl."?";
  227. $sysParams["partner_id"] = $this->getClusterTag();
  228. }else{
  229. $requestUrl = $this->gatewayUrl."?";
  230. $sysParams["partner_id"] = $this->sdkVersion;
  231. }
  232. //签名
  233. $sysParams["sign"] = $this->generateSign(array_merge($apiParams, $sysParams));
  234. foreach ($sysParams as $sysParamKey => $sysParamValue)
  235. {
  236. // if(strcmp($sysParamKey,"timestamp") != 0)
  237. $requestUrl .= "$sysParamKey=" . urlencode($sysParamValue) . "&";
  238. }
  239. $fileFields = array();
  240. foreach ($apiParams as $key => $value) {
  241. if(is_array($value) && array_key_exists('type',$value) && array_key_exists('content',$value) ){
  242. $value['name'] = $key;
  243. $fileFields[$key] = $value;
  244. unset($apiParams[$key]);
  245. }
  246. }
  247. // $requestUrl .= "timestamp=" . urlencode($sysParams["timestamp"]) . "&";
  248. $requestUrl = substr($requestUrl, 0, -1);
  249. //发起HTTP请求
  250. try
  251. {
  252. if(count($fileFields) > 0){
  253. $resp = $this->curl_with_memory_file($requestUrl, $apiParams, $fileFields);
  254. }else{
  255. $resp = $this->curl($requestUrl, $apiParams);
  256. }
  257. }
  258. catch (Exception $e)
  259. {
  260. $this->logCommunicationError($sysParams["method"],$requestUrl,"HTTP_ERROR_" . $e->getCode(),$e->getMessage());
  261. $result->code = $e->getCode();
  262. $result->msg = $e->getMessage();
  263. return $result;
  264. }
  265. unset($apiParams);
  266. unset($fileFields);
  267. //解析TOP返回结果
  268. $respWellFormed = false;
  269. if ("json" == $this->format)
  270. {
  271. $respObject = json_decode($resp);
  272. if (null !== $respObject)
  273. {
  274. $respWellFormed = true;
  275. foreach ($respObject as $propKey => $propValue)
  276. {
  277. $respObject = $propValue;
  278. }
  279. }
  280. }
  281. else if("xml" == $this->format)
  282. {
  283. $respObject = @simplexml_load_string($resp);
  284. if (false !== $respObject)
  285. {
  286. $respWellFormed = true;
  287. }
  288. }
  289. //返回的HTTP文本不是标准JSON或者XML,记下错误日志
  290. if (false === $respWellFormed)
  291. {
  292. $this->logCommunicationError($sysParams["method"],$requestUrl,"HTTP_RESPONSE_NOT_WELL_FORMED",$resp);
  293. $result->code = 0;
  294. $result->msg = "HTTP_RESPONSE_NOT_WELL_FORMED";
  295. return $result;
  296. }
  297. //如果TOP返回了错误码,记录到业务错误日志中
  298. if (isset($respObject->code))
  299. {
  300. $logger = new TopLogger;
  301. $logger->conf["log_file"] = rtrim(TOP_SDK_WORK_DIR, '\\/') . '/' . "logs/top_biz_err_" . $this->appkey . "_" . date("Y-m-d") . ".log";
  302. $logger->log(array(
  303. date("Y-m-d H:i:s"),
  304. $resp
  305. ));
  306. }
  307. return $respObject;
  308. }
  309. public function exec($paramsArray)
  310. {
  311. if (!isset($paramsArray["method"]))
  312. {
  313. trigger_error("No api name passed");
  314. }
  315. $inflector = new LtInflector;
  316. $inflector->conf["separator"] = ".";
  317. $requestClassName = ucfirst($inflector->camelize(substr($paramsArray["method"], 7))) . "Request";
  318. if (!class_exists($requestClassName))
  319. {
  320. trigger_error("No such api: " . $paramsArray["method"]);
  321. }
  322. $session = isset($paramsArray["session"]) ? $paramsArray["session"] : null;
  323. $req = new $requestClassName;
  324. foreach($paramsArray as $paraKey => $paraValue)
  325. {
  326. $inflector->conf["separator"] = "_";
  327. $setterMethodName = $inflector->camelize($paraKey);
  328. $inflector->conf["separator"] = ".";
  329. $setterMethodName = "set" . $inflector->camelize($setterMethodName);
  330. if (method_exists($req, $setterMethodName))
  331. {
  332. $req->$setterMethodName($paraValue);
  333. }
  334. }
  335. return $this->execute($req, $session);
  336. }
  337. private function getClusterTag()
  338. {
  339. return substr($this->sdkVersion,0,11)."-cluster".substr($this->sdkVersion,11);
  340. }
  341. }