moi()["etudes"][0]["id"]; * $m = $cd->creerMission($etude, ["reference" => "2026-0412", "nature" => "Constat d'état des lieux", * "requerant" => ["type" => "societe", "denomination" => "SCI Les Tilleuls"], * "lieu" => ["adresse" => "12 rue de la République", "code_postal" => "69002", "ville" => "Lyon"]]); * $fichiers = $cd->telechargerConstat($etude, $constat, "/srv/dossiers/2026-0412"); * * Le jeton (5 minutes) est obtenu et renouvelé tout seul ; une erreur de l'API lève ConstatDirect\ErreurConnect. */ namespace ConstatDirect; class ErreurConnect extends \Exception { public $statut; public $codeApi; public $details; public function __construct(int $statut, string $code, string $message, array $details = []) { parent::__construct("$statut $code : $message"); $this->statut = $statut; $this->codeApi = $code; $this->details = $details; } } class Connect { const PRODUCTION = "https://api.constatdirect.com"; const ESSAI = "https://api-essai.constatdirect.com"; private $editeur, $api, $certificat, $cle, $jeton = null, $expire = 0; public function __construct(string $editeur, string $certificat, string $cle, bool $essai = false, ?string $api = null) { $this->editeur = $editeur; $this->api = rtrim($api ?? ($essai ? self::ESSAI : self::PRODUCTION), "/"); $this->certificat = $certificat; $this->cle = $cle; } private static function b64(string $s): string { return rtrim(strtr(base64_encode($s), "+/", "-_"), "="); } /** Signature ECDSA DER -> r||s (64 octets), format du JWT. */ private static function derVersRs(string $der): string { $pos = 2; if (ord($der[1]) & 0x80) { $pos += ord($der[1]) & 0x7f; } $lr = ord($der[$pos + 1]); $r = substr($der, $pos + 2, $lr); $pos += 2 + $lr; $ls = ord($der[$pos + 1]); $s = substr($der, $pos + 2, $ls); return str_pad(ltrim($r, "\0"), 32, "\0", STR_PAD_LEFT) . str_pad(ltrim($s, "\0"), 32, "\0", STR_PAD_LEFT); } private function assertion(): string { $cle = openssl_pkey_get_private(file_get_contents($this->cle)); $ec = openssl_pkey_get_details($cle)["type"] === OPENSSL_KEYTYPE_EC; $t = time(); $a = self::b64(json_encode(["alg" => $ec ? "ES256" : "RS256", "typ" => "JWT"])); $c = self::b64(json_encode(["iss" => $this->editeur, "sub" => $this->editeur, "aud" => $this->api . "/v1/jeton", "iat" => $t, "exp" => $t + 120, "jti" => bin2hex(random_bytes(16))])); openssl_sign("$a.$c", $sig, $cle, OPENSSL_ALGO_SHA256); return "$a.$c." . self::b64($ec ? self::derVersRs($sig) : $sig); } private function curl(string $methode, string $url, array $entetes, $corps = null, ?string $fichier = null): array { $c = curl_init($url); $h = fopen("php://temp", "w+"); curl_setopt_array($c, [CURLOPT_SSLCERT => $this->certificat, CURLOPT_SSLKEY => $this->cle, CURLOPT_CUSTOMREQUEST => $methode, CURLOPT_HTTPHEADER => $entetes, CURLOPT_TIMEOUT => 120, CURLOPT_USERAGENT => "constatdirect-connect-php/1.0.0"]); if ($corps !== null) { curl_setopt($c, CURLOPT_POSTFIELDS, $corps); } $f = null; if ($fichier !== null) { $f = fopen($fichier, "wb"); curl_setopt($c, CURLOPT_FILE, $f); } else { curl_setopt($c, CURLOPT_RETURNTRANSFER, true); } $r = curl_exec($c); $statut = curl_getinfo($c, CURLINFO_RESPONSE_CODE); $erreur = curl_error($c); curl_close($c); if ($f) { fclose($f); $r = $statut >= 400 ? file_get_contents($fichier) : ""; } if ($statut === 0) { throw new ErreurConnect(0, "connexion", "Connexion impossible : $erreur"); } return [$statut, (string)$r]; } private static function verifier(int $statut, string $texte): ?array { $j = $texte === "" ? null : json_decode($texte, true); if ($statut >= 400) { $e = $j["erreur"] ?? ["code" => "http_$statut", "message" => substr($texte, 0, 300)]; throw new ErreurConnect($statut, (string)$e["code"], (string)$e["message"], $e["details"] ?? []); } return $j; } private function jeton(bool $forcer = false): string { if ($forcer || $this->jeton === null || time() > $this->expire - 60) { [$s, $t] = $this->curl("POST", $this->api . "/v1/jeton", ["Content-Type: application/x-www-form-urlencoded"], http_build_query([ "grant_type" => "client_credentials", "client_assertion_type" => "urn:ietf:params:oauth:client-assertion-type:jwt-bearer", "client_assertion" => $this->assertion()])); $j = self::verifier($s, $t); $this->jeton = $j["access_token"]; $this->expire = time() + (int)$j["expires_in"]; } return $this->jeton; } /** Appel authentifié ; un jeton refusé est renouvelé une fois, automatiquement. */ public function appel(string $methode, string $chemin, $json = null, array $entetes = [], ?string $brut = null, ?string $fichier = null): ?array { $url = strpos($chemin, "http") === 0 ? $chemin : $this->api . $chemin; for ($essai = 0; ; $essai++) { $h = array_merge(["Authorization: Bearer " . $this->jeton($essai === 1)], $entetes); $corps = $brut; if ($json !== null) { $h[] = "Content-Type: application/json"; $corps = json_encode($json, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES); } [$s, $t] = $this->curl($methode, $url, $h, $corps, $fichier); if ($s === 401 && $essai === 0 && strpos($t, '"jeton_invalide"') !== false) { continue; } return self::verifier($s, $t); } } public function moi(): array { return $this->appel("GET", "/v1/moi"); } public function commissaires(string $e): array { return $this->appel("GET", "/v1/etudes/$e/commissaires")["commissaires"]; } public function modeles(string $e): array { return $this->appel("GET", "/v1/etudes/$e/modeles")["modeles"]; } public function constats(string $e, ?string $depuis = null, int $limite = 50): array { return $this->appel("GET", "/v1/etudes/$e/constats?" . http_build_query(array_filter(["depuis" => $depuis, "limite" => $limite]))); } public function fiche(string $e, string $c): array { return $this->appel("GET", "/v1/etudes/$e/constats/$c"); } public function preuves(string $e, string $c): array { return $this->appel("GET", "/v1/etudes/$e/constats/$c/preuves"); } public function evenements(string $e, int $apres = 0): array { return $this->appel("GET", "/v1/etudes/$e/evenements?apres=$apres"); } /** Crée une mission ; rejouer la même clé ne crée jamais de doublon. */ public function creerMission(string $e, array $mission, ?string $cle = null): array { $cle = $cle ?? "mission-" . substr(hash("sha256", json_encode($mission)), 0, 40); return $this->appel("POST", "/v1/etudes/$e/missions", $mission, ["Idempotency-Key: $cle"]); } public function annulerMission(string $e, string $m, string $motif = ""): array { return $this->appel("POST", "/v1/etudes/$e/missions/$m/annulation", ["motif" => $motif]); } /** Télécharge les fichiers autorisés dans $dossier, chacun vérifié par son empreinte SHA-256. */ public function telechargerConstat(string $e, string $c, string $dossier): array { if (!is_dir($dossier)) { mkdir($dossier, 0750, true); } $sortie = []; foreach ($this->appel("GET", "/v1/etudes/$e/constats/$c/fichiers")["fichiers"] as $f) { $chemin = rtrim($dossier, "/") . "/" . basename($f["nom"]); $this->appel("GET", $f["lien"], null, [], null, "$chemin.part"); if (hash_file("sha256", "$chemin.part") !== $f["sha256"]) { unlink("$chemin.part"); throw new ErreurConnect(0, "empreinte_differente", "Le fichier {$f['nom']} est arrivé abîmé."); } rename("$chemin.part", $chemin); $sortie[] = $chemin; } return $sortie; } public function deposerActeSigne(string $e, string $c, string $pdf): array { $octets = file_get_contents($pdf); return $this->appel("POST", "/v1/etudes/$e/constats/$c/acte-signe", null, ["Content-Type: application/pdf", "X-Contenu-Sha256: " . hash("sha256", $octets), "X-Nom-Fichier: " . basename($pdf)], $octets); } /** Vrai si le message de suivi vient de Constat Direct (Ed25519 sur « t.corps ») et date de moins de 5 minutes. */ public static function verifierMessage(string $signature, string $corps, string $clePubliquePem, int $ecartMax = 300): bool { $p = []; foreach (explode(",", $signature) as $m) { [$k, $v] = explode("=", $m, 2); $p[$k] = $v; } if (abs(time() - (int)$p["t"]) > $ecartMax) { return false; } $der = base64_decode(preg_replace('/-----[^-]+-----|\s/', '', $clePubliquePem)); return sodium_crypto_sign_verify_detached(base64_decode($p["ed25519"]), $p["t"] . "." . $corps, substr($der, -32)); } }