JdClient.php 6.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228
  1. <?php
  2. namespace Jd\jd;
  3. use DateTimeZone;
  4. class JdClient
  5. {
  6. public $serverUrl = "https://api.jd.com/routerjson";
  7. public $accessToken;
  8. public $connectTimeout = 0;
  9. public $readTimeout = 0;
  10. public $appKey;
  11. public $appSecret;
  12. public $version = "2.0";
  13. public $format = "json";
  14. private $charset_utf8 = "UTF-8";
  15. private $json_param_key = "360buy_param_json";
  16. protected function generateSign($params)
  17. {
  18. ksort($params);
  19. $stringToBeSigned = $this->appSecret;
  20. foreach ($params as $k => $v)
  21. {
  22. // if(!is_string($v) && is_array($v)){
  23. if($this->json_param_key == $k){
  24. $stringToBeSigned .= "$k".json_encode($v, JSON_UNESCAPED_SLASHES);
  25. }else{
  26. $stringToBeSigned .= "$k$v";
  27. }
  28. }
  29. unset($k, $v);
  30. $stringToBeSigned .= $this->appSecret;
  31. return strtoupper(md5($stringToBeSigned));
  32. }
  33. public function curl($serverUrl, $sysParams)
  34. {
  35. $ch = curl_init();
  36. curl_setopt($ch, CURLOPT_FAILONERROR, false);
  37. curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
  38. if ($this->readTimeout) {
  39. curl_setopt($ch, CURLOPT_TIMEOUT, $this->readTimeout);
  40. }
  41. if ($this->connectTimeout) {
  42. curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $this->connectTimeout);
  43. }
  44. //https 请求
  45. if(strlen($serverUrl) > 5 && strtolower(substr($serverUrl,0,5)) == "https" ) {
  46. curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
  47. curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
  48. }
  49. // 此处修改暂时为了保证顺利上传,直接base64编码文件流的方式来上传。所以$postMultipart 依然为false
  50. //获取业务参数
  51. $apiParams = $sysParams[$this->json_param_key];
  52. /* 1)全部使用POST方式,multi和simple。
  53. 2)$postMultipart 暂时没有用,字节流拼接成串的方式上传,所以先去掉
  54. */
  55. curl_setopt($ch, CURLOPT_POST, true);
  56. // 需要把系统参数依然使用url方式传递
  57. $requestUrl = $serverUrl . "?";
  58. foreach ($sysParams as $sysParamKey => $sysParamValue)
  59. {
  60. if($sysParamKey != $this->json_param_key){
  61. $requestUrl .= "$sysParamKey=" . urlencode($sysParamValue) . "&";
  62. }
  63. }
  64. // 去掉末尾的 "&"
  65. curl_setopt($ch, CURLOPT_URL, substr($requestUrl,0,-1));
  66. curl_setopt($ch, CURLOPT_POSTFIELDS, $this->json_param_key . "=" . urlencode(json_encode($apiParams,JSON_UNESCAPED_SLASHES)));
  67. $reponse = curl_exec($ch);
  68. if (curl_errno($ch))
  69. {
  70. throw new Exception(curl_error($ch),0);
  71. }
  72. else
  73. {
  74. $httpStatusCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
  75. if (200 !== $httpStatusCode)
  76. {
  77. throw new Exception($reponse,$httpStatusCode);
  78. }
  79. }
  80. curl_close($ch);
  81. return $reponse;
  82. }
  83. /*
  84. 2024.08 修改了一版,系统参数和业务参数分别使用,其中业务参数放到postbody里面
  85. */
  86. public function execute($request, $access_token = null)
  87. {
  88. //组装系统参数
  89. $sysParams["app_key"] = $this->appKey;
  90. $version = $request->getVersion();
  91. $sysParams["v"] = empty($version)? $this->version:$version;
  92. $sysParams["method"] = $request->getApiMethodName();
  93. $sysParams["timestamp"] = $this->getCurrentTimeFormatted();
  94. if (null != $access_token)
  95. {
  96. $sysParams["access_token"] = $access_token;
  97. }
  98. $sysParams[$this->json_param_key] = $request->getApiParas();
  99. //签名
  100. $sysParams["sign"] = $this->generateSign($sysParams);
  101. //发起HTTP请求
  102. try
  103. {
  104. $resp = $this->curl($this->serverUrl, $sysParams);
  105. }
  106. catch (Exception $e)
  107. {
  108. return array(
  109. 'code' => $e->getCode(),
  110. 'msg' => $e->getMessage()
  111. );
  112. }
  113. //解析JD返回结果
  114. $respWellFormed = false;
  115. if ("json" == $this->format)
  116. {
  117. $respObject = json_decode($resp);
  118. if (null !== $respObject)
  119. {
  120. $respWellFormed = true;
  121. // foreach ($respObject as $propKey => $propValue)
  122. // {
  123. // $respObject = $propValue;
  124. // }
  125. }
  126. }
  127. else if("xml" == $this->format)
  128. {
  129. $respObject = @simplexml_load_string($resp);
  130. if (false !== $respObject)
  131. {
  132. $respWellFormed = true;
  133. }
  134. }
  135. //返回的HTTP文本不是标准JSON或者XML,记下错误日志
  136. if (false === $respWellFormed)
  137. {
  138. return array(
  139. 'code' => 0,
  140. 'msg' => "HTTP_RESPONSE_NOT_WELL_FORMED"
  141. );
  142. }
  143. return $respObject;
  144. }
  145. public function exec($paramsArray)
  146. {
  147. if (!isset($paramsArray["method"]))
  148. {
  149. trigger_error("No api name passed");
  150. }
  151. $inflector = new LtInflector;
  152. $inflector->conf["separator"] = ".";
  153. $requestClassName = ucfirst($inflector->camelize(substr($paramsArray["method"], 7))) . "Request";
  154. if (!class_exists($requestClassName))
  155. {
  156. trigger_error("No such api: " . $paramsArray["method"]);
  157. }
  158. $session = isset($paramsArray["session"]) ? $paramsArray["session"] : null;
  159. $req = new $requestClassName;
  160. foreach($paramsArray as $paraKey => $paraValue)
  161. {
  162. $inflector->conf["separator"] = "_";
  163. $setterMethodName = $inflector->camelize($paraKey);
  164. $inflector->conf["separator"] = ".";
  165. $setterMethodName = "set" . $inflector->camelize($setterMethodName);
  166. if (method_exists($req, $setterMethodName))
  167. {
  168. $req->$setterMethodName($paraValue);
  169. }
  170. }
  171. return $this->execute($req, $session);
  172. }
  173. private function getCurrentTimeFormatted()
  174. {
  175. return date("Y-m-d H:i:s").'.000'.$this->getStandardOffsetUTC(date_default_timezone_get());
  176. }
  177. private function getStandardOffsetUTC($timezone)
  178. {
  179. if($timezone == 'UTC') {
  180. return '+0000';
  181. } else {
  182. $timezone = new DateTimeZone($timezone);
  183. $transitions = array_slice($timezone->getTransitions(), -3, null, true);
  184. foreach (array_reverse($transitions, true) as $transition)
  185. {
  186. if ($transition['isdst'] == 1)
  187. {
  188. continue;
  189. }
  190. return sprintf('%+03d%02u', $transition['offset'] / 3600, abs($transition['offset']) % 3600 / 60);
  191. }
  192. return false;
  193. }
  194. }
  195. }