Webhook: verifica della firma

Descrizione

Ogni webhook inviato da FattureWeb è firmato con algoritmo HMAC-SHA256. La firma permette al cliente di verificare che la richiesta ricevuta provenga realmente da FattureWeb e che il payload non sia stato modificato.

Il secret viene generato quando il webhook viene registrato e deve essere conservato dal cliente.

Header ricevuti

X-FattureWeb-Event: evt_20260515163625_4466fbb0bcd9c3ff23c4dd09
X-FattureWeb-Event-Type: fattura.stato_aggiornato
X-FattureWeb-Timestamp: 1778855788
X-FattureWeb-Signature: sha256=...

Regola di firma

La firma viene calcolata usando questa stringa:

timestamp + "." + payload_json_raw

In PHP:

hash_hmac('sha256', $timestamp . '.' . $payload_raw, $secret)

Il valore finale viene inviato nell'header:

X-FattureWeb-Signature: sha256=<firma_calcolata>
Importante: il payload deve essere letto in formato raw, prima di effettuare json_decode. Se il JSON viene ricostruito o formattato diversamente, la firma non coinciderà.

Esempio endpoint PHP

<?php
            
$secret = 'whsec_INSERIRE_SECRET_RICEVUTO_DA_FATTUREWEB';

$payload_raw = file_get_contents('php://input');

$timestamp = $_SERVER['HTTP_X_FATTUREWEB_TIMESTAMP'] ?? '';
$signature_header = $_SERVER['HTTP_X_FATTUREWEB_SIGNATURE'] ?? '';

if ($timestamp === '' || $signature_header === '') {
    http_response_code(401);
    exit('Missing webhook signature');
}

// Protezione replay: accetto solo webhook generati negli ultimi 5 minuti
if (abs(time() - intval($timestamp)) > 300) {
    http_response_code(401);
    exit('Expired webhook timestamp');
}

$expected_signature = 'sha256=' . hash_hmac(
    'sha256',
    $timestamp . '.' . $payload_raw,
    $secret
);

if (! hash_equals($expected_signature, $signature_header)) {
    http_response_code(401);
    exit('Invalid webhook signature');
}

$payload = json_decode($payload_raw, true);

if (! is_array($payload)) {
    http_response_code(400);
    exit('Invalid JSON');
}

$event_type = $payload['event_type'] ?? '';
$data = $payload['data'] ?? array();

switch ($event_type) {
    case 'fattura.stato_aggiornato':
        // Aggiorna la fattura usando $data['id_sdi'], $data['stato'], ecc.
        break;
        
    case 'fattura.scartata':
        // Gestisci lo scarto della fattura.
        break;
        
    case 'fattura_passiva.ricevuta':
        // Importa o segnala la nuova fattura passiva.
        break;
}

http_response_code(200);
echo 'OK';

?>

Risposta attesa dal cliente

L'endpoint del cliente deve rispondere con uno dei seguenti codici HTTP per confermare la corretta ricezione:

  • 200 OK
  • 201 Created
  • 202 Accepted
  • 204 No Content

Qualsiasi altro codice HTTP viene considerato errore e potrà causare un nuovo tentativo di invio.