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

# API per sviluppatori Zapier

> Riferimento API completo per costruire integrazioni Zapier con Whappy. Configura i webhook, gestisci gli eventi e il flusso dei dati.

## URL di base

```
https://api.whappy.ai/v1
```

## Autenticazione

Tutte le richieste API richiedono autenticazione tramite API key. Includi la tua chiave negli header della richiesta:

```bash theme={null}
X-API-Key: your_api_key_here
```

### Ottenere la tua API key

1. Accedi al tuo account Whappy
2. Vai su **Integrazioni → Zapier**
3. Copia la tua API key dal pannello dell'integrazione

<Warning>
  Custodisci la tua API key e non condividerla mai pubblicamente. Trattala come una password.
</Warning>

***

## Endpoint

### Configurare gli URL dei webhook

Configura gli URL a cui Whappy invierà i dati quando si verificano determinati eventi nelle conversazioni.

#### Impostare l'URL webhook per gli appuntamenti

Configura dove inviare i dati quando un lead fissa un appuntamento.

```bash theme={null}
POST /zap/url/appointment
```

**Corpo della richiesta:**

```json theme={null}
{
  "targetUrl": "https://your-webhook-endpoint.com/appointment"
}
```

**Header:**

```bash theme={null}
Content-Type: application/json
X-API-Key: your_api_key_here
```

**Codici di risposta:**

* `200 OK`: URL configurato correttamente
* `304 Not Modified`: aggiornamento dell'URL non riuscito
* `400 Bad Request`: dati della richiesta non validi
* `401 Unauthorized`: API key mancante o non valida
* `500 Internal Server Error`: errore del server

**Esempio di richiesta:**

```bash theme={null}
curl -X POST https://api.whappy.ai/v1/zap/url/appointment \
  -H "Content-Type: application/json" \
  -H "X-API-Key: your_api_key_here" \
  -d '{"targetUrl": "https://hooks.zapier.com/hooks/catch/123456/abcdef/"}'
```

#### Impostare l'URL webhook per l'evento di chiusura

Configura dove inviare i dati quando un lead raggiunge un passaggio di "chiusura" nella conversazione.

```bash theme={null}
POST /zap/url/close
```

**Request Body:**

```json theme={null}
{
  "targetUrl": "https://your-webhook-endpoint.com/close"
}
```

**Example Request:**

```bash theme={null}
curl -X POST https://api.whappy.ai/v1/zap/url/close \
  -H "Content-Type: application/json" \
  -H "X-API-Key: your_api_key_here" \
  -d '{"targetUrl": "https://hooks.zapier.com/hooks/catch/123456/ghijkl/"}'
```

#### Rimuovere l'URL webhook degli appuntamenti

Rimuove l'URL webhook configurato per gli eventi di appuntamento.

```bash theme={null}
DELETE /zap/url/appointment
```

**Response Codes:**

* `200 OK`: URL rimosso correttamente
* `304 Not Modified`: rimozione dell'URL non riuscita
* `401 Unauthorized`: API key mancante o non valida
* `500 Internal Server Error`: errore del server

**Example Request:**

```bash theme={null}
curl -X DELETE https://api.whappy.ai/v1/zap/url/appointment \
  -H "X-API-Key: your_api_key_here"
```

#### Rimuovere l'URL webhook dell'evento di chiusura

Rimuove l'URL webhook configurato per gli eventi di chiusura.

```bash theme={null}
DELETE /zap/url/close
```

**Example Request:**

```bash theme={null}
curl -X DELETE https://api.whappy.ai/v1/zap/url/close \
  -H "X-API-Key: your_api_key_here"
```

### Provare l'integrazione

#### Prova di connessione

Verifica connessione e autenticazione. Usa questo endpoint per controllare che l'integrazione funzioni.

```bash theme={null}
POST /zap
```

**Response Codes:**

* `200 OK`: connessione riuscita
* `401 Unauthorized`: autenticazione fallita

**Example Request:**

```bash theme={null}
curl -X POST https://api.whappy.ai/v1/zap \
  -H "X-API-Key: your_api_key_here"
```

**Risposta positiva:**

