> ## Documentation Index
> Fetch the complete documentation index at: https://storekit.com/docs/llms.txt
> Use this file to discover all available pages before exploring further.

# Verifica delle firme

> Metti in sicurezza i tuoi webhook verificando la firma HMAC su ogni richiesta. Conferma che i payload provengano da storekit e non siano stati manomessi durante il trasferimento.

Verificare le firme dei webhook è fondamentale per la sicurezza. Garantisce che il webhook provenga effettivamente da storekit e non sia stato manomesso.

## Perché verificare?

Poiché il tuo endpoint webhook è pubblicamente accessibile, chiunque potrebbe inviargli richieste fingendosi storekit. La verifica della firma previene:

* **Richieste falsificate**: Attaccanti che inviano webhook fasulli
* **Attacchi di replay**: Vecchi webhook rinviati in modo malevolo
* **Manomissione dei dati**: Modifica dei payload webhook durante il transito

## Utilizzo delle librerie Svix (consigliato)

Raccomandiamo di utilizzare le librerie ufficiali Svix per la verifica, che gestiscono tutta la complessità per te:

<CodeGroup>
  ```javascript Node.js theme={null}
  import { Webhook } from 'svix';

  const wh = new Webhook(process.env.WEBHOOK_SECRET);

  try {
    const payload = wh.verify(rawBody, headers);
    // Process the verified payload
  } catch (err) {
    // Signature verification failed
    return res.status(400).send('Invalid signature');
  }
  ```

  ```python Python theme={null}
  from svix.webhooks import Webhook

  wh = Webhook(os.environ['WEBHOOK_SECRET'])

  try:
      payload = wh.verify(raw_body, headers)
      # Process the verified payload
  except Exception as e:
      # Signature verification failed
      return Response(status=400)
  ```

  ```go Go theme={null}
  import svix "github.com/svix/svix-webhooks/go"

  wh, _ := svix.NewWebhook(os.Getenv("WEBHOOK_SECRET"))

  err := wh.Verify([]byte(rawBody), headers)
  if err != nil {
      // Signature verification failed
      return
  }
  ```
</CodeGroup>

<Warning>
  Utilizza sempre il corpo grezzo della richiesta per la verifica. Se analizzi prima il JSON e poi lo trasformi in stringa, la firma non corrisponderà a causa di potenziali differenze di formattazione.
</Warning>

## Verifica manuale

Se preferisci verificare le firme manualmente senza usare la libreria Svix, segui i passaggi seguenti.

### Header della firma

Ogni webhook include questi header per la verifica:

| Header           | Descrizione                                           |
| ---------------- | ----------------------------------------------------- |
| `svix-id`        | Identificatore univoco del messaggio                  |
| `svix-timestamp` | Timestamp Unix di quando il messaggio è stato inviato |
| `svix-signature` | La firma o le firme da verificare                     |

## Passaggi di verifica

### 1. Estrai gli header

```javascript theme={null}
const svixId = request.headers['svix-id'];
const svixTimestamp = request.headers['svix-timestamp'];
const svixSignature = request.headers['svix-signature'];
```

### 2. Verifica il timestamp (previeni attacchi di replay)

Rifiuta i webhook con timestamp più vecchi di 5 minuti:

```javascript theme={null}
const tolerance = 5 * 60; // 5 minutes in seconds
const now = Math.floor(Date.now() / 1000);
const timestamp = parseInt(svixTimestamp, 10);

if (Math.abs(now - timestamp) > tolerance) {
  throw new Error('Webhook timestamp too old');
}
```

### 3. Crea il contenuto firmato

Concatena l'ID del webhook, il timestamp e il corpo:

```javascript theme={null}
const signedContent = `${svixId}.${svixTimestamp}.${rawBody}`;
```

### 4. Calcola la firma attesa

Usa HMAC-SHA256 con il tuo webhook secret:

```javascript theme={null}
const crypto = require('crypto');

// Your secret from the dashboard (remove the 'whsec_' prefix)
const secret = Buffer.from(secretKey.split('_')[1], 'base64');

const expectedSignature = crypto
  .createHmac('sha256', secret)
  .update(signedContent)
  .digest('base64');
```

### 5. Confronta le firme

```javascript theme={null}
const signatures = svixSignature.split(' ');
const isValid = signatures.some(sig => {
  const [version, signature] = sig.split(',');
  return version === 'v1' && signature === expectedSignature;
});

if (!isValid) {
  throw new Error('Invalid webhook signature');
}
```


## Related topics

- [Introduzione per sviluppatori](/docs/it/developers/introduction.md)
- [Panoramica dei webhook](/docs/it/developers/webhooks/overview.md)
- [Deliverability delle email](/docs/it/guides/notifications/email-deliverability.md)
- [Assegnazione delle portate](/docs/it/guides/menu/course-assignments.md)
- [Verifica dello stato di pagamento Pay at Table da POS o dashboard](/docs/it/guides/pay-at-table/checking-payments.md)
