lucca_client.php 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290
  1. <?php
  2. /**
  3. * Client API Lucca
  4. *
  5. * Fonctions utilitaires pour communiquer avec l'API Lucca
  6. * Configuration via variables d'environnement pour préprod/prod
  7. */
  8. // --- Configuration (change à l'env de préprod / prod via variables d'environnement) ---
  9. define('LUCCA_API_BASE', getenv('LUCCA_API_BASE') ?: 'https://siparh-livinweb.sandbox.eu1.luccasoftware.com');
  10. define('LUCCA_API_TOKEN', getenv('LUCCA_API_TOKEN') ?: 'ed29a0a8-d394-4c93-b4f7-222360f8b465');
  11. // --- Client HTTP minimal vers Lucca ---
  12. /**
  13. * Effectue une requête HTTP vers l'API Lucca avec gestion avancée des erreurs
  14. *
  15. * @param string $method Méthode HTTP (GET, POST, PUT, DELETE, etc.)
  16. * @param string $path Chemin de l'endpoint (ex: /users, /leaves)
  17. * @param array $query Paramètres de query string
  18. * @param mixed $body Corps de la requête (array ou string)
  19. * @param int $timeout Timeout en secondes
  20. * @param bool $debug Active le mode debug Lucca ($debug=true)
  21. * @return array [
  22. * 'code' => int,
  23. * 'body' => string,
  24. * 'data' => array|null (JSON décodé),
  25. * 'error' => string|null,
  26. * 'lucca_error' => string|null (X-Lucca-ErrorMessage header),
  27. * 'error_message' => string|null (ErrorMessage du body),
  28. * 'headers' => array,
  29. * 'curl_info' => array
  30. * ]
  31. */
  32. function lucca_request(string $method, string $path, array $query = [], $body = null, int $timeout = 20, bool $debug = false): array {
  33. // Ajout automatique du paramètre $debug si demandé
  34. if ($debug) {
  35. $query['$debug'] = 'true';
  36. }
  37. $url = rtrim(LUCCA_API_BASE, '/') . '/' . ltrim($path, '/');
  38. if (!empty($query)) {
  39. $url .= '?' . http_build_query($query);
  40. }
  41. $headers = [
  42. 'Accept: application/json',
  43. 'Content-Type: application/json',
  44. 'Authorization: lucca application=' . LUCCA_API_TOKEN,
  45. ];
  46. // --- CAS 1 : cURL dispo → version propre PROD
  47. if (function_exists('curl_init')) {
  48. $ch = curl_init($url);
  49. curl_setopt_array($ch, [
  50. CURLOPT_CUSTOMREQUEST => strtoupper($method),
  51. CURLOPT_RETURNTRANSFER => true,
  52. CURLOPT_HEADER => true, // ✅ Inclure les headers dans la réponse
  53. CURLOPT_HTTPHEADER => $headers,
  54. CURLOPT_TIMEOUT => $timeout, // Utilise le paramètre $timeout passé à la fonction
  55. CURLOPT_CONNECTTIMEOUT => min(30, $timeout), // Timeout de connexion augmenté à 30s max
  56. CURLOPT_SSL_VERIFYPEER => false, // Pour test local/sandbox
  57. CURLOPT_SSL_VERIFYHOST => false, // Pour test local/sandbox
  58. CURLOPT_FOLLOWLOCATION => true,
  59. CURLOPT_VERBOSE => false,
  60. ]);
  61. if ($body !== null) {
  62. curl_setopt($ch, CURLOPT_POSTFIELDS, is_string($body) ? $body : json_encode($body, JSON_UNESCAPED_UNICODE));
  63. }
  64. $response = curl_exec($ch);
  65. $code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
  66. $header_size = curl_getinfo($ch, CURLINFO_HEADER_SIZE);
  67. $err = curl_error($ch);
  68. $errno = curl_errno($ch);
  69. $info = curl_getinfo($ch);
  70. curl_close($ch);
  71. // Séparer headers et body
  72. $response_headers = substr($response, 0, $header_size);
  73. $response_body = substr($response, $header_size);
  74. // ✅ Extraction du header X-Lucca-ErrorMessage
  75. $lucca_error = null;
  76. if (preg_match('/X-Lucca-ErrorMessage:\s*(.+)/i', $response_headers, $match)) {
  77. $lucca_error = trim($match[1]);
  78. }
  79. // ✅ Parser les headers en tableau
  80. $headers_array = [];
  81. foreach (explode("\r\n", $response_headers) as $line) {
  82. if (strpos($line, ':') !== false) {
  83. list($key, $value) = explode(':', $line, 2);
  84. $headers_array[trim($key)] = trim($value);
  85. }
  86. }
  87. // ✅ Décoder le body JSON
  88. $data = json_decode($response_body, true);
  89. // ✅ Extraire ErrorMessage du body si présent
  90. $error_message_field = null;
  91. if (is_array($data) && isset($data['ErrorMessage'])) {
  92. $error_message_field = $data['ErrorMessage'];
  93. }
  94. // Diagnostic détaillé cURL
  95. $error_curl = null;
  96. if ($errno !== 0) {
  97. $error_curl = "cURL Error #$errno: $err";
  98. } elseif ($code === 0) {
  99. $error_curl = "Connection failed - no response from server. Check network/firewall. URL: $url";
  100. }
  101. return [
  102. 'code' => (int)$code,
  103. 'body' => $response_body ?: '',
  104. 'data' => $data,
  105. 'error' => $error_curl,
  106. 'lucca_error' => $lucca_error,
  107. 'error_message' => $error_message_field,
  108. 'headers' => $headers_array,
  109. 'curl_info' => [
  110. 'url' => $info['url'] ?? $url,
  111. 'total_time' => $info['total_time'] ?? 0,
  112. 'namelookup_time' => $info['namelookup_time'] ?? 0,
  113. 'connect_time' => $info['connect_time'] ?? 0,
  114. ]
  115. ];
  116. }
  117. // --- CAS 2 : PAS de cURL → fallback file_get_contents (local Windows, test rapide)
  118. // $opts = [
  119. // 'http' => [
  120. // 'method' => strtoupper($method),
  121. // 'header' => implode("\r\n", $headers),
  122. // 'timeout' => $timeout,
  123. // 'ignore_errors' => true
  124. // ],
  125. // 'ssl' => [
  126. // 'verify_peer' => false, // TEST LOCAL SEULEMENT
  127. // 'verify_peer_name' => false // TEST LOCAL SEULEMENT
  128. // ]
  129. // ];
  130. // if ($body !== null) {
  131. // $opts['http']['content'] = is_string($body) ? $body : json_encode($body, JSON_UNESCAPED_UNICODE);
  132. // }
  133. // $context = stream_context_create($opts);
  134. // $start_time = microtime(true);
  135. // // Capture les erreurs PHP
  136. // $old_error_handler = set_error_handler(function($errno, $errstr) {
  137. // return true; // Supprime l'affichage de l'erreur
  138. // });
  139. // $response = file_get_contents($url, false, $context);
  140. // $last_error = error_get_last();
  141. // if ($old_error_handler) {
  142. // set_error_handler($old_error_handler);
  143. // } else {
  144. // restore_error_handler();
  145. // }
  146. // $elapsed_time = microtime(true) - $start_time;
  147. // $code = 0;
  148. // $error_message = null;
  149. // if ($response === false) {
  150. // $error_message = "file_get_contents failed";
  151. // if ($last_error) {
  152. // $error_message .= ": " . $last_error['message'];
  153. // }
  154. // $error_message .= " | allow_url_fopen=" . ini_get('allow_url_fopen');
  155. // }
  156. // foreach ($http_response_header ?? [] as $line) {
  157. // if (preg_match('#HTTP/.* ([0-9]+)#', $line, $m)) {
  158. // $code = (int)$m[1];
  159. // break;
  160. // }
  161. // }
  162. // return [
  163. // 'code' => $code,
  164. // 'body' => $response ?: '',
  165. // 'error' => $error_message,
  166. // 'curl_info' => [
  167. // 'url' => $url,
  168. // 'total_time' => $elapsed_time,
  169. // 'namelookup_time' => 0,
  170. // 'connect_time' => 0,
  171. // 'method' => 'file_get_contents (fallback)'
  172. // ]
  173. // ];
  174. }
  175. /**
  176. * Fonction helper pour appeler Lucca et gérer les erreurs proprement
  177. *
  178. * @param string $method Méthode HTTP
  179. * @param string $path Chemin de l'endpoint
  180. * @param array $query Paramètres query string
  181. * @param mixed $body Corps de la requête
  182. * @param bool $debug Active le mode debug Lucca
  183. * @return array Les données décodées (data) en cas de succès
  184. * @throws Exception En cas d'erreur détaillée
  185. */
  186. function lucca_request_safe(string $method, string $path, array $query = [], $body = null, bool $debug = false): array {
  187. $result = lucca_request($method, $path, $query, $body, 20, $debug);
  188. // Erreur cURL
  189. if (!empty($result['error'])) {
  190. throw new Exception("Erreur cURL: " . $result['error']);
  191. }
  192. // Erreur dans le header X-Lucca-ErrorMessage
  193. if (!empty($result['lucca_error'])) {
  194. throw new Exception("Erreur Lucca (header): " . $result['lucca_error']);
  195. }
  196. // Erreur dans le body ErrorMessage
  197. if (!empty($result['error_message'])) {
  198. throw new Exception("Erreur Lucca (body): " . $result['error_message']);
  199. }
  200. // Code HTTP non-2xx
  201. if ($result['code'] < 200 || $result['code'] >= 300) {
  202. $error = "Erreur HTTP {$result['code']}";
  203. // Essayer d'extraire plus d'infos du body
  204. if (isset($result['data']['title'])) {
  205. $error .= ": " . $result['data']['title'];
  206. }
  207. if (isset($result['data']['traceId'])) {
  208. $error .= " (traceId: {$result['data']['traceId']})";
  209. }
  210. throw new Exception($error);
  211. }
  212. return $result['data'] ?? [];
  213. }
  214. /**
  215. * Formatte une réponse d'erreur détaillée pour les endpoints
  216. *
  217. * @param array $result Résultat de lucca_request()
  218. * @return array Payload d'erreur formaté pour json_response()
  219. */
  220. function lucca_format_error(array $result): array {
  221. $error = [
  222. "error" => "Erreur API Lucca",
  223. "http_code" => $result['code'],
  224. "response_body" => $result['body']
  225. ];
  226. // ✅ Ajouter X-Lucca-ErrorMessage si présent
  227. if (!empty($result['lucca_error'])) {
  228. $error['lucca_error_header'] = $result['lucca_error'];
  229. }
  230. // ✅ Ajouter ErrorMessage du body si présent
  231. if (!empty($result['error_message'])) {
  232. $error['lucca_error_message'] = $result['error_message'];
  233. }
  234. // ✅ Ajouter les détails du data si disponible
  235. if (!empty($result['data'])) {
  236. if (isset($result['data']['title'])) {
  237. $error['title'] = $result['data']['title'];
  238. }
  239. if (isset($result['data']['traceId'])) {
  240. $error['trace_id'] = $result['data']['traceId'];
  241. }
  242. if (isset($result['data']['type'])) {
  243. $error['type'] = $result['data']['type'];
  244. }
  245. }
  246. // Erreur cURL
  247. if (!empty($result['error'])) {
  248. $error['curl_error'] = $result['error'];
  249. }
  250. return $error;
  251. }