```json theme={null}
{
  "status": "success",
  "message": "Connection verified"
}
```

### Ottenere dati di esempio

#### Recuperare dati di esempio

Ottieni un esempio della struttura dati che verrà inviata ai tuoi URL webhook. Indispensabile per configurare i flussi Zapier.

```bash theme={null}
GET /zap/sample/{event_name}
```

**Parametri:**

* `event_name`: `appointment` oppure `close`

**Example Request:**

```bash theme={null}
curl -X GET https://api.whappy.ai/v1/zap/sample/appointment \
  -H "X-API-Key: your_api_key_here"
```

**Esempio di risposta:**

```json theme={null}
[
  {
    "lead_id": "lead_12345",
    "created_at": "2025-05-22T10:30:00Z",
    "phone": "+1234567890",
    "name": "John Doe",
    "lead_info_json": "{\"source\": \"website\", \"campaign\": \"spring_2025\"}",
    "collected_info_json": "{\"interests\": [\"product_a\", \"product_b\"], \"budget\": \"$5000\"}",
    "appointment": {
      "full_date": "2025-05-25T14:00:00Z"
    },
    "conversation_json": "{\"messages\": [...], \"duration\": 300}",
    "appointment_json": "{\"type\": \"consultation\", \"location\": \"online\"}"
  }
]
```

***

## Modelli di dati

### DataPayload

La struttura dati principale inviata ai tuoi URL webhook quando si verifica un evento:

