feishuapi.class.php 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497
  1. <?php
  2. class feishuapi
  3. {
  4. public $apiUrl = 'https://open.feishu.cn/open-apis/';
  5. private $appId;
  6. private $appSecret;
  7. private $token;
  8. private $expires;
  9. private $errors = array();
  10. /**
  11. * Construct
  12. *
  13. * @param string $appId
  14. * @param string $appSecret
  15. * @param string $apiUrl
  16. * @access public
  17. * @return void
  18. */
  19. public function __construct($appId, $appSecret, $apiUrl = '')
  20. {
  21. $this->appId = $appId;
  22. $this->appSecret = $appSecret;
  23. if($apiUrl) $this->apiUrl = rtrim($apiUrl, '/') . '/';
  24. if(!$this->getToken()) return array('result' => 'fail', 'message' => $this->errors);
  25. }
  26. /**
  27. * Get token.
  28. *
  29. * @access public
  30. * @return string
  31. */
  32. public function getToken()
  33. {
  34. if($this->token and (time() - $this->expires) >= 0) return $this->token;
  35. $response = $this->queryAPI($this->apiUrl . "auth/v3/tenant_access_token/internal/", json_encode(array('app_id' => $this->appId, 'app_secret' => $this->appSecret)));
  36. if($this->isError()) return false;
  37. $this->token = $response->tenant_access_token;
  38. $this->expires = time() + $response->expire;
  39. return $this->token;
  40. }
  41. /**
  42. * Get users.
  43. *
  44. * @param string $selectedDepts
  45. * @access public
  46. * @return array
  47. */
  48. public function getAllUsers($selectedDepts = '')
  49. {
  50. $selectedDepts = trim($selectedDepts);
  51. if(empty($selectedDepts)) return array('result' => 'fail', 'message' => 'nodept');
  52. set_time_limit(0);
  53. $users = array();
  54. $depts = explode(',', $selectedDepts);
  55. $depts = array_flip($depts);
  56. unset($depts[1]);
  57. if(empty($depts)) return array('result' => 'fail', 'message' => 'nodept');
  58. /* Get users by dept. */
  59. foreach($depts as $deptID => $count)
  60. {
  61. if(empty($deptID)) continue;
  62. $pageToken = '';
  63. while(true)
  64. {
  65. $response = $this->queryAPI($this->apiUrl . "contact/v3/users?department_id={$deptID}&page_size=50" . ($pageToken ? "&page_token={$pageToken}" : ''), '', array(CURLOPT_CUSTOMREQUEST => "GET"));
  66. if(isset($response->data->items))
  67. {
  68. foreach($response->data->items as $user) $users[$user->name] = $user->open_id;
  69. }
  70. if(!isset($response->data->page_token)) break;
  71. $pageToken = $response->data->page_token;
  72. }
  73. }
  74. /* Get users in root. */
  75. $pageToken = '';
  76. while(true)
  77. {
  78. $response = $this->queryAPI($this->apiUrl . "contact/v3/users" . ($pageToken ? "?page_token={$pageToken}" : ''), '', array(CURLOPT_CUSTOMREQUEST => "GET"));
  79. if(isset($response->data->items))
  80. {
  81. foreach($response->data->items as $user) $users[$user->name] = $user->open_id;
  82. }
  83. if(!isset($response->data->page_token)) break;
  84. $pageToken = $response->data->page_token;
  85. }
  86. return array('result' => 'success', 'data' => $users);
  87. }
  88. /**
  89. * Get depts.
  90. *
  91. * @access public
  92. * @return array
  93. */
  94. public function getDepts()
  95. {
  96. set_time_limit(0);
  97. $depts = array('0' => '0');
  98. /* Get depts by parent dept. */
  99. $pageToken = '';
  100. while(true)
  101. {
  102. $response = $this->queryAPI($this->apiUrl . "contact/v3/departments?parent_department_id=0" . ($pageToken ? "&page_token={$pageToken}" : '') . "&fetch_child=true", '', array(CURLOPT_CUSTOMREQUEST => "GET"));
  103. if(isset($response->data->items))
  104. {
  105. foreach($response->data->items as $dept) $depts[$dept->open_department_id] = $dept->member_count;
  106. }
  107. if(!isset($response->data->page_token)) break;
  108. $pageToken = $response->data->page_token;
  109. }
  110. /* Get depts by root. */
  111. $pageToken = '';
  112. while(true)
  113. {
  114. $response = $this->queryAPI($this->apiUrl . "contact/v3/departments?fetch_child=true" . ($pageToken ? "&page_token={$pageToken}" : ''), '', array(CURLOPT_CUSTOMREQUEST => "GET"));
  115. if(isset($response->data->items))
  116. {
  117. foreach($response->data->items as $dept) $depts[$dept->open_department_id] = $dept->member_count;
  118. }
  119. if(!isset($response->data->page_token)) break;
  120. $pageToken = $response->data->page_token;
  121. }
  122. return $depts;
  123. }
  124. /**
  125. * Get department tree structure.
  126. *
  127. * @param string $departmentID
  128. * @access public
  129. * @return array
  130. */
  131. public function getChildDeptTree($departmentID)
  132. {
  133. /* Get depts by parent dept. */
  134. $depts = array();
  135. $pageToken = '';
  136. while(true)
  137. {
  138. $response = $this->queryAPI($this->apiUrl . "contact/v3/departments?parent_department_id={$departmentID}" . ($pageToken ? "&page_token={$pageToken}" : '') . "&fetch_child=false&page_size=50", '', array(CURLOPT_CUSTOMREQUEST => "GET"));
  139. if(isset($response->data->items))
  140. {
  141. foreach($response->data->items as $key => $dept)
  142. {
  143. $data = array();
  144. $data['id'] = $dept->open_department_id;
  145. $data['pId'] = empty($dept->parent_department_id) ? 1 : $dept->parent_department_id;
  146. $data['name'] = $dept->name;
  147. $data['open'] = 1;
  148. $depts[] = $data;
  149. }
  150. }
  151. if(!isset($response->data->page_token)) break;
  152. $pageToken = $response->data->page_token;
  153. }
  154. return $depts;
  155. }
  156. /**
  157. * Get the first tier department.
  158. *
  159. * @access public
  160. * @return array
  161. */
  162. public function getDeptTree()
  163. {
  164. $depts = array('data' => array());
  165. /* Gets the enterprise name. */
  166. $response = $this->queryAPI($this->apiUrl . "tenant/v2/tenant/query", '', array(CURLOPT_CUSTOMREQUEST => "GET"));
  167. $company = array('id' => '1', 'pId' => '0', 'name' => $response->data->tenant->name, 'open' => 1);
  168. $depts = array($company);
  169. $departmentIdList = $this->getScopes();
  170. $urls = array();
  171. foreach($departmentIdList as $departmentID) $urls[] = $this->apiUrl . "contact/v3/departments/{$departmentID}";
  172. $datas = $this->multiRequest($urls);
  173. foreach($datas as $dept)
  174. {
  175. $dept = json_decode($dept);
  176. $data = array();
  177. $data['id'] = $dept->data->department->open_department_id;
  178. $data['pId'] = empty($dept->data->department->parent_department_id) ? 1 : $dept->data->department->parent_department_id;
  179. $data['name'] = $dept->data->department->name;
  180. $data['open'] = 1;
  181. $depts[] = $data;
  182. }
  183. return $depts;
  184. }
  185. /**
  186. * Get the visible range of the application.
  187. *
  188. * @access public
  189. * @return array
  190. */
  191. public function getScopes()
  192. {
  193. $pageToken = '';
  194. $departmentIdList = array();
  195. while(true)
  196. {
  197. $response = $this->queryAPI($this->apiUrl . "contact/v3/scopes" . "?user_id_type=open_id&department_id_type=open_department_id&page_token={$pageToken}&page_size=100", '', array(CURLOPT_CUSTOMREQUEST => "GET"));
  198. $departmentIds = isset($response->data->department_ids) ? $response->data->department_ids : array();
  199. foreach($departmentIds as $id) $departmentIdList[] = $id;
  200. if(!isset($response->data->page_token)) break;
  201. $pageToken = $response->data->page_token;
  202. }
  203. return $departmentIdList;
  204. }
  205. /**
  206. * Handle the concurrency of requests.
  207. *
  208. * @param array $urls
  209. * @access public
  210. * @return array
  211. */
  212. public function multiRequest($urls)
  213. {
  214. $curl = curl_multi_init();
  215. $urlHandlers = array();
  216. $urlData = array();
  217. /* Set request header information. */
  218. $headers = array();
  219. $headers[] = "Content-Type: application/json";
  220. if($this->token) $headers[] = "Authorization:Bearer {$this->token}";
  221. /* Initialize multiple request handles to one. */
  222. foreach($urls as $url)
  223. {
  224. $ch = curl_init();
  225. curl_setopt($ch, CURLOPT_URL, $url);
  226. curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
  227. curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
  228. if(!isset($_SERVER['HTTPS']) or $_SERVER['HTTPS'] != 'on')
  229. {
  230. curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
  231. curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
  232. }
  233. $urlHandlers[] = $ch;
  234. curl_multi_add_handle($curl, $ch);
  235. }
  236. $active = null;
  237. do
  238. {
  239. $mrc = curl_multi_exec($curl, $active);
  240. }
  241. while($mrc == CURLM_CALL_MULTI_PERFORM);
  242. while($active and $mrc == CURLM_OK)
  243. {
  244. usleep(50000);
  245. if(curl_multi_select($curl) != -1)
  246. {
  247. do
  248. {
  249. $mrc = curl_multi_exec($curl, $active);
  250. }
  251. while($mrc == CURLM_CALL_MULTI_PERFORM);
  252. }
  253. }
  254. foreach($urlHandlers as $index => $ch)
  255. {
  256. $urlData[$index] = curl_multi_getcontent($ch);
  257. curl_multi_remove_handle($curl, $ch);
  258. }
  259. curl_multi_close($curl);
  260. return $urlData;
  261. }
  262. /**
  263. * Send message
  264. *
  265. * @param string $userList
  266. * @param string $message
  267. * @access public
  268. * @return array
  269. */
  270. public function send($userList, $message)
  271. {
  272. $postData = json_decode($message, true);
  273. $postData['open_ids'] = explode(',', $userList);
  274. $url = $this->apiUrl . 'message/v4/batch_send/';
  275. $response = $this->queryAPI($url, json_encode($postData));
  276. if(isset($response->code) and $response->code == 0) return array('result' => 'success');
  277. return array('result' => 'fail', 'message' => $this->errors);
  278. }
  279. /**
  280. * Query API.
  281. *
  282. * @param string $url
  283. * @access public
  284. * @return string
  285. */
  286. public function queryAPI($url, $data = '', $options = array())
  287. {
  288. $headers = array();
  289. $headers[] = "Content-Type: application/json";
  290. if($this->token) $headers[] = "Authorization:Bearer {$this->token}";
  291. $response = common::http($url, $data, $options, $headers);
  292. $errors = commonModel::$requestErrors;
  293. $response = json_decode($response);
  294. if(isset($response->code) and $response->code == 0) return $response;
  295. if(empty($response)) $this->errors = $errors;
  296. if(isset($response->result) and $response->result == 'fail') $this->errors['curl'] = $response->message;
  297. if(isset($response->code)) $this->errors[$response->code] = "Errcode:{$response->code}, Errmsg:{$response->msg}";
  298. if(!empty($this->errors))
  299. {
  300. if(helper::isAjaxRequest())
  301. {
  302. http_response_code(500);
  303. echo array_shift($this->errors);
  304. die();
  305. }
  306. else
  307. {
  308. echo js::error(array_shift($this->errors));
  309. die(js::locate(helper::createLink('webhook', 'browse')));
  310. }
  311. }
  312. return false;
  313. }
  314. /**
  315. * 获取传入部门列表的下一级部门树数据
  316. * Get next step dept tree by dept id list.
  317. *
  318. * @param array $deptIdList
  319. * @access public
  320. * @return array
  321. */
  322. public function getNextStepDeptTree($deptIdList)
  323. {
  324. if(empty($deptIdList)) return array();
  325. $nextStepUrls = array();
  326. foreach($deptIdList as $deptID) $nextStepUrls[] = $this->apiUrl . "contact/v3/departments?parent_department_id={$deptID}&fetch_child=false&page_size=50";
  327. return $this->multiGetChildrenData($nextStepUrls);
  328. }
  329. /**
  330. * 获取传入部门列表的下一页部门树数据。
  331. * Get next page dept tree by dept and page token pairs.
  332. *
  333. * @param array $deptPageTokenPairs
  334. * @access public
  335. * @return array
  336. */
  337. public function getNextPageDeptTree($deptPageTokenPairs)
  338. {
  339. if(empty($deptPageTokenPairs)) return array();
  340. $nextPageUrls = array();
  341. foreach($deptPageTokenPairs as $deptID => $pageToken) $nextPageUrls[] = $this->apiUrl . "contact/v3/departments?parent_department_id={$deptID}&page_token={$pageToken}&fetch_child=false&page_size=50";
  342. return $this->multiGetChildrenData($nextPageUrls);
  343. }
  344. /**
  345. * 根据API链接列表,多路获取子部门数据。
  346. * Multi get children data by api url list.
  347. *
  348. * @param array $urlList
  349. * @access public
  350. * @return array
  351. */
  352. public function multiGetChildrenData($urlList)
  353. {
  354. if(empty($urlList)) return array();
  355. $nextStepParentIdList = array();
  356. $nextPageTokenPairs = array();
  357. $depts = array();
  358. $datas = $this->multiRequest($urlList);
  359. foreach($datas as $response)
  360. {
  361. $response = json_decode($response);
  362. if(!isset($response->data->items)) continue;
  363. foreach($response->data->items as $key => $dept)
  364. {
  365. $data = array();
  366. $data['id'] = $dept->open_department_id;
  367. $data['pId'] = empty($dept->parent_department_id) ? 1 : $dept->parent_department_id;
  368. $data['name'] = $dept->name;
  369. $data['open'] = 1;
  370. $depts[] = $data;
  371. $nextStepParentIdList[] = $data['id'];
  372. }
  373. if(!empty($response->data->page_token)) $nextPageTokenPairs[$data['pId']] = $response->data->page_token;
  374. }
  375. $depts = array_merge($depts, $this->getNextStepDeptTree($nextStepParentIdList));
  376. $depts = array_merge($depts, $this->getNextPageDeptTree($nextPageTokenPairs));
  377. return $depts;
  378. }
  379. /**
  380. * 根据open_id列表,获取用户。
  381. * Batch get users by open_id list.
  382. *
  383. * @param array $userIdList
  384. * @access public
  385. * @return array
  386. */
  387. public function batchGetUsers($userIdList)
  388. {
  389. $openidPairs = array();
  390. $userGroup = array_chunk($userIdList, 49);
  391. foreach($userGroup as $userIdList)
  392. {
  393. $urls = array();
  394. foreach($userIdList as $userID) $urls[] = $this->apiUrl . "contact/v3/users/{$userID}";
  395. $datas = $this->multiRequest($urls);
  396. foreach($datas as $response)
  397. {
  398. $response = json_decode($response);
  399. if(empty($response->data->user)) continue;
  400. $user = $response->data->user;
  401. $openidPairs[$user->open_id] = $user->name;
  402. }
  403. }
  404. return $openidPairs;
  405. }
  406. /**
  407. * Check for errors.
  408. *
  409. * @access public
  410. * @return bool
  411. */
  412. public function isError()
  413. {
  414. return !empty($this->errors);
  415. }
  416. /**
  417. * Get errors.
  418. *
  419. * @access public
  420. * @return array
  421. */
  422. public function getErrors()
  423. {
  424. $errors = $this->errors;
  425. $this->errors = array();
  426. return $errors;
  427. }
  428. }