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

# Receive calls

> Verify Calling webhooks and accept an inbound WhatsApp voice call

## Call lifecycle

Complete [Calling setup](https://docs.kapso.ai/docs/whatsapp/calling/overview.md) first.

1. Receive a `calls` change with `event: "connect"`, `direction: "USER_INITIATED"`, and an SDP offer.
2. Create one media session for the call ID, apply the offer, and generate an SDP answer.
3. Start the audio pipeline without speaking, and send `pre_accept` with the answer.
4. Once media is ready, send `accept`. Greet only after `accept` succeeds and media is connected; `pre_accept` doesn't answer the call.
5. On `event: "terminate"`, stop the pipeline and close the media connection.

One delivery can batch several entries, changes, calls, and statuses. Iterate over all of them and route by `value.metadata.phone_number_id`. Statuses such as `RINGING`, `ACCEPTED`, and `REJECTED` arrive in `value.statuses[]` on the same `calls` field, with the call ID in `id`. [Outbound calls](https://docs.kapso.ai/docs/whatsapp/calling/outbound-calls.md) rely on them.

```json theme={null}
{
  "object": "whatsapp_business_account",
  "entry": [{
    "changes": [{
      "field": "calls",
      "value": {
        "metadata": {"phone_number_id": "PHONE_NUMBER_ID"},
        "calls": [{
          "id": "wacid.EXAMPLE",
          "event": "connect",
          "direction": "USER_INITIATED",
          "from_user_id": "US.13491208655302741918",
          "session": {"sdp_type": "offer", "sdp": "GENERATED_SDP_OFFER"}
        }]
      }
    }]
  }]
}
```

Store `from_user_id` when present, and don't assume `from` is a phone number; see [business-scoped user IDs](https://docs.kapso.ai/docs/whatsapp/business-scoped-user-ids.md).

## Verify the webhook

Kapso signs forwarded Meta webhooks with a **hex HMAC-SHA256** of the raw request body in `X-Webhook-Signature`, keyed with your webhook's `secret_key`. Verify it before parsing JSON. This isn't Meta's `X-Hub-Signature-256` scheme and doesn't use your Meta app secret.

This Express handler verifies the signature and queues every event. `enqueueCallEvent` and `enqueueOtherMetaChange` are yours to implement with your queue or router; they must persist the event before the handler returns `200`. Don't start the conversation inside the request.

```javascript theme={null}
import express from 'express';
import { createHmac, timingSafeEqual } from 'node:crypto';

const app = express();

app.post('/webhooks/whatsapp', express.raw({ type: 'application/json', limit: '1mb' }), async (req, res, next) => {
  try {
    if (!Buffer.isBuffer(req.body)) return res.sendStatus(415);
    const signature = req.get('X-Webhook-Signature') ?? '';
    if (!/^[a-f0-9]{64}$/i.test(signature)) return res.sendStatus(401);

    const expected = createHmac('sha256', process.env.WHATSAPP_WEBHOOK_SECRET)
      .update(req.body).digest();
    if (!timingSafeEqual(expected, Buffer.from(signature, 'hex'))) {
      return res.sendStatus(401);
    }

    const payload = JSON.parse(req.body.toString('utf8'));
    const deliveryKey = req.get('X-Idempotency-Key');
    for (const [entryIndex, entry] of (payload.entry ?? []).entries()) {
      for (const [changeIndex, change] of (entry.changes ?? []).entries()) {
        const value = change.value;
        if (value?.metadata?.phone_number_id !== process.env.WHATSAPP_PHONE_NUMBER_ID) continue;
        const changeKey = deliveryKey ? `${deliveryKey}:${entryIndex}:${changeIndex}` : undefined;
        if (change.field !== 'calls') {
          // Preserve messaging and permission-reply handling on a shared receiver.
          await enqueueOtherMetaChange({ key: changeKey, change });
          continue;
        }
        for (const kind of ['calls', 'statuses']) {
          for (const [eventIndex, event] of (value[kind] ?? []).entries()) {
            await enqueueCallEvent({
              key: changeKey ? `${changeKey}:${kind}:${eventIndex}` : undefined, kind, event, value
            });
          }
        }
      }
    }
    res.sendStatus(200);
  } catch (error) {
    next(error);
  }
});
```

Register this route before any global JSON parser so the raw body stays intact. Return `200` within the 10-second webhook timeout, and run session startup and the conversation in a worker. If you already process normal messages from a Kapso-format webhook, skip them here to avoid processing them twice, but keep handling `interactive.call_permission_reply`.

## Pre-accept and accept

Both actions use your API key. `answer.sdp` must come from the WebRTC session that applied this call's offer.

```javascript theme={null}
async function callAction(callId, action, answerSdp) {
  const body = { messaging_product: 'whatsapp', call_id: callId, action };
  if (answerSdp !== undefined) {
    body.session = { sdp_type: 'answer', sdp: answerSdp };
  }

  const response = await fetch(
    `https://api.kapso.ai/meta/whatsapp/${process.env.META_GRAPH_VERSION}/${process.env.WHATSAPP_PHONE_NUMBER_ID}/calls`,
    {
      method: 'POST',
      headers: { 'X-API-Key': process.env.KAPSO_API_KEY, 'Content-Type': 'application/json' },
      body: JSON.stringify(body)
    }
  );
  const text = await response.text();
  if (!response.ok) throw new Error(`Call action failed: HTTP ${response.status}: ${text.slice(0, 300)}`);
  const result = JSON.parse(text);
  if (result.success !== true) throw new Error('Call action was not confirmed');
  return result;
}

