# Control calls from your server

> Place, answer and end WhatsApp calls from your server, speak and listen on a call, and change a Number's call settings.

Your server controls calls in two ways. HTTP requests, or `messaging.voip` in
`@polymorfa/sdk`, place, answer, decline and end calls without carrying
media. `CallsClient` from `@polymorfa/sdk/calls` joins a call over the media
socket so your code can speak and listen, for example to run a voice agent.

Server requests use a team key or project token with `sessions:manage`, and
act as `server:<participant>`. See
[How calls work](https://docs.polymorfa.com/calls/how-calls-work) for participants, claims and limits.

## Check before you call

`POST /messaging/voip/calls/check` runs the checks a placement runs, without
calling: the Number's calling switch, your team's do-not-call list and blocked
country codes, and on a Cloud API Number the person's call permission and
WhatsApp's call limits.

```bash cURL
curl -X POST "https://api.polymorfa.com/messaging/voip/calls/check" \
  -H "Authorization: Bearer $POLYMORFA_KEY" \
  -H "Content-Type: application/json" \
  -d '{ "session": "support", "to": "+15550100" }'
```

```typescript TypeScript
const check = await messaging.voip.check({ session: "support", to: "+15550100" });

if (!check.data.data.allowed) {
  console.log("Call would fail:", check.data.data.refusal);
}
```

`refusal` is `calls_disabled`, `call_recipient_opted_out`,
`call_destination_blocked`, `call_permission_required` or
`call_limit_reached`, or `null`. Placing the call runs the checks again, so a
call can still fail if something changed in between. If WhatsApp's permission
state cannot be read and nothing else refuses the call, the check returns
`503 service_unavailable`. See [Call permissions and opt-outs](https://docs.polymorfa.com/calls/permissions).

## Place a call

```bash cURL
curl -X POST "https://api.polymorfa.com/messaging/voip/calls" \
  -H "Authorization: Bearer $POLYMORFA_KEY" \
  -H "Idempotency-Key: call-order-1042" \
  -H "Content-Type: application/json" \
  -d '{ "session": "support", "to": "+15550100", "video": false, "exclusive": true, "participant": "agent-7" }'
```

```typescript TypeScript
const placed = await messaging.voip.place(
  {
    session: "support",
    to: "+15550100",
    video: false,
    exclusive: true,
    participant: "agent-7",
  },
  { idempotencyKey: "call-order-1042" },
);

console.log(placed.data.data.callId);
```

See [Place an outbound call](https://docs.polymorfa.com/api/calls/place-outbound-call).

*TypeScript:*

Pass an idempotency key so the SDK can retry the request without placing a
second call.

The response carries the `callId` while the callee's device rings.
`call.accepted` follows when the callee picks up and `call.ended` when the call
ends. `to` is an E.164 phone number or a user ID. A server credential must name
`session`. `participant` names who acts on the call for your server, as
`server:agent-7`; it defaults to `default`. Set `video: true` for a video call.

The placing participant owns the call. Carry its audio with
[`CallsClient`](#speak-and-listen-on-a-call), a [browser](https://docs.polymorfa.com/calls/web), or a
[SIP trunk](https://docs.polymorfa.com/calls/sip-trunks).

### Place a group call

Instead of `to`, send `participants` with 2 to 31 distinct E.164 phone numbers
or user IDs, or `groupId` with a WhatsApp group whose roster has 2 to 31
remote members. Send exactly one destination form. Group calls need a
linked-device Number, and every recipient is checked against your team's call
policy and the Number's restrictions before dialing. A membership change
during placement refuses the call.

## Answer, decline, end and invite

| SDK method | HTTP request |
| --- | --- |
| `accept(callId, { exclusive, video, participant })` | `POST /messaging/voip/calls/{id}/accept` |
| `reject(callId)` | `POST /messaging/voip/calls/{id}/reject` |
| `leave(callId, { connectionId })` | `POST /messaging/voip/calls/{id}/leave` |
| `end(callId)` | `DELETE /messaging/voip/calls/{id}` |
| `addParticipant(callId, { to })` | `POST /messaging/voip/calls/{id}/participants` |

```ts
const accepted = await messaging.voip.accept(callId, {
  exclusive: true,
  participant: "agent-7",
});
console.log(accepted.data.data.answeredBy); // "server:agent-7"
```

Every inbound call raises `call.received`; answer it from your webhook handler.
`accept` returns `answered` (`true` when this request answered the call,
`false` when it joined an answered call), `answeredBy` and `exclusive`.
`reject` fails with `409 call_not_ringing` once the call was answered, declined
or ended. Later accepts by other participants join an answered call, unless the
first participant set `exclusive: true`; then they fail with `409 call_claimed`.

`addParticipant` rings another WhatsApp user into a live call, turning a
one-to-one call into a group call. Webhooks report the roster as
`call.participant_joined`, `call.participant_state` and
`call.participant_left`. To add people from your own app instead, give each a
client token and have them join the shared call.

## Speak and listen on a call

`CallsClient` follows the calls of one Number and carries a participant's media
over a WebSocket. Use it to answer calls with a voice agent, transcribe them, or
play audio.

```ts
import { CallsClient } from "@polymorfa/sdk/calls";

const client = new CallsClient({
  token: process.env.POLYMORFA_KEY!,
  session: "support",
  participant: "voice-agent",
});

client.on("incoming", async (call) => {
  await call.answer({ exclusive: true });
  call.audio.on("data", (pcm) => recognizer.push(pcm));
  call.audio.write(synth.speak("Hello, how can I help?"));
  call.on("ended", (reason) => console.log("ended:", reason));
});

await client.connect();
```

`recognizer` and `synth` stand for the speech services you choose. Polymorfa
carries the audio; it does not provide speech recognition, speech synthesis or
a voice agent.

- `call.audio` carries the call's merged audio as signed 16-bit mono PCM at
  `call.audio.sampleRate`, in both directions. Write audio in real time.
- `call.video` receives each other participant's video as a separate stream of
  H.264 frames and sends one H.264 stream of your own. `call.video.sources`
  names the participant behind each stream. Send a keyframe (an access unit
  with an IDR slice, with SPS and PPS in it or before it) when the
  `keyframeRequest` event fires. Other participants start receiving your video
  at your first IDR.
- When the connection drops, the client reconnects it and keeps the call. Call
  `client.disconnect()` to stop following the Number.
- From server code, `client.place("+15550100")` places a call this client
  carries.
- The client sends call diagnostics by default: an error code when media fails
  and the connection's reconnect count when it closes. Pass
  `diagnostics: false` to send none.

`@polymorfa/sdk/calls` runs on Node.js 22 or later, or on Node.js 20 with a
`WebSocket` implementation passed in the options.

## Change a Number's call settings

Each Number has call settings that apply to its calls:

| Setting | Default | Effect |
| --- | --- | --- |
| `callsEnabled` | `true` | `false` turns calling off for the Number without disconnecting it |
| `conferenceMode` | `true` | Whether your participants hear each other; see [Conference mode](https://docs.polymorfa.com/calls/how-calls-work#conference-mode) |
| `hostCloudApiCalls` | `false` | On a Cloud API Number, `true` has your Calls apps answer incoming calls instead of your Graph API integration |
| `simultaneousCalls` | `false` | On a linked-device Number, `true` lets it hold any number of calls at once; see [Simultaneous calls](#simultaneous-calls) |
| `inboundRoute`, `sipTrunkId`, `sipClaim` | `clients`, `null`, `true` | Route incoming calls to a SIP trunk; see [Connect a SIP trunk](https://docs.polymorfa.com/calls/sip-trunks#send-whatsapp-calls-to-your-pbx) |

**Console:**

Open the Number from **Numbers**, select **Settings**, then **Calls**. Every team
member can see the settings; team owners and admins change them.

- **Calls on this number** turns calling on or off.
- **Answer calls with Polymorfa Calls** appears on a Cloud API Number.
- **Conference mode** turns conference mode on or off.

Switches apply as soon as you change them. If someone else changed the
Number's call settings after the page loaded, the Console refuses your change
and shows the latest values. See [Calls in the Console](https://docs.polymorfa.com/calls/console#call-settings).

**API:**

```bash cURL
curl -X PUT "https://api.polymorfa.com/platform/sessions/support/call-settings" \
  -H "Authorization: Bearer $POLYMORFA_KEY" \
  -H "Content-Type: application/json" \
  -d '{ "conferenceMode": false, "expectedRevision": 0 }'
```

```typescript TypeScript
const current = await messaging.voip.retrieveCallSettings("support");

await messaging.voip.updateCallSettings("support", {
  conferenceMode: false,
  expectedRevision: current.data.data.revision,
});
```

An update changes only the settings you send. `revision` increases on every
change. Send the `revision` you read as `expectedRevision` to refuse the update
with `409 state_conflict` when someone changed the settings after you read
them; read them again and retry. Reading requires `sessions:read` and saving
requires `sessions:manage`, with a team key or a project token. Client tokens
cannot read or change call settings. See
[Get call settings](https://docs.polymorfa.com/api/calls/get-call-settings) and
[Update call settings](https://docs.polymorfa.com/api/calls/update-call-settings).

*TypeScript:*

A stale `expectedRevision` throws `PolymorfaConflictError` with
`state_conflict`; read the settings again and retry.

A Number without saved settings returns `callsEnabled: true`,
`conferenceMode: true`, `inboundRoute: "clients"`, `sipTrunkId: null`,
`sipClaim: true`, `hostCloudApiCalls: false`, `simultaneousCalls: false`,
`revision: 0` and `updatedAt: null`. A saved setting applies to a call the next time a
participant answers it or connects to it, including calls in progress;
`hostCloudApiCalls` applies to calls that arrive after the change. When the
settings cannot be read, answering and connecting fail with `503` instead of
using a value you did not choose.

### Turn calling off for a Number

While `callsEnabled` is `false`:

- placing a call, answering or joining one, inviting a participant and
  connecting media fail with `403 calls_disabled`. Starting or answering a call
  through the Graph API's `/calls` endpoint fails with a permission error;
- incoming calls are declined. You still receive `call.received`, followed by
  `call.rejected` and `call.ended`; and
- a [SIP trunk](https://docs.polymorfa.com/calls/sip-trunks) cannot place calls through the Number.

Calls in progress continue: the participant that answered or placed a call can
still reconnect its media, and leaving, ending and declining calls keep
working. Other participants cannot join a call in progress. A change reaches
incoming calls and SIP trunks within about a minute.

### Simultaneous calls

A Number on a linked device holds one call at a time, as WhatsApp's own apps
do. While a call is in progress, an incoming call waits until that call ends,
and placing a call waits for it too or fails when your request times out.

Turn on `simultaneousCalls` to let the Number hold any number of calls at
once: incoming, placed and from campaigns.

```bash
curl -X PUT "https://api.polymorfa.com/platform/sessions/support/call-settings" \
  -H "Authorization: Bearer $POLYMORFA_KEY" \
  -H "Content-Type: application/json" \
  -d '{ "simultaneousCalls": true, "acknowledgeRisk": true }'
```

> **Warning**
>
> WhatsApp's own apps never hold two calls at once, so this is unusual behavior
> for a WhatsApp account. A Number with simultaneous calls on is not covered by
> [Ban Credit](https://docs.polymorfa.com/safety/ban-insurance#who-it-covers): a ban that starts while
> the setting is on, or within 30 days after you turn it off, gets no credits
> back.

- Turning it on requires `acknowledgeRisk: true`, or the update fails with
  `400 invalid_parameter` on `acknowledgeRisk`. Changing other settings later
  does not ask again.
- Only a team key, or a team owner or admin in the Console, can turn it on. A
  project token can turn it off but gets `403 permission_denied` when turning
  it on.
- There is no limit on how many calls the Number holds. Each call is billed
  and rate limited as it would be on its own; the per-Number
  [outbound-start limit](https://docs.polymorfa.com/calls/how-calls-work#limits) still applies.
- The change applies to calls that start after it, within about a minute.
  Turning it off does not end calls in progress.
- Cloud API Numbers ignore the setting: their calls never wait for each other.
- While the setting is off, `simultaneousCallsCoverageExcludedUntil` on the
  call settings says when the exclusion from an earlier period ends: 30 days
  after that period ended. A ban is excluded when the setting was on at any
  time in the 30 days before it, so until this time a new ban gets no credits back.
  It is `null` while the setting is on, and `null` when no period ended in the
  last 30 days. It is read-only, and `null` does not mean the Number is
  covered: the other [Ban Credit](https://docs.polymorfa.com/safety/ban-insurance#who-it-covers)
  conditions still apply.

Polymorfa support can turn the setting off for a Number, for example when
WhatsApp starts restricting it. Only your team can turn it back on.

### Answer Cloud API calls with Polymorfa Calls

A Cloud API Number keeps answering its incoming calls through your Graph API
integration until you set `hostCloudApiCalls` to `true`. Then your Calls apps
receive and answer them, and the Graph API `/calls` endpoint refuses to answer
them. While calling is off, Polymorfa declines the Number's incoming calls
whatever this setting is. Calls you place with the SDKs always use Polymorfa
Calls.

### Handle Cloud API calls through the Graph API

An integration built on Meta's Calling API keeps sending its call actions to
[Manage a call](https://docs.polymorfa.com/api/graph/calls/manage-a-call) on the
[Graph API](https://docs.polymorfa.com/api/graph). It takes Meta's call actions: `connect` to
place a call, `pre_accept`, `accept`, `reject` and `terminate`.

```bash Graph API
curl -X POST "https://api.polymorfa.com/graph/whatsapp/v26.0/$PHONE_NUMBER_ID/calls" \
  -H "Authorization: Bearer $POLYMORFA_PROJECT_TOKEN" \
  -H "Content-Type: application/json" \
  -d '{ "messaging_product": "whatsapp", "call_id": "wacid.HBgLMTU1NTAxMDA", "action": "terminate" }'
```

**Graph API:** Meta Cloud API Numbers: Supported. Linked Devices Numbers: Not supported.

[Manage a call](https://docs.polymorfa.com/api/graph/calls/manage-a-call) needs
`messages:write`. Polymorfa forwards the request body to Meta unchanged.
Linked Devices Numbers return capability error `131026`.

- While calling is [off for the Number](#turn-calling-off-for-a-number),
  `connect`, `pre_accept` and `accept` fail with a permission error.
- `connect` is rate-limited per Number; a request above the limit fails
  without ringing anyone.
- With `hostCloudApiCalls` on, `pre_accept` or `accept` on a call that
  Polymorfa Calls handles fails with an invalid-parameter error. Answer it with
  the Calls API instead.
- `call_id` is Meta's call ID, as in Meta's Calling API, not a Polymorfa
  `callId`.

## See also

- [How calls work](https://docs.polymorfa.com/calls/how-calls-work)
- [Add calling to a web app](https://docs.polymorfa.com/calls/web)
- [Call permissions and opt-outs](https://docs.polymorfa.com/calls/permissions)
- [Connect a SIP trunk](https://docs.polymorfa.com/calls/sip-trunks)