| Campo                 | Tipo                                      | Obbligatorio | Descrizione                                                        |
| --------------------- | ----------------------------------------- | ------------ | ------------------------------------------------------------------ |
| `lead_id`             | string                                    | Sì           | Identificatore univoco del lead                                    |
| `created_at`          | string                                    | Sì           | Data e ora ISO 8601 di creazione del lead                          |
| `phone`               | string                                    | Sì           | Numero di telefono del lead con prefisso internazionale            |
| `name`                | string                                    | Sì           | Nome completo del lead                                             |
| `lead_info_json`      | string                                    | No           | Stringa JSON con origine del lead e informazioni sulla campagna    |
| `collected_info_json` | string                                    | No           | Stringa JSON con le informazioni raccolte durante la conversazione |
| `appointment`         | [AppointmentPayload](#appointmentpayload) | No           | Dettagli dell'appuntamento (solo per gli eventi di appuntamento)   |
| `conversation_json`   | string                                    | No           | Stringa JSON con lo storico completo della conversazione           |
| `appointment_json`    | string                                    | No           | Stringa JSON con i dettagli dell'appuntamento                      |

### AppointmentPayload

Informazioni specifiche incluse negli eventi di appuntamento:

| Field       | Type   | Required | Description                                   |
| ----------- | ------ | -------- | --------------------------------------------- |
| `full_date` | string | Sì       | Data e ora ISO 8601 dell'appuntamento fissato |

### Campi JSON da interpretare

I campi stringa JSON contengono dati strutturati che puoi interpretare:

#### lead\_info\_json

```json theme={null}
{
  "source": "website",
  "campaign": "spring_2025",
  "utm_source": "google",
  "utm_medium": "cpc"
}
```

#### collected\_info\_json

```json theme={null}
{
  "budget": "$5000",
  "timeline": "Q2 2025",
  "interests": ["product_a", "product_b"],
  "company_size": "50-100",
  "decision_maker": true
}
```

#### conversation\_json

```json theme={null}
{
  "messages": [
    {
      "timestamp": "2025-05-22T10:30:00Z",
      "sender": "ai",
      "content": "Ciao! Come posso aiutarti oggi?"
    },
    {
      "timestamp": "2025-05-22T10:31:00Z",
      "sender": "lead",
      "content": "Mi interessano i vostri servizi di web design"
    }
  ],
  "duration": 300,
  "steps_completed": 5
}
```

#### appointment\_json

```json theme={null}
{
  "type": "consultation",
  "location": "online",
  "duration": "30 minutes",
  "calendar_event_id": "cal_12345",
  "meeting_link": "https://zoom.us/j/123456789"
}
```

***

## Esempi di payload webhook

### Evento Lead Closed

Quando un lead completa il funnel di conversazione:

```json theme={null}
{
  "lead_id": "lead_67890",
  "created_at": "2025-05-22T14:15:30Z",
  "phone": "+1987654321",
  "name": "Jane Smith",
  "lead_info_json": "{\"source\": \"facebook_ads\", \"campaign\": \"summer_promo\"}",
  "collected_info_json": "{\"budget\": \"$10000\", \"timeline\": \"Immediate\", \"service_type\": \"ecommerce\"}",
  "conversation_json": "{\"messages\": [...], \"duration\": 420, \"steps_completed\": 7}",
  "appointment_json": null
}
```

### Evento Appointment Scheduled

Quando un lead fissa un appuntamento:

```json theme={null}
{
  "lead_id": "lead_54321",
  "created_at": "2025-05-22T16:45:00Z",
  "phone": "+1555123456",
  "name": "Mike Johnson",
  "lead_info_json": "{\"source\": \"website\", \"campaign\": \"consultation_page\"}",
  "collected_info_json": "{\"budget\": \"$7500\", \"timeline\": \"Q3 2025\", \"current_solution\": \"none\"}",
  "appointment": {
    "full_date": "2025-05-24T10:00:00Z"
  },
  "conversation_json": "{\"messages\": [...], \"duration\": 380}",
  "appointment_json": "{\"type\": \"discovery_call\", \"location\": \"zoom\", \"duration\": \"45 minutes\"}"
}
```

***

## Flusso di integrazione

### 1. Configura gli endpoint webhook

Indica dove Whappy deve inviare i dati degli eventi:

```bash theme={null}
# Configura il webhook degli appuntamenti
curl -X POST https://api.whappy.ai/v1/zap/url/appointment \
  -H "Content-Type: application/json" \
  -H "X-API-Key: your_api_key" \
  -d '{"targetUrl": "https://hooks.zapier.com/hooks/catch/123456/appointment/"}'

# Configura il webhook dell'evento di chiusura
curl -X POST https://api.whappy.ai/v1/zap/url/close \
  -H "Content-Type: application/json" \
  -H "X-API-Key: your_api_key" \
  -d '{"targetUrl": "https://hooks.zapier.com/hooks/catch/123456/close/"}'
```

### 2. Prova l'integrazione

Verifica la connessione API:

```bash theme={null}
curl -X POST https://api.whappy.ai/v1/zap \
  -H "X-API-Key: your_api_key"
```

### 3. Ottieni dati di esempio

Capisci la struttura dati che riceverai:

```bash theme={null}
# Esempio di evento appuntamento
curl -X GET https://api.whappy.ai/v1/zap/sample/appointment \
  -H "X-API-Key: your_api_key"

# Esempio di evento di chiusura
curl -X GET https://api.whappy.ai/v1/zap/sample/close \
  -H "X-API-Key: your_api_key"
```

### 4. Gestisci i dati del webhook

Nel gestore webhook riceverai la struttura DataPayload. Interpreta i campi JSON secondo necessità:

```javascript theme={null}
// Esempio di gestore webhook (Node.js)
app.post('/webhook/whappy-appointment', (req, res) => {
  const payload = req.body;

  // Interpreta i campi JSON
  const leadInfo = JSON.parse(payload.lead_info_json || '{}');
  const collectedInfo = JSON.parse(payload.collected_info_json || '{}');
  const appointmentInfo = JSON.parse(payload.appointment_json || '{}');

  // Elabora i dati
  console.log('New appointment scheduled:', {
    leadName: payload.name,
    phone: payload.phone,
    appointmentDate: payload.appointment.full_date,
    budget: collectedInfo.budget,
    source: leadInfo.source
  });

  res.status(200).send('OK');
});
```

***

## Casi d'uso comuni

### Integrazione CRM

Crea o aggiorna automaticamente i contatti nel tuo CRM:

```javascript theme={null}
// Esempio: invio a HubSpot
const hubspotContact = {
  properties: {
    firstname: payload.name.split(' ')[0],
    lastname: payload.name.split(' ')[1],
    phone: payload.phone,
    lead_source: JSON.parse(payload.lead_info_json).source,
    budget: JSON.parse(payload.collected_info_json).budget
  }
};
```

### Integrazione con il calendario

Aggiungi gli appuntamenti ai sistemi di pianificazione:

```javascript theme={null}
// Esempio: creazione di un evento su Google Calendar
const calendarEvent = {
  summary: `Consultation with ${payload.name}`,
  start: {
    dateTime: payload.appointment.full_date,
    timeZone: 'America/New_York'
  },
  description: `Phone: ${payload.phone}\nBudget: ${JSON.parse(payload.collected_info_json).budget}`
};
```

### Email marketing

Aggiungi i lead alle sequenze email:

```javascript theme={null}
// Esempio: aggiunta a una lista Mailchimp
const subscriber = {
  email_address: JSON.parse(payload.collected_info_json).email,
  status: 'subscribed',
  merge_fields: {
    FNAME: payload.name.split(' ')[0],
    PHONE: payload.phone,
    BUDGET: JSON.parse(payload.collected_info_json).budget
  }
};
```

***

## Gestione degli errori

### Codici di stato HTTP standard

| Codice | Descrizione           | Cosa fare                                               |
| ------ | --------------------- | ------------------------------------------------------- |
| `200`  | Successo              | Richiesta completata correttamente                      |
| `304`  | Not Modified          | La risorsa non è stata modificata (negli aggiornamenti) |
| `400`  | Bad Request           | Controlla parametri e formato del corpo della richiesta |
| `401`  | Unauthorized          | Verifica che la tua API key sia corretta                |
| `500`  | Internal Server Error | Contatta l'assistenza se persiste                       |

### Formato della risposta di errore

```json theme={null}
{
  "detail": "Description of the error"
}
```

### Errori frequenti

<AccordionGroup>
  <Accordion title="API key non valida">
    **Risposta di errore:**

    ```json theme={null}
    {
        "detail": "Invalid authentication credentials"
    }
    ```

    **Soluzione:** verifica di aver copiato correttamente la API key dalla dashboard di Whappy.
  </Accordion>

  <Accordion title="URL webhook non valido">
    **Error Response:**

    ```json theme={null}
    {
        "detail": "Invalid URL format"
    }
    ```

    **Soluzione:** assicurati che l'URL sia formattato correttamente e raggiungibile.
  </Accordion>

  <Accordion title="URL webhook irraggiungibile">
    **Error Response:**

    ```json theme={null}
    {
        "detail": "Unable to reach webhook URL"
    }
    ```

    **Soluzione:** verifica che l'endpoint sia online e accetti richieste POST.
  </Accordion>
</AccordionGroup>

***

## Limiti di frequenza

* **Limite generale**: 100 richieste al minuto per API key
* **Configurazione webhook**: 10 richieste al minuto
* **Dati di esempio**: 50 richieste al minuto

<Note>
  Se ti servono limiti più alti per l'uso in produzione, contatta l'assistenza descrivendo il tuo caso d'uso.
</Note>

***

## Buone pratiche di sicurezza

### Gestione delle API key

* Conserva le chiavi in modo sicuro usando variabili d'ambiente
* Non inserire mai una chiave nel controllo di versione
* Ruota le chiavi periodicamente
* Usa chiavi diverse per sviluppo e produzione

### Sicurezza dei webhook

* Valida i payload prima di elaborarli
* Usa endpoint HTTPS
* Implementa una gestione degli errori e un logging adeguati
* Monitora i fallimenti dei webhook

### Trattamento dei dati

* Interpreta i campi JSON in sicurezza con blocchi try-catch
* Valida i tipi di dato prima di elaborarli
* Ripulisci i dati prima di archiviarli o inoltrarli
* Rispetta le normative sulla privacy (GDPR)

***

## Provare l'integrazione

### 1. Prova la connessione API

```bash theme={null}
curl -X POST https://api.whappy.ai/v1/zap \
  -H "X-API-Key: your_test_api_key" \
  -v
```

### 2. Configura webhook di prova

```bash theme={null}
# Usa strumenti come ngrok per i test in locale
ngrok http 3000

# Configura il webhook con l'URL ngrok
curl -X POST https://api.whappy.ai/v1/zap/url/close \
  -H "Content-Type: application/json" \
  -H "X-API-Key: your_test_api_key" \
  -d '{"targetUrl": "https://abc123.ngrok.io/webhook/close"}'
```

### 3. Verifica i dati di esempio

```bash theme={null}
# Recupera e verifica la struttura dei dati di esempio
curl -X GET https://api.whappy.ai/v1/zap/sample/close \
  -H "X-API-Key: your_test_api_key" | jq .
```

### 4. Monitora le chiamate webhook

Attiva il logging nel gestore webhook per monitorare i dati in arrivo:

```javascript theme={null}
app.post('/webhook/test', (req, res) => {
  console.log('Webhook received:', JSON.stringify(req.body, null, 2));
  res.status(200).send('OK');
});
```

***

## Assistenza

Per supporto tecnico o domande sull'API:

* **Documentazione**: parti dalla [home della documentazione](/it/introduction)
* **Assistenza dalla dashboard**: contatta il supporto dalla tua dashboard Whappy
* **Email**: [team@whappy.ai](mailto:team@whappy.ai)

### Quando contatti l'assistenza

Includi queste informazioni:

* La tua API key (solo i primi 8 caratteri)
* Esempi di richiesta e risposta
* Messaggi di errore e codici di stato HTTP
* Data e ora del problema
* Comportamento atteso e comportamento effettivo

***

## Cronologia delle versioni

### Versione 1.0

* Prima release
* Supporto per i webhook di appuntamento e chiusura
* Endpoint per i dati di esempio
* Autenticazione di base tramite API key
* Configurazione e gestione degli URL webhook

***

## SDK e librerie

### Librerie ufficiali

Stiamo lavorando a SDK ufficiali per i linguaggi più diffusi. Nel frattempo, ecco alcuni esempi:

<Tabs>
  <Tab title="Node.js">
    ```javascript theme={null}
    const axios = require('axios');

    class WhappyAPI {
    constructor(apiKey) {
    this.apiKey = apiKey;
    this.baseURL = 'https://api.whappy.ai/v1';
    }

    async setAppointmentWebhook(targetUrl) {
    return axios.post(`${this.baseURL}/zap/url/appointment`,
    { targetUrl },
    { headers: { 'X-API-Key': this.apiKey } }
    );
    }

    async testConnection() {
    return axios.post(`${this.baseURL}/zap`, {},
    { headers: { 'X-API-Key': this.apiKey } }
    );
    }
    }
    ```
  </Tab>

  <Tab title="Python">
    ```python theme={null}
    import requests

    class WhappyAPI:
    def __init__(self, api_key):
    self.api_key = api_key
    self.base_url = 'https://api.whappy.ai/v1'
    self.headers = {'X-API-Key': api_key}

    def set_appointment_webhook(self, target_url):
    return requests.post(
    f'{self.base_url}/zap/url/appointment',
    json={'targetUrl': target_url},
    headers=self.headers
    )

    def test_connection(self):
    return requests.post(
    f'{self.base_url}/zap',
    headers=self.headers
    )
    ```
  </Tab>

  <Tab title="PHP">
    ```php theme={null}
    <?php
    class WhappyAPI {
        private $apiKey;
        private $baseURL = 'https://api.whappy.ai/v1';

        public function __construct($apiKey) {
            $this->apiKey = $apiKey;
        }

        public function setAppointmentWebhook($targetUrl) {
            $curl = curl_init();
            curl_setopt_array($curl, [
                CURLOPT_URL => $this->baseURL . '/zap/url/appointment',
                CURLOPT_RETURNTRANSFER => true,
                CURLOPT_POST => true,
                CURLOPT_POSTFIELDS => json_encode(['targetUrl' => $targetUrl]),
                CURLOPT_HTTPHEADER => [
                    'Content-Type: application/json',
                    'X-API-Key: ' . $this->apiKey
                ],
            ]);
            return curl_exec($curl);
        }
    }
    ?>
    ```
  </Tab>
</Tabs>

Tutto pronto per costruire la tua integrazione Zapier? Comincia provando la connessione API ed esplorando gli endpoint dei dati di esempio.