// In your call worker, after preparing the media session:
await callAction(call.id, 'pre_accept', answer.sdp);
await callAction(call.id, 'accept', answer.sdp);
```

To record or transcribe the call, add `recording` and/or `transcription` to the `accept` body, never to `pre_accept`. See [Recordings and transcripts](https://docs.kapso.ai/docs/whatsapp/calling/recordings-and-transcripts.md).

A `409` means Kapso gave the call to another answerer, based on the number's [Incoming call answering](https://docs.kapso.ai/docs/whatsapp/calling/overview.md#choose-who-answers) setting. Stop the media session and don't send `reject`; Kapso refuses it the same way.

```json theme={null}
{ "error": "Answered elsewhere", "code": "answered_elsewhere" }
```

For SDK equivalents, see [Calls](https://docs.kapso.ai/docs/whatsapp/typescript-sdk/calls.md). To generate `answer.sdp` from a voice runtime, see [Connect a voice agent](https://docs.kapso.ai/docs/whatsapp/calling/voice-agents.md).

## End or reject a call

```javascript theme={null}
// To decline an unanswered call:
await callAction(call.id, 'reject');

// In a separate path, to end a call from your application:
await callAction(call.id, 'terminate');
```

* **Caller hangs up:** you receive `terminate`. Stop the pipeline and close the media connection. Don't start a new session or try to accept the call.
* **Your agent hangs up:** let the farewell audio finish, send `terminate`, then close the media connection. Stopping the AI pipeline alone doesn't end the WhatsApp call.

## Handle duplicates and late events

Webhooks can be delivered more than once, so guard at two levels:

* **Per delivery.** `X-Idempotency-Key` identifies the whole webhook body. Combine it with each event's position in the payload, as the receiver above does; using the header alone would drop other calls in the same delivery. If the header is missing, skip this check rather than generating keys that collide.
* **Per call.** Create at most one session per Meta call ID (`call.id` or `status.id`), and keep a terminal state so a late or repeated `connect` can't restart an ended call.

With multiple workers, keep call state in shared storage and route each call's events to the worker that owns its media session.

`call_recording_available` and transcript events (`call_transcript_available` or `call_transcription_available`) arrive after `terminate`. Treat them as metadata: they must never start a session or reopen an ended call.


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.