# Webhook tramite API (e quello che nasce con l'attivazione)

`POST /v1/webhooks`

Gli stessi webhook del pannello, gestiti con la tua chiave API su `/v1/webhooks`: creare (`POST /v1/webhooks`), elencare (`GET /v1/webhooks`), vederne uno (`GET /v1/webhooks/:id`), modificarlo (`PATCH /v1/webhooks/:id`), eliminarlo (`DELETE /v1/webhooks/:id`), provarlo (`POST /v1/webhooks/:id/test`, un evento firmato inviato subito) e cambiarne il segreto (`POST /v1/webhooks/:id/rotate-secret`). Un webhook **senza** `connectionId` è dell'account; **con** esso, riceve solo gli eventi di quel numero e sostituisce quello dell'account per quel numero. Il numero si indica con il suo `conn_…` **o con il tuo `externalId`**, e così torna anche in ogni risposta (con il suo `externalId` accanto): mai un id interno. Il segreto di firma (`whsec_…`) e il token di intestazione, se l'hai chiesto con `headerToken: true`, si mostrano **una sola volta**.

**Il webhook che nasce con l'attivazione.** Se integri con i link di attivazione, invia `webhook: { url, events }` in `POST /v1/onboarding-links`: lo validiamo alla creazione del link e ti restituiamo il segreto **in quel momento**. Quando il tuo cliente finisce, il numero nasce con il suo webhook, firmato con QUEL segreto, e prima di `connection.created`: quell'evento gli arriva già. Poi lo trovi con `GET /v1/webhooks?externalId=…`.

## Esempi

### cURL

```bash
# 1) onboarding link + the webhook of the number it will connect
curl -X POST https://api.waiaconnect.com/v1/onboarding-links \
  -H "Authorization: Bearer wc_live_YOUR_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{"externalId": "pharmacy-42", "webhook": {"url": "https://api.yourcompany.com/hooks/connect", "events": ["connection.created", "message.received", "message.status"]}}'
# → { "url": "https://…/c/<token>", "publicId": "onb_…",
#     "webhook": { "secret": "whsec_…", "createdOnCompletion": true, … } }   ← store the secret NOW

# 2) after your customer connects: the number's webhooks, by your externalId
curl "https://api.waiaconnect.com/v1/webhooks?externalId=pharmacy-42" -H "Authorization: Bearer wc_live_YOUR_API_KEY"
# → { "webhooks": [ { "id": "wh_…", "connectionId": "conn_…", "externalId": "pharmacy-42", … } ] }

# 3) create one directly (connectionId = conn_… or your externalId; omit = account-wide)
curl -X POST https://api.waiaconnect.com/v1/webhooks \
  -H "Authorization: Bearer wc_live_YOUR_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{"url": "https://api.yourcompany.com/hooks/connect-2", "connectionId": "pharmacy-42"}'

# rotate the secret (the old one stops verifying at once)
curl -X POST https://api.waiaconnect.com/v1/webhooks/wh_…/rotate-secret -H "Authorization: Bearer wc_live_YOUR_API_KEY"
```

### Node.js

```javascript
const H = { "Authorization": "Bearer wc_live_YOUR_API_KEY", "Content-Type": "application/json" };

// 1) onboarding link + the webhook of the number it will connect
const link = await (await fetch("https://api.waiaconnect.com/v1/onboarding-links", {
  method: "POST", headers: H,
  body: JSON.stringify({
    externalId: "pharmacy-42",
    webhook: { url: "https://api.yourcompany.com/hooks/connect", events: ["connection.created", "message.received", "message.status"] }
  })
})).json();
await saveSecret("pharmacy-42", link.webhook.secret); // shown ONCE — it signs this number's events

// 2) later: the number's webhooks, by your externalId
const { webhooks } = await (await fetch("https://api.waiaconnect.com/v1/webhooks?externalId=pharmacy-42", { headers: H })).json();

// rotate the secret (the old one stops verifying at once)
const rotated = await (await fetch(`https://api.waiaconnect.com/v1/webhooks/${webhooks[0].id}/rotate-secret`, { method: "POST", headers: H })).json();
await saveSecret("pharmacy-42", rotated.secret);
```

### PHP

```php
<?php
function connect($method, $url, $body = null) {
  $ch = curl_init($url);
  curl_setopt_array($ch, [
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_CUSTOMREQUEST => $method,
    CURLOPT_HTTPHEADER => ["Authorization: Bearer wc_live_YOUR_API_KEY", "Content-Type: application/json"],
    CURLOPT_POSTFIELDS => $body ? json_encode($body) : null,
  ]);
  return json_decode(curl_exec($ch), true);
}
// 1) onboarding link + the webhook of the number it will connect
$link = connect("POST", "https://api.waiaconnect.com/v1/onboarding-links", [
  "externalId" => "pharmacy-42",
  "webhook" => ["url" => "https://api.yourcompany.com/hooks/connect", "events" => ["connection.created", "message.received", "message.status"]],
]);
save_secret("pharmacy-42", $link["webhook"]["secret"]); // shown ONCE

// 2) later: the number's webhooks, by your externalId
$list = connect("GET", "https://api.waiaconnect.com/v1/webhooks?externalId=pharmacy-42");
// rotate the secret (the old one stops verifying at once)
$rotated = connect("POST", "https://api.waiaconnect.com/v1/webhooks/" . $list["webhooks"][0]["id"] . "/rotate-secret");
```

### Python

```python
import requests
H = {"Authorization": "Bearer wc_live_YOUR_API_KEY"}

# 1) onboarding link + the webhook of the number it will connect
link = requests.post("https://api.waiaconnect.com/v1/onboarding-links", headers=H, json={
    "externalId": "pharmacy-42",
    "webhook": {"url": "https://api.yourcompany.com/hooks/connect",
                "events": ["connection.created", "message.received", "message.status"]},
}).json()
save_secret("pharmacy-42", link["webhook"]["secret"])  # shown ONCE

# 2) later: the number's webhooks, by your externalId
hooks = requests.get("https://api.waiaconnect.com/v1/webhooks", headers=H, params={"externalId": "pharmacy-42"}).json()["webhooks"]

# rotate the secret (the old one stops verifying at once)
rotated = requests.post(f"https://api.waiaconnect.com/v1/webhooks/{hooks[0]['id']}/rotate-secret", headers=H).json()
```

## Note

- **Limite:** 2 webhook per numero (uno attivo e uno per migrare senza interruzioni), 2 × i tuoi numeri per tutti quelli di numero insieme, e 5 dell'account; contano anche quelli spenti. Superarlo creando o spostando uno su un numero → `422 WEBHOOK_LIMIT_REACHED` con `details.scope`, `used` e `limit`. Quelli che avevi già oltre il limite continuano a funzionare: puoi modificarli, provarli, cambiarne il segreto ed eliminarli.
- Filtri dell'elenco: `?connectionId=conn_…` (o il tuo `externalId`), `?connectionId=none` (solo quelli dell'account) o `?externalId=` (vuoto se quel numero non esiste ancora). Un `wh_…` o un numero di un altro account dà lo stesso 404 di uno che non esiste.
- Ricollegare lo stesso numero con un link che porta lo stesso URL non aggiunge un altro webhook: aggiorna quello, con il segreto del nuovo link. Se l'attivazione fallisce, non resta nessun webhook.
- Cambiare il segreto vale subito: da quel momento firmiamo con il nuovo e il vecchio smette di verificare. Aggiornalo subito nel tuo sistema.
