Vai al contenuto principale

Webhook

I webhook ti permettono di ricevere callback HTTP in tempo reale quando si verificano eventi sulle tue istanze WhatsApp. Invece di interrogare continuamente l’API, Wappfy invia gli eventi al tuo server nel momento in cui si verificano.

Eventi supportati

Wappfy supporta 12 tipi di eventi webhook:
EventoDescrizione
message.receivedUn nuovo messaggio in arrivo e stato ricevuto.
message.sentUn messaggio in uscita e stato inviato con successo.
message.deliveredUn messaggio inviato e stato consegnato al dispositivo del destinatario (doppia spunta).
message.readUn messaggio inviato e stato letto dal destinatario (spunte blu).
message.failedL’invio di un messaggio in uscita e fallito.
message.reactionQualcuno ha reagito a un messaggio con un emoji.
EventoDescrizione
instance.connectedUn’istanza si e connessa con successo a WhatsApp.
instance.disconnectedUn’istanza ha perso la connessione a WhatsApp.
instance.qrUn nuovo codice QR e disponibile per la scansione.
EventoDescrizione
group.joinedUn partecipante si e unito a un gruppo (incluso il bot stesso).
group.leftUn partecipante ha lasciato un gruppo.
contact.createdUn nuovo contatto e stato salvato o rilevato.

Creare un webhook

Registra un endpoint webhook per iniziare a ricevere eventi.
curl -X POST https://api.wappfy.io/api/webhooks \
  -H "X-Api-Key: YOUR_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "url": "https://your-server.com/webhooks/wappfy",
    "events": ["message.received", "message.sent", "message.delivered"],
    "instance_id": "inst_abc123",
    "secret": "whsec_my_signing_secret",
    "retry_count": 3,
    "timeout_ms": 10000
  }'
Risposta:
{
  "data": {
    "id": "wh_xyz789",
    "url": "https://your-server.com/webhooks/wappfy",
    "events": ["message.received", "message.sent", "message.delivered"],
    "instance_id": "inst_abc123",
    "is_active": true,
    "retry_count": 3,
    "timeout_ms": 10000,
    "created_at": "2026-02-10T12:00:00Z"
  }
}

Opzioni di configurazione

CampoTipoPredefinitoDescrizione
urlstringobbligatorioL’URL HTTPS che ricevera le richieste POST del webhook.
eventsstring[]obbligatorioArray dei tipi di evento a cui iscriversi.
instance_idstringnullLimita il webhook a un’istanza specifica. Se null, riceve eventi da tutte le istanze.
secretstringnullSegreto utilizzato per generare firme HMAC per la verifica del payload.
retry_countnumber3Numero di tentativi in caso di errore nella consegna (0-5).
timeout_msnumber10000Timeout della richiesta in millisecondi (1000-30000).
Il campo instance_id e opzionale. Se omesso, il webhook ricevera eventi da tutte le istanze del tuo account.

Elencare i webhook

curl https://api.wappfy.io/api/webhooks \
  -H "X-Api-Key: YOUR_API_KEY"
Risposta:
{
  "data": [
    {
      "id": "wh_xyz789",
      "url": "https://your-server.com/webhooks/wappfy",
      "events": ["message.received", "message.sent", "message.delivered"],
      "instance_id": "inst_abc123",
      "is_active": true,
      "retry_count": 3,
      "timeout_ms": 10000
    }
  ]
}

Aggiornare un webhook

Aggiorna l’URL, gli eventi o la configurazione di un webhook esistente.
curl -X PATCH https://api.wappfy.io/api/webhooks/wh_xyz789 \
  -H "X-Api-Key: YOUR_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "events": ["message.received", "message.sent", "message.delivered", "message.read"],
    "is_active": true
  }'

Eliminare un webhook

curl -X DELETE https://api.wappfy.io/api/webhooks/wh_xyz789 \
  -H "X-Api-Key: YOUR_API_KEY"

Formato del payload di consegna

Quando si verifica un evento, Wappfy invia una richiesta POST all’URL del tuo webhook con la seguente struttura:
{
  "id": "dlv_abc123def456",
  "event": "message.received",
  "instance_id": "inst_abc123",
  "timestamp": "2026-02-10T14:30:00Z",
  "data": {
    "message_id": "BAE5F2C4D3B2A1",
    "chat_id": "[email protected]",
    "from": "[email protected]",
    "type": "text",
    "text": "Hello!",
    "timestamp": "2026-02-10T14:30:00Z"
  }
}

Campi del payload

CampoDescrizione
idID univoco della consegna. Usalo per la deduplicazione.
eventIl tipo di evento che ha attivato questa consegna.
instance_idL’istanza che ha generato l’evento.
timestampTimestamp ISO 8601 del momento in cui si e verificato l’evento.
dataPayload specifico dell’evento. Il contenuto varia in base al tipo di evento.

Verifica della firma HMAC

Se fornisci un secret durante la creazione del webhook, ogni consegna includera un header X-Wappfy-Signature contenente una firma HMAC-SHA256 del corpo della richiesta. Verifica sempre questa firma per assicurarti che la richiesta provenga da Wappfy e non sia stata alterata.

Esempi di verifica

