enti -> crea lotto -> aggiungi posizione -> carica PDF -> conferma -> stato -> cambiamenti. // ===== Impostazioni: per la produzione cambiano solo BASE, CLIENTE, KID e il file della chiave ===== $BASE = getenv('HUB_BASE') ?: 'https://supabase-test.infotecservizi.it/functions/v1'; $CLIENTE = getenv('HUB_CLIENTE') ?: 'IL-TUO-IDENTIFICATIVO-CLIENTE'; $KID = getenv('HUB_KID') ?: 'il-tuo-kid'; $CHIAVE = getenv('HUB_CHIAVE') ?: './privata.pem'; // PEM, EC P-256 (ES256) o RSA (RS256) $CF_ENTE = getenv('HUB_CF_ENTE') ?: 'CODICE-FISCALE-ENTE'; $PDF = getenv('HUB_PDF') ?: './atto.pdf'; // ==================================================================================================== function b64u(string $b): string { return rtrim(strtr(base64_encode($b), '+/', '-_'), '='); } // OpenSSL firma ECDSA in DER; JWT (ES256) vuole r||s di 32 byte ciascuno. function derInJose(string $der): string { $p = 2 + ((ord($der[1]) & 0x80) ? (ord($der[1]) & 0x7f) : 0); $lr = ord($der[$p + 1]); $r = substr($der, $p + 2, $lr); $p += 2 + $lr; $ls = ord($der[$p + 1]); $s = substr($der, $p + 2, $ls); $r = str_pad(ltrim($r, "\x00"), 32, "\x00", STR_PAD_LEFT); $s = str_pad(ltrim($s, "\x00"), 32, "\x00", STR_PAD_LEFT); return $r . $s; } // Ripetizioni: 429 rispetta Retry-After; 5xx ed errori di rete con attese crescenti (1, 2, 4, 8 s). // $corpo può essere una funzione: si richiama a ogni ripetizione (serve per il lasciapassare, jti mai riusato). function chiama(string $metodo, string $url, array $intestazioni = [], $corpo = null): array { global $BASE; for ($i = 0; ; $i++) { $dati = is_callable($corpo) ? $corpo() : $corpo; $ch = curl_init($url); $ritorno = []; curl_setopt_array($ch, [ CURLOPT_CUSTOMREQUEST => $metodo, CURLOPT_RETURNTRANSFER => true, CURLOPT_TIMEOUT => 60, CURLOPT_HTTPHEADER => $intestazioni, CURLOPT_HEADERFUNCTION => function ($c, $riga) use (&$ritorno) { if (strpos($riga, ':') !== false) { [$k, $v] = explode(':', $riga, 2); $ritorno[strtolower(trim($k))] = trim($v); } return strlen($riga); }, ]); if ($dati !== null) curl_setopt($ch, CURLOPT_POSTFIELDS, $dati); $testo = curl_exec($ch); $stato = curl_getinfo($ch, CURLINFO_RESPONSE_CODE); curl_close($ch); if ($testo === false || (($stato === 429 || $stato >= 500) && $i < 4)) { if ($i >= 4) throw new RuntimeException("Servizio non raggiungibile: $url"); sleep((int)($ritorno['retry-after'] ?? (2 ** $i))); continue; } $json = json_decode($testo, true) ?? ['testo' => $testo]; echo "$metodo " . str_replace($BASE, '', $url) . " -> $stato" . (isset($json['id_richiesta']) ? " (id_richiesta {$json['id_richiesta']})" : '') . "\n"; if ($stato >= 400) echo json_encode($json, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE) . "\n"; return $json; } } function asserzione(string $aud): string { global $CLIENTE, $KID, $CHIAVE; $chiave = openssl_pkey_get_private(file_get_contents($CHIAVE)); if ($chiave === false) throw new RuntimeException('Chiave privata non leggibile'); $ec = openssl_pkey_get_details($chiave)['type'] === OPENSSL_KEYTYPE_EC; $alg = $ec ? 'ES256' : 'RS256'; $ora = time(); $testa = b64u(json_encode(['alg' => $alg, 'kid' => $KID, 'typ' => 'JWT'])); $corpo = b64u(json_encode(['iss' => $CLIENTE, 'sub' => $CLIENTE, 'aud' => $aud, 'iat' => $ora, 'exp' => $ora + 120, 'jti' => bin2hex(random_bytes(16))], JSON_UNESCAPED_SLASHES)); openssl_sign("$testa.$corpo", $firma, $chiave, OPENSSL_ALGO_SHA256); if ($ec) $firma = derInJose($firma); return "$testa.$corpo." . b64u($firma); } function lasciapassare(): string { global $BASE; $aud = "$BASE/api-token"; $r = chiama('POST', $aud, ['Content-Type: application/x-www-form-urlencoded'], fn() => http_build_query([ 'grant_type' => 'client_credentials', 'client_assertion_type' => 'urn:ietf:params:oauth:client-assertion-type:jwt-bearer', 'client_assertion' => asserzione($aud), ])); return $r['access_token']; } $auth = 'Authorization: Bearer ' . lasciapassare(); $L = "$BASE/api-sh/enti/" . rawurlencode($CF_ENTE) . '/lotti'; $idLotto = 'ESEMPIO-' . time(); chiama('GET', "$BASE/api-sh/enti", [$auth]); $lotto = chiama('POST', $L, [$auth, 'Content-Type: application/json', "Idempotency-Key: $idLotto"], json_encode([ 'scenario' => 'posta', 'id_lotto_esterno' => $idLotto, 'titolo' => "Lotto d'esempio", 'opzioni' => ['prodotto' => 'ordinaria', 'stampa' => ['colore' => false, 'fronte_retro' => true]], ])); $codice = $lotto['codice_lotto']; $protocollo = "$idLotto-1"; chiama('POST', "$L/$codice/posizioni", [$auth, 'Content-Type: application/json'], json_encode(['posizioni' => [[ 'protocollo_pa' => $protocollo, 'causale' => "Comunicazione d'esempio", 'destinatario' => ['cf_piva' => 'RSSMRA85T10A562S', 'tipo_persona' => 'fisica', 'denominazione' => 'Mario Rossi (prova)'], 'indirizzo' => ['indirizzo' => 'Via Roma 1', 'cap' => '00187', 'comune' => 'Roma', 'provincia' => 'RM', 'stato' => 'IT'], 'documenti' => [['tipo' => 'atto', 'nome' => 'atto.pdf']], ]]])); $pdf = file_get_contents($PDF); chiama('PUT', "$L/$codice/posizioni/" . rawurlencode($protocollo) . '/documenti/atto.pdf', [$auth, 'Content-Type: application/pdf', 'X-Content-SHA256: ' . hash('sha256', $pdf)], $pdf); chiama('POST', "$L/$codice/conferma", [$auth]); chiama('GET', "$L/$codice", [$auth]); $cambi = chiama('GET', "$BASE/api-sh/enti/" . rawurlencode($CF_ENTE) . '/cambiamenti', [$auth]); echo 'Segnalibro da conservare: ' . (!empty($cambi['segnalibro']) ? 'sì' : 'no') . "\n";