# WhatsApp calls

> Receive and place voice calls with the Calling API: Messajo handles the signaling, the audio flows straight between your WebRTC client and Meta.

Messajo handles **only the signaling** of [Calling API](https://developers.facebook.com/docs/whatsapp/cloud-api/calling) calls: the SDP offer arrives by webhook, you answer through the API, and the audio (WebRTC or SIP) flows directly between your system and Meta. Messajo never carries media.

## Before you start

- A WhatsApp connection in **API-only** mode. Coexistence has no calling: any call action in that mode returns `422` [`calling_not_supported_in_coex`](/en/errors#calling_not_supported_in_coex).
- Calling turned on in the number's settings (below). Off → `409` [`calling_not_enabled`](/en/errors#calling_not_enabled).
- The `calls` field subscribed in your Meta app's webhook.
- A key with `send` (answer, reject, hang up, call), `read` (log and permissions) and `admin` (settings).

## Call states

| Direction | Path |
|---|---|
| Incoming (`user_initiated`) | `offered` → `pre_accepted` (optional) → `accepted` → `terminating` → `ended`; or `offered`/`pre_accepted` → `rejected` |
| Outgoing (`business_initiated`) | `dialing` → `ringing` → `accepted` → `terminating` → `ended`; or `dialing`/`ringing` → `rejected` |

`end_reason` says how it ended: `completed`, `missed` (never answered), `failed`, `rejected`, `canceled` or `unknown` (no news from Meta for more than 10 minutes). An action that is not valid in the current state returns `409` [`call_invalid_state`](/en/errors#call_invalid_state), with the current state in `details`.

## Receiving a call, end to end

1. The contact calls. A `call.incoming` event arrives with `data.call.id` (`cal_…`), `sdp_type: "offer"` and the offer `sdp`.
2. Your WebRTC client builds the SDP answer from the offer.
3. Optional: `POST /v1/calls/{id}/pre-accept` with the `sdp`, so Meta sets up media while the answer screen shows.
4. `POST /v1/calls/{id}/accept` with the **same** `sdp`. After a `pre-accept`, a different SDP returns `409` [`call_sdp_mismatch`](/en/errors#call_sdp_mismatch) without calling Meta.
5. To hang up: `POST /v1/calls/{id}/terminate`. Once Meta confirms, `call.ended` arrives with `duration_s`.

A minimal JavaScript client (browser) that gets `call.incoming` from your backend (for example over the [WebSocket](/en/webhooks/destinations/)) and answers:

```js title="answer.js"
const API = "https://api.messajo.com/v1";

// Call through your backend: the API key never reaches the browser.
async function callApi(path, body) {
  const res = await fetch(`/my-backend/messajo${path}`, {
    method: "POST",
    headers: { "Content-Type": "application/json" },
    body: JSON.stringify(body),
  });
  if (!res.ok) throw new Error(`Messajo ${res.status}`);
  return res.json();
}

export async function onIncomingCall(event) {
  const { id, sdp } = event.data.call; // call.incoming
  const pc = new RTCPeerConnection();
  const mic = await navigator.mediaDevices.getUserMedia({ audio: true });
  for (const track of mic.getTracks()) pc.addTrack(track, mic);
  pc.ontrack = ({ streams }) => {
    const audio = new Audio();
    audio.srcObject = streams[0];
    audio.play();
  };

  await pc.setRemoteDescription({ type: "offer", sdp });
  await pc.setLocalDescription(await pc.createAnswer());
  // wait for the ICE candidates to land in the local SDP
  await new Promise((resolve) => {
    if (pc.iceGatheringState === "complete") return resolve();
    pc.onicegatheringstatechange = () =>
      pc.iceGatheringState === "complete" && resolve();
  });

  const answer = pc.localDescription.sdp;
  await callApi(`/calls/${id}/pre-accept`, { sdp: answer });
  await callApi(`/calls/${id}/accept`, { sdp: answer });
  return { pc, hangUp: () => callApi(`/calls/${id}/terminate`, {}) };
}
```

The backend just forwards the body to `${API}/calls/{id}/…` with `Authorization: Bearer $MESSAJO_API_KEY`. The SDP is text up to 64 KiB, starts with `v=0` and may use LF or CRLF line breaks; anything else returns `400` [`call_sdp_invalid`](/en/errors#call_sdp_invalid).

## Calling the contact

Meta only lets the business call people who granted **call permission**. Check first:

```bash
curl "https://api.messajo.com/v1/connections/conn_.../call-permissions?to=5511999990001" \
  -H "Authorization: Bearer $MESSAJO_API_KEY"
```

The response has `status` (`no_permission`, `temporary`, `permanent` or `rejected`), `expires_at` and the `actions` Meta allows right now, with their limits. Without permission, ask for it with an `interactive` message of type `call_permission_request` (only `body.text`, inside the 24-hour window) or with a template that has the permission request component. The contact's answer arrives as `call.permission_updated`. Meta limits requests to 1 per 24 h and 2 per 7 days for the same contact.

With permission, call with the SDP offer from your WebRTC client:

```bash
curl https://api.messajo.com/v1/calls \
  -H "Authorization: Bearer $MESSAJO_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{ "connection_id": "conn_...", "to": "5511999990001", "sdp": "v=0\r\n..." }'
```

It returns `201` with the call in `dialing`. The contact's SDP answer arrives in `call.sdp_answer`; the next steps in `call.status`. No permission → `403` [`call_permission_required`](/en/errors#call_permission_required).

## Events

| Type | When |
|---|---|
| `call.incoming` | the contact called (with the offer `sdp`) |
| `call.sdp_answer` | the contact picked up your call (with the answer `sdp`) |
| `call.status` | `RINGING`, `ACCEPTED`, `REJECTED` |
| `call.ended` | the end, with `end_reason`, `start_time`, `end_time` and `duration_s` |
| `call.permission_updated` | the contact's call permission changed (`status`, `is_permanent`, `expires_at`) |

The SDP holds the contact's IP addresses. It goes in the events, but reading through the API (`GET /v1/calls`, `GET /v1/calls/{id}`) only shows `has_sdp`, and Messajo deletes the SDP 1 hour after the call ends. The panel shows the log under **Calls**.

## Number settings

`GET /v1/connections/{id}/calling-settings` reads and `PUT` (`admin` key) changes, in parts: turning calling on or off (`status`), showing the call icon (`call_icon_visibility`), offering callbacks (`callback_permission_status`), business hours (`call_hours`, with time zone, weekdays and holidays) and SIP. In the panel: connection → **Calls**.

## SIP

To send the audio to a PBX instead of a WebRTC client, set `sip.servers` (public hostname and port). Messajo only stores the settings and passes them to Meta. The SIP password Meta generates comes **once**, only in a `GET …/calling-settings?include_sip_credentials=true` made with an `admin` key: Messajo neither stores nor logs it.

## Limits and errors

| Code | When |
|---|---|
| [`call_permission_required`](/en/errors#call_permission_required) | Meta `138006`: the contact did not grant permission |
| [`call_rate_limited`](/en/errors#call_rate_limited) | Meta's call or permission request limit |
| [`call_error`](/en/errors#call_error) | another Meta `138xxx` error, with the detail in `details[0].message` |
| [`meta_unknown_outcome`](/en/errors#meta_unknown_outcome) | Meta failed in the middle of the action; the webhook fixes the state later |
