# Web calls

URL: https://www.callshift.ai/docs/web-calls

A web call connects a visitor of your website to one of your agents, in their browser and through their microphone, with no phone number on either side. Your server creates the call with [`POST /v1/web-calls`](https://www.callshift.ai/docs/api/web-calls#create-web-call), and your page joins it with the `@callshift/web` package.

## When to use a web call

- **A "Talk to us" button** on your website, for visitors who would rather speak than fill in a form.
- **Voice in your product**: an assistant your signed-in customers talk to, which knows who they are.
- **Trying an agent** while you build it, without dialing a number.

It is the same agent as on the phone, with its call flow and its after-call analysis. To answer or place phone calls instead, see [Phone numbers](https://www.callshift.ai/docs/phone-numbers) and [Outbound campaigns](https://www.callshift.ai/docs/campaigns).

## How a web call works

1. **Your server creates the call**: With your API key. The agent starts and waits for the visitor.
2. **It hands a token to the page**: The call's `accessToken`, never your API key.
3. **The browser joins**: With `@callshift/web`, within two minutes. The visitor and the agent talk.
4. **After the call**: CallShift analyses it and posts it to the agent's webhook, with your `metadata`.

## Set up a web call

1. ### Install the package in your page

   `@callshift/web` runs in the visitor's browser: add it to the JavaScript of your website, with npm or the package manager you use, whatever language your server is written in.

   ```bash
   npm install @callshift/web
   ```

2. ### Join from the browser

   When the visitor clicks, create a `CallshiftWebCall`, listen to its events, fetch a token from your server (step 3) and join:

   ```javascript
   import { CallshiftWebCall } from "@callshift/web";

   let call;

   startButton.addEventListener("click", async () => {
     // One CallshiftWebCall per call
     call = new CallshiftWebCall();
     call.on("status", (status) => {
       // "connecting", then "live", then "ended"
       statusLabel.textContent = status;
     });
     call.on("error", (error) => console.error(error.code, error.message));

     // Your server creates the web call and returns its accessToken
     const res = await fetch("/api/web-call", { method: "POST" });
     const { accessToken } = await res.json();
     await call.join({ accessToken });
   });

   endButton.addEventListener("click", () => call?.end());
   ```

   `join()` asks for the microphone, joins the call and resolves once it is `live`. A `CallshiftWebCall` serves one call: create a new one for the next call, as `join()` refuses to run twice.

3. ### Create the call on your server

   The page gets its token from a route of your server, here `POST /api/web-call`. That route creates the web call with [`POST /v1/web-calls`](https://www.callshift.ai/docs/api/web-calls#create-web-call) and answers with the `accessToken`. Any language that can send an HTTPS request will do: there is nothing to install on the server.

   **cURL**

   ```bash
   curl -X POST "https://api.callshift.ai/v1/web-calls" \
     -H "Authorization: Bearer $CALLSHIFT_API_KEY" \
     -H "Content-Type: application/json" \
     -d '{
       "agentId": "550e8400-e29b-41d4-a716-446655440000",
       "contact": { "firstName": "Ada", "lastName": "Lovelace", "metadata": { "plan": "pro" } },
       "metadata": { "orderId": "A-42" }
     }'
   ```

   **JavaScript**

   ```javascript
   // On your server, behind the route your page calls, such as POST /api/web-call
   const res = await fetch("https://api.callshift.ai/v1/web-calls", {
     method: "POST",
     headers: {
       Authorization: `Bearer ${process.env.CALLSHIFT_API_KEY}`,
       "Content-Type": "application/json",
     },
     body: JSON.stringify({
       agentId: "550e8400-e29b-41d4-a716-446655440000",
       contact: { firstName: "Ada", lastName: "Lovelace", metadata: { plan: "pro" } },
       metadata: { orderId: "A-42" },
     }),
   });
   const { accessToken } = await res.json();
   // Send accessToken, and nothing else, to the page.
   ```

   **Python**

   ```python
   import os
   import requests

   res = requests.post(
       "https://api.callshift.ai/v1/web-calls",
       headers={"Authorization": f"Bearer {os.environ['CALLSHIFT_API_KEY']}"},
       json={
           "agentId": "550e8400-e29b-41d4-a716-446655440000",
           "contact": {"firstName": "Ada", "lastName": "Lovelace", "metadata": {"plan": "pro"}},
           "metadata": {"orderId": "A-42"},
       },
   )
   access_token = res.json()["accessToken"]
   ```

   | Field | What it does |
   | --- | --- |
   | `agentId` | Required. The agent that takes the call. |
   | `contact` | Who is calling: `salutation`, `firstName`, `lastName`, `email`, `phone` and `metadata` (16 KB of JSON at most). They fill the agent's `contact.*` variables, the same ones as in a campaign: see [Variables and contact data](https://www.callshift.ai/docs/variables). The contact is neither looked up in nor written to your CRM. |
   | `metadata` | Yours, 16 KB of JSON at most, such as an order or a session id. Never shown to the agent, and returned as sent with the call and in the after-call webhook. |

   The answer, a `201`:

   ```json
   {
     "callId": "550e8400-e29b-41d4-a716-446655440000",
     "accessToken": "eyJzZXJ2ZXJVcmwiOi…",
     "expiresAt": "2026-01-01T10:02:00.000Z"
   }
   ```

   The `accessToken` is opaque: pass it on as it is, without decoding it. The browser must join before `expiresAt`, two minutes after the call was created.

   > **Keep the API key on the server**
   >
   > Never call [`POST /v1/web-calls`](https://www.callshift.ai/docs/api/web-calls#create-web-call) from the browser: the page would expose your API key. The call is built from the `agentId` and the `contact` your server sends, so nothing the browser sends shapes it. Your route decides who may start a call: signed-in customers only, for example, or visitors who passed a bot check.

4. ### End the call

   `await call.end()` hangs up. The status `ended` arrives once, whoever ends the call: the visitor with `end()`, or the agent hanging up.

## Call events

| Event | Its argument | When |
| --- | --- | --- |
| `status` | `"connecting"`, `"live"` or `"ended"` | Each time the call changes state, in this order |
| `agentSpeaking` | `true` or `false` | When the agent starts or stops speaking |
| `transcript` | `{ id, speaker, text, final }` | While the agent and the visitor speak |
| `error` | A `CallshiftWebCallError` | When the call fails: see [Errors](https://www.callshift.ai/docs/web-calls#errors) |

`call.on()` returns a function that removes the listener.

### Show a live transcript

`speaker` is `"agent"` or `"caller"`, the visitor. A segment arrives several times as its text grows, with the same `id`, and the last time with `final: true`: replace the line of that `id` rather than adding a line for each event.

```javascript
const lines = new Map(); // segment id, then its line on the page

call.on("transcript", ({ id, speaker, text, final }) => {
  let line = lines.get(id);
  if (!line) {
    line = document.createElement("p");
    line.className = speaker; // "agent" or "caller"
    lines.set(id, line);
    transcriptBox.append(line);
  }
  line.textContent = text; // the whole segment so far
  line.classList.toggle("pending", !final);
});
```

## Mute the microphone

`mute()` stops sending the visitor's microphone to the agent, and `unmute()` starts it again. `agentSpeaking` lets the page show when the agent is talking.

```javascript
await call.mute();   // the agent no longer hears the visitor
await call.unmute();

call.on("agentSpeaking", (isSpeaking) => {
  avatar.classList.toggle("speaking", isSpeaking);
});
```

## Errors

In the browser, `error.code` says what went wrong. When `join()` fails, the call emits `error`, then the status `ended`, and `join()` rejects with the same error.

| `error.code` | What happened |
| --- | --- |
| `invalid_access_token` | The token is not one that [`POST /v1/web-calls`](https://www.callshift.ai/docs/api/web-calls#create-web-call) returned. |
| `microphone_unavailable` | The visitor refused the microphone, or has none. |
| `connection_failed` | The call could not be joined, often because its token expired. Create another call. |

```javascript
import { CallshiftWebCallError } from "@callshift/web";

try {
  await call.join({ accessToken });
} catch (error) {
  if (error instanceof CallshiftWebCallError && error.code === "microphone_unavailable") {
    showMessage("Allow the microphone to talk to us.");
  } else {
    showMessage("The call could not start. Try again.");
  }
}
```

On your server, [`POST /v1/web-calls`](https://www.callshift.ai/docs/api/web-calls#create-web-call) can answer:

| Status | Meaning |
| --- | --- |
| `400` | The body is not valid, such as a missing `agentId` |
| `401` | The API key is missing or unknown |
| `402` | The account cannot pay for calls: no active subscription, or not enough credit |
| `404` | No agent has this `agentId` |
| `415` | The body was not sent as `application/json` |

The error bodies are described in [Errors](https://www.callshift.ai/docs/errors).

## In the browser

- **HTTPS.** Browsers grant the microphone to secure pages only: `https://`, or `http://localhost` while you develop.
- **A click first.** Call `join()` from a click, or another gesture of the visitor, so that the browser lets the agent's voice play.
- **Content-Security-Policy.** If your site sets one, its `connect-src` must allow the servers that carry the call's audio, over `https:` and `wss:`. Ask `support@callshift.ai` for the hosts to allow.

## After the call

- The call is in [`GET /v1/calls`](https://www.callshift.ai/docs/api/calls#list-calls) and [`GET /v1/calls/{callId}`](https://www.callshift.ai/docs/api/calls#get-call) like any other, with the `type` `webcall` and the `metadata` you created it with. `type=webcall` lists the web calls only.
- The agent's [after-call webhook](https://www.callshift.ai/docs/webhooks) receives it too, with `"web-call"` as its `callerNumber` and your `metadata`.
- Billing starts when the browser joins. A call nobody joins before `expiresAt` ends as not reached, and is billed nothing.

In the call flow, a web call counts as an inbound call: the edges marked `inboundOnly` apply to it. Transfers are not offered during a web call: the agent cannot pass the visitor to a number of your team.

## Example project

The package's repository has an [example](https://github.com/Callshift/client-sdk-web/tree/main/example): a page and a small Node.js server that create a web call through the API and join it. The package is on [npm](https://www.npmjs.com/package/@callshift/web).

## FAQ

**Can the page create the web call itself?**

No. Creating a web call takes your API key, which a page would show to every visitor. Your server creates the call and hands the page its `accessToken`.

**How long is an access token valid?**

Two minutes, until its `expiresAt`. Create the call when the visitor clicks, not when the page loads. An expired token fails with `connection_failed`: create another call.

**How do I give the agent the visitor's details?**

Send them in `contact` when your server creates the call: the agent has them in its `contact.*` variables from its first sentence. Keep what is only for your systems in `metadata`, which the agent never sees.

**Can the agent transfer a web call to my team?**

No. Transfers are not offered during a web call, only during phone calls.

**What if the visitor refuses the microphone?**

`join()` fails with `microphone_unavailable`, which also covers a device without a microphone. Ask the visitor to allow it in the browser, then create a new call.
