# Crea webhook (POST)

Crea un nuovo webhook per ricevere notifiche push dai servizi esterni.

## Endpoint

```
POST https://api.pocketalert.app/v1/webhooks
```

## Autenticazione

> **Info: Obbligatorio**
>
> Includi una di queste intestazioni nella tua richiesta:
> - `Token: <your-api-key>` — Ottienila da [Chiavi API](https://pocketalert.app/account/apikeys)
> - `Authorization: Bearer <jwt-token>` — Da [Accedi](https://info.pocketalert.app/api/user/login.md)

## Richiesta

### Intestazioni

| Intestazione | Obbligatoria | Descrizione |
|--------------|:------------:|-------------|
| `Token` | ✅ | La tua chiave API |
| `Authorization` | ✅ | `Bearer <jwt-token>` |

### Parametri del corpo

| Parametro | Tipo | Obbligatorio | Descrizione |
|-----------|------|:------------:|-------------|
| `name` | string | ✅ | Nome del webhook (ad esempio "Sentry", "GitHub") |
| `url` | string | ❌ | Slug dell'URL di ricezione `https://p4a.me/wh/{url}`. Se omesso, viene generato uno slug casuale di 20 caratteri. Deve essere univoco: uno slug già in uso restituisce `409` |
| `message` | string | ✅ | Template del messaggio (usa `*` per il JSON grezzo) |
| `application_id` | string | ❌ | TID dell'applicazione per categorizzare i messaggi |
| `device_id` | string | ❌ | TID del dispositivo di destinazione (ometti per tutti i dispositivi) |
| `default_level` | string \| int | ❌ | Livello di priorità predefinito applicato ai messaggi di questo webhook quando il payload non ne specifica uno: un nome (`silent`, `low`, `default`, `high`, `critical`) o un intero (`-2`..`2`). Vedi [Livelli di priorità dei messaggi](https://info.pocketalert.app/api/messages/create.md#priority-levels). |
| `actions` | string | ❌ | Template JSON dei pulsanti di azione. Stessa struttura delle [azioni dei messaggi](https://info.pocketalert.app/api/messages/create.md#action-buttons), ma `label`/`value` possono contenere segnaposto `%field.path%` risolti con il payload in arrivo. Salvato come stringa JSON. Funzionalità a pagamento: rimossa nei piani gratuiti. |

### Template dei pulsanti di azione

`actions` permette alle notifiche generate dai webhook di includere fino a 3 pulsanti, con segnaposto `%field.path%` sostituiti dal payload in arrivo (stessa sintassi del template del messaggio):

```json
[
  { "type": "view", "label": "Open issue", "value": "%issue.html_url%" },
  { "type": "http", "label": "Ack", "value": "{\"url\":\"https://ops.example.com/ack/%issue.id%\",\"method\":\"POST\"}" }
]
```

Il template viene verificato al salvataggio: deve essere un array JSON di al massimo 3 pulsanti con un `type` valido, e un pulsante senza segnaposto deve essere completamente valido, altrimenti la richiesta restituisce `400`.

Dopo la sostituzione, ogni pulsante viene validato come le [azioni dei messaggi](https://info.pocketalert.app/api/messages/create.md#action-buttons). Un pulsante che risulta non valido per questo payload, come un pulsante `view` il cui campo URL manca, viene scartato da solo; gli altri pulsanti e il messaggio vengono comunque consegnati.

I pulsanti di azione sono una funzionalità a pagamento. Nei piani gratuiti vengono rimossi lato server e il messaggio viene consegnato senza di essi.

### Sintassi del template del messaggio

Usa `%field.path%` per estrarre valori dal JSON in arrivo:

| Template | Descrizione |
|----------|-------------|
| `*` | Restituisce l'intero payload JSON |
| `%field%` | Estrae un campo di primo livello |
| `%object.field%` | Estrae un campo annidato |
| `%array.0.field%` | Estrae da un array tramite indice |
| `%%` | Un `%` letterale. Serve solo subito prima di una parola seguita da un altro `%`, come in `%cpu%%%`; un `%` seguito da uno spazio, come in `90% on %host%`, resta invariato |

Vedi [Impostazioni del webhook](https://info.pocketalert.app/api/webhooks/settings.md) per esempi dettagliati.

### Esempio di richiesta

**cURL**

```bash
curl -X POST "https://api.pocketalert.app/v1/webhooks" \
  -H "Token: your-api-key" \
  -H "Content-Type: application/json" \
  -d '{
    "name": "GitHub Push",
    "message": "Push to %repository.name%: %head_commit.message%",
    "application_id": "s9h1ekk5xb46jikthl"
  }'
```

**JavaScript**

```javascript
const response = await fetch('https://api.pocketalert.app/v1/webhooks', {
  method: 'POST',
  headers: {
    'Token': 'your-api-key',
    'Content-Type': 'application/json'
  },
  body: JSON.stringify({
    name: 'GitHub Push',
    message: 'Push to %repository.name%: %head_commit.message%',
    application_id: 's9h1ekk5xb46jikthl'
  })
});

const webhook = await response.json();
console.log('Webhook URL:', `https://p4a.me/wh/${webhook.url}`);
```

**Python**

```python
import requests

response = requests.post(
    'https://api.pocketalert.app/v1/webhooks',
    headers={'Token': 'your-api-key'},
    json={
        'name': 'GitHub Push',
        'message': 'Push to %repository.name%: %head_commit.message%',
        'application_id': 's9h1ekk5xb46jikthl'
    }
)

webhook = response.json()
print(f"Webhook URL: https://p4a.me/wh/{webhook['url']}")
```

**PHP**

```php
$response = Http::withHeaders([
    'Token' => 'your-api-key',
])->post('https://api.pocketalert.app/v1/webhooks', [
    'name' => 'GitHub Push',
    'message' => 'Push to %repository.name%: %head_commit.message%',
    'application_id' => 's9h1ekk5xb46jikthl',
]);

$webhook = $response->json();
echo 'Webhook URL: https://p4a.me/wh/'.$webhook['url'];
```

## Risposta

### Risposta di successo

> **Tip: 201 Created**
>
> Webhook creato con successo

| Campo | Tipo | Descrizione |
|-------|------|-------------|
| `tid` | string | Identificatore univoco del webhook |
| `name` | string | Nome del webhook |
| `url` | string | Slug dell'URL del webhook — usalo nei servizi esterni |
| `message` | string | Template del messaggio |
| `actions` | string | Template JSON dei pulsanti di azione (vuoto se non impostato) |
| `is_active` | boolean | Indica se il webhook è attivo |

```json
{
  "tid": "kblf7mh9j8jjyeh4fx",
  "name": "GitHub Push",
  "url": "cs994rqfkk8ljngt",
  "message": "Push to %repository.name%: %head_commit.message%",
  "actions": "",
  "application_tid": "qm47b9pzxzx7applfd0",
  "device_tid": "",
  "is_active": true,
  "created_at": "01.09.2023 22:38:48"
}
```

> **Tip: Usare il tuo webhook**
>
> Configura il servizio esterno per inviare una POST a:
> ```
> https://p4a.me/wh/{url}
> ```

### Risposte di errore

| Stato | Descrizione |
|:-----:|-------------|
| `400` | Richiesta non valida — `name` o `message` mancanti, un `default_level` non valido o un template `actions` non valido |
| `401` | Non autorizzato — token non valido o mancante |
| `403` | Vietato — raggiunto il limite di webhook del tuo piano |
| `404` | Non trovato — `application_id` o `device_id` non esiste |
| `409` | Conflitto — lo slug `url` è già in uso |
