# Autenticazione e Firma delle Richieste

> Firma le richieste API con HMAC-SHA256 utilizzando il tuo project UUID e l'API key.

Ogni richiesta API (eccetto i webhook in entrata) deve contenere il tuo project UUID e una firma della richiesta. La firma dimostra che la richiesta proviene da te e che nessuno l'ha modificata lungo il percorso.

## API key

2328.io utilizza **due chiavi** che condividono lo stesso algoritmo di firma ma coprono endpoint differenti:

| Chiave | Utilizzata per |
|-----|----------|
| **API key** | Pagamenti, wallet statici, saldo, tassi di cambio e verifica dei webhook di pagamento / wallet statico |
| **Payout API key** | Tutti gli endpoint `/v1/payout/*` e la verifica dei webhook di prelievo |

Entrambe le chiavi si trovano nelle impostazioni del progetto su [2328.io](https://2328.io). Negli esempi seguenti viene indicato genericamente "API key" — sostituiscila con quella corretta in base all'endpoint che stai chiamando.

> **INFO:** **Non** mescolare mai le due chiavi: firmare una richiesta di prelievo con l'API key normale (o una richiesta di pagamento con la payout key) restituisce un errore di firma.

## Header obbligatori

| Header | Tipo | Obbligatorio | Descrizione |
|--------|------|----------|-------------|
| `Content-Type` | string | sì | Sempre `application/json` |
| `project` | string | sì | Il tuo project UUID |
| `sign` | string | sì | Firma HMAC-SHA256 della richiesta, calcolata con la tua API key |
| `User-Agent` | string | sì | Identifica la tua applicazione (es. `MyShop/1.4 (+https://myshop.example)`). Le richieste senza `User-Agent` possono essere bloccate. |

## Come funziona la firma

Pensa alla firma come a un'impronta digitale del body della richiesta. Viene costruita così:

1. Serializzando il body in JSON (compatto — senza spazi extra).
2. Codificando in Base64 quel JSON. Questo passaggio normalizza l'input tra i linguaggi — una volta che è ASCII puro, ogni linguaggio produce gli stessi byte per HMAC.
3. Calcolando **HMAC-SHA256** della stringa Base64 utilizzando la tua API key, quindi convertendo il risultato in hex minuscolo.

Per le richieste **GET** e gli altri tipi senza body, firma una stringa vuota invece del JSON.

> **INFO:** La firma della stringa vuota è costante per una determinata API key. Puoi memorizzarla in cache se effettui molte chiamate GET.

## Implementazioni

#### php

```php
<?php
function apiSign(array $data, string $apiKey): string {
    $json = json_encode($data, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
    $base64 = base64_encode($json);
    return hash_hmac('sha256', $base64, $apiKey);
}
```

#### js

```js
import crypto from "crypto";

export function apiSign(data, apiKey) {
  const json = JSON.stringify(data);
  const base64 = Buffer.from(json).toString("base64");
  return crypto.createHmac("sha256", apiKey).update(base64).digest("hex");
}
```

#### ts

```ts
import { createHmac } from "crypto";

export function apiSign(data: object, apiKey: string): string {
  const json = JSON.stringify(data);
  const base64 = Buffer.from(json).toString("base64");
  return createHmac("sha256", apiKey).update(base64).digest("hex");
}
```

#### python

```python
import json
import hmac
import hashlib
import base64

def api_sign(data: dict, api_key: str) -> str:
    # ensure_ascii=False keeps non-ASCII characters (Cyrillic, Chinese, …)
    # as-is. Without it, Python escapes them to \uXXXX and the signature
    # diverges from PHP / Node / Go.
    body = json.dumps(data, separators=(",", ":"), ensure_ascii=False)
    b64 = base64.b64encode(body.encode("utf-8")).decode()
    return hmac.new(api_key.encode(), b64.encode(), hashlib.sha256).hexdigest()
```

#### go

```go
package sign

import (
    "bytes"
    "crypto/hmac"
    "crypto/sha256"
    "encoding/base64"
    "encoding/hex"
    "encoding/json"
)

func ApiSign(data any, apiKey string) (string, error) {
    // json.Encoder with SetEscapeHTML(false) — without it, Go escapes <, >, &
    // to \u003c etc., which breaks compatibility with PHP / Node / Python.
    var buf bytes.Buffer
    enc := json.NewEncoder(&buf)
    enc.SetEscapeHTML(false)
    if err := enc.Encode(data); err != nil {
        return "", err
    }
    // Encoder appends a trailing newline — drop it.
    body := bytes.TrimRight(buf.Bytes(), "\n")

    b64 := base64.StdEncoding.EncodeToString(body)
    h := hmac.New(sha256.New, []byte(apiKey))
    h.Write([]byte(b64))
    return hex.EncodeToString(h.Sum(nil)), nil
}
```

### Richieste senza body (GET)

Per le richieste con body vuoto (es. `GET /v1/payout/status/{uuid}`), firma una stringa vuota:

#### curl

```curl
SIGN=$(printf '' | openssl dgst -sha256 -hmac "$API_KEY" -hex | awk '{print $NF}')
```

#### php

```php
$sign = hash_hmac('sha256', base64_encode(''), $apiKey);
```

#### js

```js
import { createHmac } from "crypto";

const sign = createHmac("sha256", apiKey)
  .update(Buffer.from("").toString("base64"))
  .digest("hex");
```

#### ts

```ts
import { createHmac } from "crypto";

const sign: string = createHmac("sha256", apiKey)
  .update(Buffer.from("").toString("base64"))
  .digest("hex");
```

#### python

```python
import hmac
import hashlib
import base64

sign = hmac.new(
    api_key.encode(),
    base64.b64encode(b"").decode().encode(),
    hashlib.sha256,
).hexdigest()
```

#### go

```go
package sign

import (
    "crypto/hmac"
    "crypto/sha256"
    "encoding/base64"
    "encoding/hex"
)

func EmptyBodySign(apiKey string) string {
    b64 := base64.StdEncoding.EncodeToString([]byte(""))
    h := hmac.New(sha256.New, []byte(apiKey))
    h.Write([]byte(b64))
    return hex.EncodeToString(h.Sum(nil))
}
```

## Esempio completo di richiesta

#### curl

```curl
curl -X POST https://api.2328.io/api/v1/payment \
  -H "Content-Type: application/json" \
  -H "User-Agent: MyShop/1.0 (+https://myshop.example)" \
  -H "project: YOUR_PROJECT_UUID" \
  -H "sign: YOUR_HMAC_SIGNATURE" \
  -d '{"amount":"100.00","currency":"USD","order_id":"ORDER-123"}'
```

#### php

```php
<?php
function apiSign(string $body, string $apiKey): string {
    return hash_hmac('sha256', base64_encode($body), $apiKey);
}

$project = 'YOUR_PROJECT_UUID';
$apiKey  = 'YOUR_API_KEY';

$data = [
    'amount'   => '100.00',
    'currency' => 'USD',
    'order_id' => 'ORDER-123',
];

$body = json_encode($data, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
$sign = apiSign($body, $apiKey);

$ch = curl_init('https://api.2328.io/api/v1/payment');
curl_setopt_array($ch, [
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_POST => true,
    CURLOPT_POSTFIELDS => $body,
    CURLOPT_HTTPHEADER => [
        'Content-Type: application/json',
        'User-Agent: MyShop/1.0 (+https://myshop.example)',
        "project: $project",
        "sign: $sign",
    ],
]);

$response = json_decode(curl_exec($ch), true);
```

#### js

```js
import { createHmac } from "crypto";

function apiSign(body, apiKey) {
  const base64 = Buffer.from(body, "utf8").toString("base64");
  return createHmac("sha256", apiKey).update(base64).digest("hex");
}

const data = {
  amount: "100.00",
  currency: "USD",
  order_id: "ORDER-123",
};

const body = JSON.stringify(data);
const sign = apiSign(body, process.env.API_KEY);

const res = await fetch("https://api.2328.io/api/v1/payment", {
  method: "POST",
  headers: {
    "Content-Type": "application/json",
    "User-Agent": "MyShop/1.0 (+https://myshop.example)",
    project: process.env.PROJECT_UUID,
    sign,
  },
  body,
});

const json = await res.json();
```

#### ts

```ts
import { createHmac } from "crypto";

function apiSign(body: string, apiKey: string): string {
  const base64 = Buffer.from(body, "utf8").toString("base64");
  return createHmac("sha256", apiKey).update(base64).digest("hex");
}

type CreatePaymentBody = {
  amount: string;
  currency: string;
  order_id: string;
};

type CreatePaymentResponse = { state: number; result: unknown };

const data: CreatePaymentBody = {
  amount: "100.00",
  currency: "USD",
  order_id: "ORDER-123",
};

const body = JSON.stringify(data);
const sign = apiSign(body, process.env.API_KEY!);

const res = await fetch("https://api.2328.io/api/v1/payment", {
  method: "POST",
  headers: {
    "Content-Type": "application/json",
    "User-Agent": "MyShop/1.0 (+https://myshop.example)",
    project: process.env.PROJECT_UUID!,
    sign,
  },
  body,
});

const json = (await res.json()) as CreatePaymentResponse;
```

#### python

```python
import json
import hmac
import hashlib
import base64
import httpx

def api_sign(body: str, api_key: str) -> str:
    b64 = base64.b64encode(body.encode("utf-8")).decode()
    return hmac.new(api_key.encode(), b64.encode(), hashlib.sha256).hexdigest()

data = {
    "amount": "100.00",
    "currency": "USD",
    "order_id": "ORDER-123",
}

body = json.dumps(data, separators=(",", ":"), ensure_ascii=False)
sign = api_sign(body, API_KEY)

r = httpx.post(
    "https://api.2328.io/api/v1/payment",
    headers={
        "Content-Type": "application/json",
        "User-Agent": "MyShop/1.0 (+https://myshop.example)",
        "project": PROJECT_UUID,
        "sign": sign,
    },
    content=body.encode("utf-8"),
)
response = r.json()
```

#### go

```go
package main

import (
    "bytes"
    "crypto/hmac"
    "crypto/sha256"
    "encoding/base64"
    "encoding/hex"
    "encoding/json"
    "net/http"
)

func ApiSign(body []byte, apiKey string) string {
    b64 := base64.StdEncoding.EncodeToString(body)
    h := hmac.New(sha256.New, []byte(apiKey))
    h.Write([]byte(b64))
    return hex.EncodeToString(h.Sum(nil))
}

func marshalCanonical(v any) ([]byte, error) {
    var buf bytes.Buffer
    enc := json.NewEncoder(&buf)
    enc.SetEscapeHTML(false)
    if err := enc.Encode(v); err != nil {
        return nil, err
    }
    return bytes.TrimRight(buf.Bytes(), "\n"), nil
}

func main() {
    data := struct {
        Amount   string `json:"amount"`
        Currency string `json:"currency"`
        OrderID  string `json:"order_id"`
    }{
        Amount:   "100.00",
        Currency: "USD",
        OrderID:  "ORDER-123",
    }

    body, err := marshalCanonical(data)
    if err != nil {
        panic(err)
    }
    sign := ApiSign(body, apiKey)

    req, _ := http.NewRequest("POST",
        "https://api.2328.io/api/v1/payment",
        bytes.NewReader(body))
    req.Header.Set("Content-Type", "application/json")
    req.Header.Set("User-Agent", "MyShop/1.0 (+https://myshop.example)")
    req.Header.Set("project", projectUUID)
    req.Header.Set("sign", sign)

    resp, err := http.DefaultClient.Do(req)
    if err != nil {
        panic(err)
    }
    defer resp.Body.Close()
}
```

> **DANGER:** **Non esporre mai la tua API key nel codice lato client.** Firma le richieste sul tuo backend. Una API key compromessa concede a chiunque pieno accesso al tuo account merchant.

## Verifica delle firme dei webhook

Quando 2328.io ti invia un webhook, viene eseguito lo stesso algoritmo in senso inverso:

1. Estrai il campo `sign` dal payload.
2. Codifica in JSON i campi rimanenti (compatto, senza spazi).
3. Codifica in Base64 quella stringa.
4. Calcola `HMAC-SHA256` con la chiave appropriata.
5. Confrontala con il `sign` ricevuto utilizzando un confronto **a tempo costante** (`hash_equals`, `crypto.timingSafeEqual`, `hmac.compare_digest`, `subtle.ConstantTimeCompare`, `OpenSSL.fixed_length_secure_compare`).

La chiave di firma dipende dalla sorgente del webhook:

| Webhook | Chiave per la verifica |
|---------|---------------------|
| Webhook di pagamento / wallet statico (`/v1/payment`, `/v1/static-wallet`) | **API key** |
| Webhook di prelievo (`/v1/payout`) | **Payout API key** |

> **WARNING:** **Errori comuni di verifica.** Il tuo encoder JSON deve produrre **gli stessi byte identici** prodotti dal mittente — altrimenti il Base64 differisce e la firma non corrisponderà.
> 
> - **Go**: usa `json.NewEncoder` con `SetEscapeHTML(false)`. Il `json.Marshal` predefinito esegue l'escape di `<`, `>`, `&` in `<` e rompe la firma.
> - **Python**: passa `ensure_ascii=False` a `json.dumps`. Senza, i caratteri non ASCII (cirillico, cinese, …) vengono fatti escape come `\uXXXX`.
> - **JSON compatto**: nessuno spazio tra i campi (`separators=(",", ":")` in Python).
> - **Ordine dei campi** (Go): un semplice `map[string]any` randomizza le chiavi alla ri-codifica. Usa `json.RawMessage`, una struct ordinata, oppure rimuovi `sign` dai byte grezzi.
> 
> Se la verifica continua a fallire, esegui tu stesso `apiSign` sul payload — deve produrre la stessa stringa esadecimale del `sign` ricevuto.

> **INFO:** **Una firma valida non previene i replay.** Dimostra solo che il webhook proviene da 2328.io — non impedisce a un attaccante di ripubblicare in seguito un webhook *catturato*. Verifica sempre l'idempotenza tramite `uuid` (o `txid` per i wallet statici) prima di accreditare i fondi. Rifiuta con HTTP `401` se la firma è mancante o errata.

Gli esempi di codice completi sono su **[Webhook Notifications](/docs/webhooks#verifying-the-signature)**. La gestione dei retry e le regole di idempotenza sono in [Best practice](/docs/webhooks#best-practices).