Brak opisu

DingTalkClient.php 9.4KB

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