优惠券订单及其他脚本

TopClient.php 10KB

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