DingTalkClient.php 9.4 KB

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