QimenCloudClient.php 10 KB

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