const crypto = require("crypto");

function verifyWebhookSignature(req, secret) {
  const signature = req.headers["x-wappfy-signature"];
  if (!signature) return false;

  const expectedSignature = crypto
    .createHmac("sha256", secret)
    .update(JSON.stringify(req.body))
    .digest("hex");

  return crypto.timingSafeEqual(
    Buffer.from(signature),
    Buffer.from(expectedSignature)
  );
}

// Express middleware
app.post("/webhooks/wappfy", (req, res) => {
  const isValid = verifyWebhookSignature(req, "whsec_my_signing_secret");

  if (!isValid) {
    return res.status(401).json({ error: "Invalid signature" });
  }

  const { event, data } = req.body;
  console.log(`Received event: ${event}`, data);

  // Always respond with 200 quickly to prevent retries
  res.status(200).json({ received: true });
});
Usa sempre un confronto a tempo costante (come timingSafeEqual o hmac.compare_digest) durante la verifica delle firme per prevenire attacchi di timing.

Comportamento dei tentativi

Se il tuo server non risponde con un codice di stato 2xx entro il timeout_ms configurato, Wappfy ritentera la consegna.
TentativoRitardo
1o tentativo10 secondi
2o tentativo60 secondi
3o tentativo5 minuti
4o tentativo30 minuti
5o tentativo2 ore
I tentativi si fermano quando viene ricevuta una risposta 2xx o quando il retry_count e esaurito. Il numero predefinito di tentativi e 3.

Visualizzare lo storico delle consegne

Controlla il log delle consegne di un webhook per vedere i tentativi passati e i relativi risultati.
curl https://api.wappfy.io/api/webhooks/wh_xyz789/deliveries \
  -H "X-Api-Key: YOUR_API_KEY"
Risposta:
{
  "data": [
    {
      "id": "dlv_abc123def456",
      "event": "message.received",
      "status": "delivered",
      "http_status": 200,
      "attempts": 1,
      "created_at": "2026-02-10T14:30:00Z",
      "delivered_at": "2026-02-10T14:30:01Z"
    },
    {
      "id": "dlv_ghi789jkl012",
      "event": "message.sent",
      "status": "failed",
      "http_status": 500,
      "attempts": 3,
      "created_at": "2026-02-10T14:31:00Z",
      "last_error": "Server returned 500 Internal Server Error"
    }
  ]
}

Esempi di payload degli eventi

{
  "id": "dlv_abc123",
  "event": "message.received",
  "instance_id": "inst_abc123",
  "timestamp": "2026-02-10T14:30:00Z",
  "data": {
    "message_id": "BAE5F2C4D3B2A1",
    "chat_id": "[email protected]",
    "from": "[email protected]",
    "type": "text",
    "text": "Hello, I need help with my order",
    "timestamp": "2026-02-10T14:30:00Z"
  }
}
{
  "id": "dlv_def456",
  "event": "message.delivered",
  "instance_id": "inst_abc123",
  "timestamp": "2026-02-10T14:30:05Z",
  "data": {
    "message_id": "BAE5A1B2C3D4E5",
    "chat_id": "[email protected]",
    "status": "delivered"
  }
}
{
  "id": "dlv_ghi789",
  "event": "message.read",
  "instance_id": "inst_abc123",
  "timestamp": "2026-02-10T14:31:00Z",
  "data": {
    "message_id": "BAE5A1B2C3D4E5",
    "chat_id": "[email protected]",
    "status": "read"
  }
}
{
  "id": "dlv_jkl012",
  "event": "message.reaction",
  "instance_id": "inst_abc123",
  "timestamp": "2026-02-10T14:32:00Z",
  "data": {
    "message_id": "BAE5F2C4D3B2A1",
    "chat_id": "[email protected]",
    "from": "[email protected]",
    "reaction": "\u2764\ufe0f"
  }
}
{
  "id": "dlv_mno345",
  "event": "instance.connected",
  "instance_id": "inst_abc123",
  "timestamp": "2026-02-10T12:00:00Z",
  "data": {
    "instance_id": "inst_abc123",
    "status": "connected",
    "phone_number": "5511999998888"
  }
}
{
  "id": "dlv_pqr678",
  "event": "instance.qr",
  "instance_id": "inst_abc123",
  "timestamp": "2026-02-10T11:59:00Z",
  "data": {
    "instance_id": "inst_abc123",
    "qr": "data:image/png;base64,iVBORw0KGgo..."
  }
}
{
  "id": "dlv_stu901",
  "event": "group.joined",
  "instance_id": "inst_abc123",
  "timestamp": "2026-02-10T15:00:00Z",
  "data": {
    "group_id": "[email protected]",
    "participant": "[email protected]"
  }
}

Buone pratiche

Rispondi rapidamente

Restituisci uno stato 200 entro 5 secondi. Elabora l’evento in modo asincrono per evitare timeout.

Deduplica

Usa l’id della consegna per rilevare e saltare le consegne duplicate causate dai tentativi.

Verifica le firme

Valida sempre l’header X-Wappfy-Signature se hai configurato un segreto.

Usa HTTPS

Gli URL dei webhook devono utilizzare HTTPS. Gli endpoint HTTP verranno rifiutati.