# LexoConnect developer API guide

Build your own product on LexoConnect: phone calls, phone system (PBX), contact center, messaging, AI agents and CRM, all through the REST API and webhooks.

The full API reference (every endpoint and field) is the OpenAPI file `openapi.yaml`, published next to this guide.

## Contents

1. [Overview](#overview)
2. [Getting started](#getting-started)
3. [Calls](#calls)
4. [Phone system (PBX)](#phone-system-pbx)
5. [Contact center](#contact-center)
6. [Messaging](#messaging)
7. [AI agents and ringless voicemail](#ai-agents-and-ringless-voicemail)
8. [CRM](#crm)
9. [Webhooks](#webhooks)
10. [Embedding](#embedding)
11. [Recipes](#recipes)


---

# Overview

_Build your own product on LexoConnect. Calls, phone system, contact center, messaging, AI agents and CRM are all available through one REST API and signed webhooks._

## What you can build

LexoConnect is a cloud phone system (PBX), contact center, dialer, omnichannel inbox and CRM in one product. Everything the LexoConnect app does goes through the same REST API that you can use. A partner company can therefore build its own product on top of LexoConnect, for example:

- a **CRM or helpdesk integration** with click-to-call buttons, screen pops and every call logged automatically;
- its **own softphone or agent desktop** on top of LexoConnect's SIP/WebRTC service;
- an **outbound sales tool** that loads leads into LexoConnect dialer campaigns and reads the outcomes back;
- an **SMS / WhatsApp / email bot** that receives messages by webhook and answers through the API;
- **AI voice agents** that answer calls, book appointments in the partner's system and hand over to humans.

## How the pieces fit

| Piece | What it is for |
| --- | --- |
| REST API (`/api/v1`) | Read and change everything: calls, users, numbers, queues, IVR, campaigns, messages, CRM, AI agents. JSON over HTTPS, authenticated with an API key. |
| Webhooks | LexoConnect calls your server when something happens: a call rings, is answered or ends, a recording is ready, a message arrives, an agent saves an outcome. Signed per the Standard Webhooks specification. |
| Webphone embed and SDK | Put a working phone inside your own web app with an iframe or a small JavaScript SDK. Your server mints a short-lived token; the API key never reaches the browser. |
| SIP / WebRTC | Desk phones, softphones and your own WebRTC client register to LexoConnect with SIP credentials. |

## Your first call in three steps

1. Ask a LexoConnect admin of the company to create an **API key** in *Admin → Developer → API keys* with the scopes you need (see [Getting started](#getting-started)).
2. Check the key:

```bash
curl "$LEXO_URL/api/v1/me" -H "Authorization: Bearer $LEXO_API_KEY"
```

3. Place a click-to-call: the user's phone rings first, then LexoConnect dials the customer.

```bash
curl -X POST "$LEXO_URL/api/v1/calls/originate" \
  -H "Authorization: Bearer $LEXO_API_KEY" -H "Content-Type: application/json" \
  -d '{"extension": "101", "to": "+12125550123"}'
```

## Guide contents

| Page | Read it when you want to |
| --- | --- |
| [Getting started](#getting-started) | create a key, authenticate, page through lists and handle errors and rate limits |
| [Calls](#calls) | place calls, control live calls (transfer, conference, record, park, hang up), read call history and recordings, monitor calls |
| [Phone system (PBX)](#phone-system-pbx) | manage users and extensions, numbers and their routing, queues, IVR call flows, business hours and voicemail |
| [Contact center](#contact-center) | run dialer campaigns, upload leads, save dispositions and callbacks, read the wallboard, use call scripts and do-not-call lists |
| [Messaging](#messaging) | send and receive SMS, WhatsApp, email and chat, and work with conversations |
| [AI agents and ringless voicemail](#ai-agents-and-ringless-voicemail) | create AI voice agents, place AI calls, read AI call history, send ringless voicemails |
| [CRM](#crm) | create and search contacts and other records, add notes and tasks, read the timeline |
| [Webhooks](#webhooks) | receive events, verify signatures, handle retries |
| [Embedding](#embedding) | embed the webphone or the chat widget in your product |
| [Recipes](#recipes) | follow complete, end-to-end examples |

The [API reference](/docs/api) lists every endpoint, field and response. The same definition is available as an [OpenAPI file](/docs/api/openapi.yaml) for Postman or a code generator, and this whole guide can be downloaded as [one Markdown file](/docs/guide.md) to share with your team.

---

# Getting started

_API keys and scopes, the base URL, request and response format, pagination, errors, rate limits and versioning._

## Create an API key

API keys are created by an admin of the company (tenant) the integration works for, in *Admin → Developer → API keys*:

1. Click **New API key**, give it a name (for example the partner's product name) and pick the **scopes** it needs.
2. Optionally set an expiry date and a rate limit.
3. Copy the key. It starts with `nc_live_` and is shown **once**; LexoConnect only keeps a hash.

A key acts as the admin who created it, in that company only, limited to its scopes. It can never reach platform, billing, trunk, channel or API key management endpoints, and it never acts across companies. Every write made with a key is in the company's audit log, and the last use is shown next to the key. Revoke a key at any time; it stops working at once.

> **Least privilege.** Give each integration its own key with only the scopes it needs. When the admin who created a key leaves (is disabled or deleted), create a new key with another admin.

### Scopes

Every endpoint in the [API reference](/docs/api) shows the scope it needs. A request outside the key's scopes is refused with `403 forbidden`.

<!-- gen:scopes -->
| Scope | What it allows |
| --- | --- |
| `calls:read` | List and read calls, recordings, voicemails and parked calls |
| `calls:write` | Place click-to-call calls, hang up, transfer, record, park and pick up calls |
| `calls:monitor` | Listen to, whisper into or barge into live calls and read the wallboard |
| `numbers:read` | Read numbers and routing objects (queues, schedules, call flows, caller ID profiles) |
| `numbers:write` | Change number routing; create, update and delete queues (and members), schedules, call flows and caller ID profiles |
| `crm:read` | Read CRM objects, records, activities; search records by phone |
| `crm:write` | Create, update and delete CRM records, activities and notes |
| `messages:read` | List conversations and messages (SMS, WhatsApp, email, chat) |
| `messages:write` | Send messages and start conversations |
| `users:read` | List users and extensions |
| `users:write` | Create, update and delete users (extension, role, queue membership, manual outbound AMD) |
| `reports:read` | Read call, missed call, agent, queue and campaign reports |
| `campaigns:read` | Read dialer campaigns and their leads |
| `campaigns:write` | Manage campaigns, upload leads and edit the do-not-call list |
| `webphone` | Mint webphone tokens for users |
| `webhooks` | Manage webhook endpoints and read the delivery log |
| `rvm:read` | Read voicemail messages and ringless voicemail / voicemail drop results |
| `rvm:write` | Create voicemail messages and send ringless voicemails / voicemail drops |
| `ai:read` | Read AI agents and AI call history (transcripts, tool log, outcome) |
| `ai:write` | Create, update and delete AI agents and place outbound AI agent calls |
<!-- /gen -->

## Base URL and authentication

All endpoints live under one base URL:

```text
https://telco.lexogenix.com/api/v1
```

If your LexoConnect provider runs LexoConnect on its own domain, use that domain instead; only the host changes. The samples in this guide read the host and key from two environment variables:

```bash
export LEXO_URL="https://telco.lexogenix.com"
export LEXO_API_KEY="nc_live_..."
```

Send the key as a bearer token on every request:

```bash
curl "$LEXO_URL/api/v1/me" -H "Authorization: Bearer $LEXO_API_KEY"
```

```javascript
// Node.js 18+ (built-in fetch). Reused by the JavaScript samples in this guide.
const BASE = `${process.env.LEXO_URL}/api/v1`;
const KEY = process.env.LEXO_API_KEY;

async function lexo(method, path, body) {
  const res = await fetch(BASE + path, {
    method,
    headers: { Authorization: `Bearer ${KEY}`, ...(body ? { "Content-Type": "application/json" } : {}) },
    body: body ? JSON.stringify(body) : undefined,
  });
  if (res.status === 204) return null;
  const data = await res.json();
  if (!res.ok) throw new Error(`${res.status} ${data.error?.code}: ${data.error?.message}`);
  return data;
}

console.log(await lexo("GET", "/me"));
```

```python
# Python 3 with requests. Reused by the Python samples in this guide.
import os, requests

BASE = os.environ["LEXO_URL"] + "/api/v1"
s = requests.Session()
s.headers["Authorization"] = "Bearer " + os.environ["LEXO_API_KEY"]

def lexo(method, path, json=None, **kw):
    r = s.request(method, BASE + path, json=json, timeout=30, **kw)
    if r.status_code == 204:
        return None
    data = r.json()
    if not r.ok:
        raise RuntimeError(f"{r.status_code} {data['error']['code']}: {data['error']['message']}")
    return data

print(lexo("GET", "/me"))
```

`GET /me` answers with the key's user and company, so it is the quickest way to check a key.

> **Never put an API key in a browser or a mobile app.** Keys belong on your server. To give a browser a phone, mint a short-lived webphone token on your server (see [Embedding](#embedding)).

## Requests and responses

- Request and response bodies are JSON (`Content-Type: application/json`) with camelCase field names. A few uploads use `multipart/form-data`; the reference says so.
- Ids are UUIDs. Times are RFC 3339 in UTC, for example `2026-11-13T15:04:05Z`.
- Phone numbers are E.164: `+` followed by the country code and number, for example `+12125550123`.
- `PATCH` changes only the fields you send. `PUT` replaces the whole object (absent fields take their defaults).
- Successful creates answer `201`, deletes `204` with no body, and operations that start something in the background (placing a call, sending a voicemail drop) `202`.

## Pagination

List endpoints return an envelope:

```json
{ "items": [ { "id": "..." } ], "nextCursor": "eyJ0IjoiMjAyNi0xMS0xM1QxNTowNDowNVoifQ" }
```

Pass `limit` (1–200, default 50 where supported) and, for the next page, `cursor` set to the previous `nextCursor`. `nextCursor` is `null` on the last page. Lists are newest first unless the reference says otherwise.

```bash
curl "$LEXO_URL/api/v1/calls?limit=100" -H "Authorization: Bearer $LEXO_API_KEY"
curl "$LEXO_URL/api/v1/calls?limit=100&cursor=NEXT_CURSOR" -H "Authorization: Bearer $LEXO_API_KEY"
```

```javascript
// Every call of the key's user, page by page.
let cursor = null;
do {
  const page = await lexo("GET", `/calls?limit=100${cursor ? `&cursor=${encodeURIComponent(cursor)}` : ""}`);
  for (const call of page.items) console.log(call.startedAt, call.direction, call.from, call.to, call.status);
  cursor = page.nextCursor;
} while (cursor);
```

```python
cursor = None
while True:
    page = lexo("GET", "/calls", params={"limit": 100, **({"cursor": cursor} if cursor else {})})
    for call in page["items"]:
        print(call["startedAt"], call["direction"], call["from"], call["to"], call["status"])
    cursor = page["nextCursor"]
    if not cursor:
        break
```

### Page numbers

Every list that is not cursor-paged also accepts page numbers. Send `page` (from 1) and `pageSize` (1–100, default **10**; larger values are reduced to 100), optionally `q` to search the items' text and `sort` to order by a field (`sort=name`, `sort=-createdAt` for descending). The response then carries the total:

```json
{ "items": [ { "id": "..." } ], "total": 137, "page": 2, "pageSize": 25, "nextCursor": null }
```

```bash
curl -s "$LEXO_URL/api/v1/queues?page=2&pageSize=25&sort=name" -H "Authorization: Bearer $LEXO_API_KEY"
```

Without `page`/`pageSize` these lists answer as before (`{items, nextCursor: null}` with every item, capped at 1,000; `"truncated": true` marks a capped list), so existing integrations keep working. Lists that page with `cursor` (calls, conversations, CRM records, audit log, opt-outs) keep using the cursor.

## Errors

Errors use HTTP status codes and one JSON shape:

```json
{ "error": { "code": "validation_error", "message": "Validation failed", "fields": { "to": "must be a phone number" } } }
```

`fields` is present for validation errors and names each wrong field.

| HTTP | `code` | Meaning |
| --- | --- | --- |
| 400 | `validation_error` | The request is malformed or a field is wrong; see `fields`. |
| 401 | `unauthorized` | Missing, wrong, expired or revoked key, or the user who created the key is no longer active. |
| 402 | `payment_required`, `insufficient_balance` | The company's plan or prepaid balance does not allow it (for example no balance for an outbound call). |
| 403 | `forbidden` | The key lacks the scope, the endpoint is not available to keys, the user's role does not allow it, or the company is suspended. |
| 403 | `module_disabled`, `feature_disabled` | The feature is not part of the company's plan or is switched off. |
| 403 | `call_blocked` | Call protection or fraud rules refused the destination. |
| 404 | `not_found` | The object does not exist or the key's user may not see it. |
| 409 | `conflict` | The object is in the wrong state (for example a campaign must be paused before it is deleted, or a call is not live any more). |
| 409 | `opted_out`, `consent_required` | The recipient opted out, or consent must be attested first. |
| 429 | `rate_limited` | Too many requests; wait for `Retry-After` seconds. |
| 500 | `internal` | Something went wrong on LexoConnect's side; retry later. |
| 503 | `media_unavailable`, `service_unavailable` | The phone system (or another part) is briefly unavailable; retry shortly. |

Treat any unknown `code` by its HTTP status. Retry only `429`, `500` and `503`, with back-off.

## Rate limits

- **Per key:** 600 requests a minute by default. The admin can set each key between 1 and 6 000 requests a minute.
- **Per IP address:** 600 requests a minute with bursts of up to 200, for all traffic from one address.

Over a limit the API answers `429 rate_limited` with `Retry-After: 10`. Prefer webhooks to polling: they arrive within seconds and cost no requests.

## Retries and idempotency

The API does not support an `Idempotency-Key` header. Before retrying a request that creates something (a call, a message, a record), check whether the first attempt succeeded:

- place calls once and follow them through the `call.*` webhooks;
- for records, search first (`GET /crm/lookup?phone=...`) and create only when nothing is found;
- for webhooks, deduplicate on the `webhook-id` header, which stays the same across retries.

## Versioning

The version is in the path (`/api/v1`). Within v1, LexoConnect only adds things: new endpoints, new optional request fields, new response fields and new webhook event types. Your code must ignore fields it does not know. A breaking change would ship as `/api/v2`, with v1 kept running alongside it.

## Testing safely

- Ask your LexoConnect provider for a separate **test company** (tenant) and create the key there. Test data never mixes with live customers.
- Use test phone numbers you own; outbound calls and messages are real and are billed from the company's prepaid balance.
- Point webhooks at a request inspector or a local tunnel while you develop, and use **Send test event** on the endpoint.
- Use short-lived keys (set an expiry) for experiments, and revoke them afterwards.

---

# Calls

_Place calls, control live calls, read call history, download recordings and transcripts, and monitor calls in progress._

## How calls work

Every call belongs to a **user** (an extension) of the company. When your integration places a call with the API, LexoConnect first rings that user's phone (the browser webphone, a softphone or a desk phone); when the user answers, LexoConnect dials the customer as that user. All the company's rules apply exactly as if the user had dialed: caller ID profiles, call protection and fraud checks, least-cost routing over the company's trunks, the recording policy and the prepaid balance.

A call has two ids:

- `id`: the **call record** id (UUID) used by the history endpoints (`GET /calls/{id}`, recordings, events, transcript).
- `callUuid`: the id of the **live** call. The live control endpoints (hang up, transfer, record, park, conference, monitor) accept any leg UUID of the live call, or `current` for the key user's own active call. Webhooks (`call.ringing`, `call.answered`) and the wallboard carry `callUuid`.

## Place a call (click-to-call)

`POST /calls/originate` (scope `calls:write`). Give the destination `to` (E.164 or an extension) and the user whose phone rings first, by `userId` or `extension` (default: the key's user). Placing a call for another user needs the creator of the key to be a supervisor or admin.

```bash
curl -X POST "$LEXO_URL/api/v1/calls/originate" \
  -H "Authorization: Bearer $LEXO_API_KEY" -H "Content-Type: application/json" \
  -d '{"extension": "101", "to": "+12125550123", "timeoutSec": 30}'
```

```javascript
const call = await lexo("POST", "/calls/originate", { extension: "101", to: "+12125550123", timeoutSec: 30 });
console.log(call.status, call.callUuid); // "ringing_user", "3f0c1d8e-..."
```

```python
call = lexo("POST", "/calls/originate", {"extension": "101", "to": "+12125550123", "timeoutSec": 30})
print(call["status"], call["callUuid"])
```

The answer comes as soon as the user's phone starts ringing (`202`):

```json
{ "status": "ringing_user", "callUuid": "3f0c1d8e-7a51-4d1b-9a3e-2b51d2f4b6a0", "userId": "0b7e5d1c-...", "extension": "101", "userName": "Olivia Owner", "to": "+12125550123" }
```

Optional fields: `callerId` (an E.164 number the company owns, to present to the customer) and `timeoutSec` (how long the user's phone rings, 5–120, default 30). Follow the call through the `call.answered` and `call.ended` webhooks rather than polling.

> To place a call **without a human** (an AI agent talks to the customer), use `POST /ai-agents/{id}/calls`; see [AI agents](#ai-agents-and-ringless-voicemail). To dial lists of numbers, use a dialer campaign; see [Contact center](#contact-center).

## Control a live call

All of these take the live call reference in the path (`callUuid`, any leg UUID, or `current`). Scope `calls:write`.

| Action | Endpoint | Body |
| --- | --- | --- |
| Hang up | `POST /calls/{id}/hangup` | none |
| Transfer | `POST /calls/{id}/transfer` | `{"target": "...", "mode": "blind" \| "attended"}` |
| Add a third party (3-way call) | `POST /calls/{id}/conference` | `{"add": "102"}` (extension or E.164) |
| Leave a 3-way call | `POST /calls/{id}/conference/leave` | none |
| Start or stop recording | `POST /calls/{id}/recording` | `{"action": "start"}` or `{"action": "stop"}` |
| Park | `POST /calls/{id}/park` | optional `{"timeoutSec": 120}` |
| Pick up a parked call | `POST /parked/{slot}/pickup` | none |
| Leave a saved voicemail and free the agent | `POST /calls/{id}/voicemail-drop` | `{"messageId": "..."}` |

**Transfer targets:** an extension (`"102"`), an E.164 number, `queue:<queueId>`, `ai_agent:<agentId>`, `voicemail:<userId>` or `callflow:<callflowId>`. A **blind** transfer hands the caller over at once; an **attended** transfer first connects the transferring user with the target.

```bash
curl -X POST "$LEXO_URL/api/v1/calls/3f0c1d8e-7a51-4d1b-9a3e-2b51d2f4b6a0/transfer" \
  -H "Authorization: Bearer $LEXO_API_KEY" -H "Content-Type: application/json" \
  -d '{"target": "queue:6f1e2d3c-4b5a-4968-8776-5a4b3c2d1e0f", "mode": "blind"}'
```

```javascript
await lexo("POST", `/calls/${callUuid}/transfer`, { target: "queue:6f1e2d3c-4b5a-4968-8776-5a4b3c2d1e0f", mode: "blind" });
```

```python
lexo("POST", f"/calls/{call_uuid}/transfer", {"target": "queue:6f1e2d3c-4b5a-4968-8776-5a4b3c2d1e0f", "mode": "blind"})
```

**Park** puts the caller on hold in a numbered slot (`GET /parked` lists them) where any user can pick the call up. There is no separate hold / unhold endpoint: hold is a button on the user's phone, and park is the server-side way to hold a caller for someone else. Live control answers `409 conflict` when the call has already ended and `503 media_unavailable` when the phone system is briefly unreachable.

## Call history

`GET /calls` (scope `calls:read`) lists calls newest first, with filters `direction` (`inbound`, `outbound`, `internal`), `status` (`answered`, `missed`, `voicemail`, `ai_handled`, `failed`), `mine=true`, `limit` and `cursor`. Without the supervisor role, the creator of the key sees only their own calls.

```bash
curl "$LEXO_URL/api/v1/calls?direction=inbound&status=missed&limit=50" -H "Authorization: Bearer $LEXO_API_KEY"
```

```javascript
const missed = await lexo("GET", "/calls?direction=inbound&status=missed&limit=50");
```

```python
missed = lexo("GET", "/calls", params={"direction": "inbound", "status": "missed", "limit": 50})
```

Each call record has `from`, `to`, `fromName`, `toName`, `startedAt`, `answeredAt`, `endedAt`, `durationSec`, `status`, `hangupCause`, the handling `userId`, the linked CRM `recordId`, the `dispositionId` saved at wrap-up, `transferCount`, the `callerIdUsed` and the answering machine result `amdResult` (`human`, `machine`, `unknown`). More detail:

- `GET /calls/{id}`: one call.
- `GET /calls/{id}/events`: what happened during the call (transfers, park and pickup, recording, answering machine detection).
- `GET /calls/{id}/transcript`: the transcript and AI summary of a call that was transcribed (when live transcription is on for the queue or campaign).
- `GET /calls/{id}/recordings`: the on-demand recordings of a call.
- `GET /reports/missed-calls` and `GET /reports` (scope `reports:read`): totals by number, queue, agent, hour or day, as JSON or CSV (`format=csv`).

The `call.ended` webhook delivers the same call record the moment a call ends, which is the best way to keep another system in sync.

## Recordings and voicemail

| What | Endpoint |
| --- | --- |
| Full-call recording (audio) | `GET /calls/{id}/recording` |
| One on-demand recording (audio) | `GET /calls/{id}/recordings/{recId}/audio` |
| Voicemails of the key's user (or all, for admins) | `GET /voicemails` |
| Voicemail audio | `GET /voicemails/{id}/audio` |
| Mark a voicemail read / delete it | `PATCH /voicemails/{id}` `{"read": true}` / `DELETE /voicemails/{id}` |

Audio downloads need the `Authorization` header. To play a recording in a browser or another system without a key, ask for a **signed link** (valid 1 hour by default, at most 24 hours):

```bash
curl -X POST "$LEXO_URL/api/v1/media/sign" \
  -H "Authorization: Bearer $LEXO_API_KEY" -H "Content-Type: application/json" \
  -d '{"url": "/api/v1/calls/8a7c2b4e-5f1d-4c3a-9b2e-1d0f3a6b7c8d/recording", "expiresInSec": 3600}'
```

```javascript
const { absoluteUrl } = await lexo("POST", "/media/sign", { url: `/api/v1/calls/${callId}/recording`, expiresInSec: 3600 });
// <audio src={absoluteUrl} controls />
```

```python
link = lexo("POST", "/media/sign", {"url": f"/api/v1/calls/{call_id}/recording", "expiresInSec": 3600})
audio = requests.get(link["absoluteUrl"], timeout=60).content
```

The `recording.ready` and `voicemail.created` webhooks already include a 24-hour `signedUrl`.

## Monitor live calls (listen, whisper, barge)

Scope `calls:monitor`. Supervisors can join a live call in three modes:

- `listen`: hear both sides, unheard;
- `whisper`: talk to the agent only (coaching);
- `barge`: talk to both sides.

`POST /calls/{id}/monitor` rings the monitoring user's phone (the key's user, or `userId`); when they answer they join the call.

```bash
curl -X POST "$LEXO_URL/api/v1/calls/3f0c1d8e-7a51-4d1b-9a3e-2b51d2f4b6a0/monitor" \
  -H "Authorization: Bearer $LEXO_API_KEY" -H "Content-Type: application/json" \
  -d '{"mode": "listen"}'
```

```javascript
await lexo("POST", `/calls/${callUuid}/monitor`, { mode: "whisper", userId: supervisorId });
```

```python
lexo("POST", f"/calls/{call_uuid}/monitor", {"mode": "barge"})
```

`GET /supervisor/board` (same scope) is the live wallboard: queues, agents with their state, live calls with their `uuid`, and `missedToday`. Use it to show live calls in your own dashboard and to pick the call to monitor.

## Wrap-up after a call

When the agent's wrap-up is done in your own product, save it with `POST /calls/wrapup` (scope `calls:write`). Send the customer's `number` and the call `direction`, plus at least one of a `dispositionId` (from `GET /dispositions`), a `note` or a follow-up time `followUpAt`. LexoConnect stores it on the CRM record (by `recordId`, else the newest record with that number) and its timeline; a follow-up becomes a task. For a dialer call, add `campaignLeadId` so the lead is retried or completed according to the disposition. LexoConnect then sends the `call.dispositioned` webhook.

```bash
curl -X POST "$LEXO_URL/api/v1/calls/wrapup" \
  -H "Authorization: Bearer $LEXO_API_KEY" -H "Content-Type: application/json" \
  -d '{"number": "+12125550123", "direction": "outbound", "dispositionId": "4b5c6d7e-8f90-4a1b-2c3d-4e5f6a7b8c9d", "note": "Interested, call back next week", "followUpAt": "2026-11-20T15:00:00Z"}'
```

```javascript
const { items: dispositions } = await lexo("GET", "/dispositions");
const interested = dispositions.find((d) => d.label === "Interested");
await lexo("POST", "/calls/wrapup", { number: "+12125550123", direction: "outbound", dispositionId: interested.id, note: "Wants a demo" });
```

```python
dispositions = lexo("GET", "/dispositions")["items"]
lexo("POST", "/calls/wrapup", {"number": "+12125550123", "direction": "outbound", "dispositionId": dispositions[0]["id"], "note": "Wants a demo"})
```

A disposition that schedules a callback (for example "Call back") requires `followUpAt`; the request is refused with `400` otherwise.

---

# Phone system (PBX)

_Users and extensions, phones and SIP credentials, numbers and inbound routing, queues, IVR call flows, business hours, caller ID and voicemail._

## The building blocks

| Object | What it is | Endpoints |
| --- | --- | --- |
| User | A person with a login, a role and an **extension** (their internal number). | `/users` |
| Phone | Where a user's calls ring: the browser webphone, a softphone or desk phone (SIP), or both. | `phoneType` on the user |
| Number | A phone number (DID) of the company and where its inbound calls go. | `/numbers` |
| Queue | A group of users that share calls (ring all, in order, round robin, longest idle). | `/queues` |
| Call flow | An IVR menu ("press 1 for sales"), built as a graph of steps. | `/callflows` |
| Schedule | Business hours and holidays; numbers route differently outside them. | `/schedules` |
| Caller ID profile | Which number customers see on outbound calls (fixed, local presence, rotate, or your own URL). | `/caller-id-profiles` |

Reading these needs `users:read` / `numbers:read`; changing them needs `users:write` / `numbers:write`.

## Users and extensions

```bash
curl "$LEXO_URL/api/v1/users" -H "Authorization: Bearer $LEXO_API_KEY"
```

```javascript
const { items: users } = await lexo("GET", "/users");
const byExtension = Object.fromEntries(users.map((u) => [u.extension, u]));
```

```python
users = lexo("GET", "/users")["items"]
```

Create (invite) a user with `POST /users`: `email`, `name`, `role` (`agent`, `supervisor` or `admin`), `extension`, the queues they belong to, and `phoneType`. The answer is `{"user": {...}, "tempPassword": "..."}`: the user is `invited` and receives an invitation email with the temporary password (when the platform has email set up), and sets their own password at first sign-in. Seats are limited by the company's plan (`402` when none is left).

```bash
curl -X POST "$LEXO_URL/api/v1/users" \
  -H "Authorization: Bearer $LEXO_API_KEY" -H "Content-Type: application/json" \
  -d '{"email": "ana@example.com", "name": "Ana Agent", "role": "agent", "extension": "150", "phoneType": "both", "queues": [{"queueId": "6f1e2d3c-4b5a-4968-8776-5a4b3c2d1e0f", "priority": 1}]}'
```

```javascript
const { user: ana } = await lexo("POST", "/users", {
  email: "ana@example.com", name: "Ana Agent", role: "agent", extension: "150", phoneType: "both",
  queues: [{ queueId: salesQueueId, priority: 1 }],
});
```

```python
ana = lexo("POST", "/users", {"email": "ana@example.com", "name": "Ana Agent", "role": "agent",
                              "extension": "150", "phoneType": "both",
                              "queues": [{"queueId": sales_queue_id, "priority": 1}]})["user"]
```

`PATCH /users/{id}` changes the name, role, extension, status (`active` or `disabled`; new users are `invited` until they set a password), phone type, manual outbound answering machine detection (`amd`) or the queue memberships (`queues` replaces the list). `DELETE /users/{id}` removes the user.

## Phones and SIP credentials

`phoneType` decides where a user's calls ring:

| `phoneType` | Calls ring on |
| --- | --- |
| `webphone` (default) | the LexoConnect app or your embedded webphone in the browser |
| `softphone` | a SIP softphone or desk phone registered with the user's SIP credentials |
| `both` | the browser and the SIP device at the same time |

A SIP device registers with the user's extension as the username, the company's SIP domain and the user's SIP password; the user sees these settings, ready to copy, on their phone settings page in the LexoConnect app. Desk phones and softphones connect over SIP (UDP or TCP port 5060); browsers over WebSocket (`wss://`, port 8443). The platform operator must allow the device's public IP address for SIP.

For **your own WebRTC client** you do not need the user's password: mint a webphone token on your server and exchange it for short-lived SIP credentials (`wsUri`, `sipUri`, `authUser`, `password`, `domain`, `iceServers`). See [Embedding](#build-your-own-phone-ui).

## Numbers and inbound routing

`GET /numbers` lists the company's numbers with their current routing. `PATCH /numbers/{id}` changes where inbound calls go:

| `routeType` | `routeId` / `routeTarget` | Inbound calls go to |
| --- | --- | --- |
| `user` | user id | one user's phone |
| `queue` | queue id | a queue |
| `callflow` | call flow id | an IVR menu |
| `ai_agent` | AI agent id | an AI voice agent |
| `voicemail` | user id | a user's voicemail box |
| `external` | `routeTarget`: E.164 | an outside number (call forwarding) |

Add `scheduleId` plus `afterHoursRouteType` / `afterHoursRouteId` (or `afterHoursTarget`) to route differently outside business hours, and `amd` to detect answering machines on inbound calls.

```bash
curl -X PATCH "$LEXO_URL/api/v1/numbers/5a4b3c2d-1e0f-4a9b-8c7d-6e5f4a3b2c1d" \
  -H "Authorization: Bearer $LEXO_API_KEY" -H "Content-Type: application/json" \
  -d '{"routeType": "queue", "routeId": "6f1e2d3c-4b5a-4968-8776-5a4b3c2d1e0f", "scheduleId": "1d2c3b4a-5968-4776-8594-a3b2c1d0e9f8", "afterHoursRouteType": "voicemail", "afterHoursRouteId": "0b7e5d1c-2a3f-4e6d-8c9b-1a2b3c4d5e6f"}'
```

```javascript
await lexo("PATCH", `/numbers/${numberId}`, {
  routeType: "queue", routeId: salesQueueId,
  scheduleId: officeHoursId, afterHoursRouteType: "voicemail", afterHoursRouteId: ownerUserId,
});
```

```python
lexo("PATCH", f"/numbers/{number_id}", {"routeType": "callflow", "routeId": main_menu_id})
```

**Getting new numbers.** `GET /numbers/available?country=US&areaCode=212&type=local` (or `type=tollfree`) searches numbers that can be added. Numbers are bought and assigned to a company by the platform operator (they also set up the carriers and prices), so send them the number you picked; once assigned, it appears in `GET /numbers` and you route it with `PATCH`.

## Queues

A queue shares calls among its members. `strategy` is one of:

| Strategy | Behaviour |
| --- | --- |
| `ring_all` | ring every available member at once; the first to answer gets the call |
| `sequential` | ring members one at a time in their order |
| `round_robin` | rotate the first member call by call |
| `longest_idle` | ring the member who has waited longest since their last call |

```bash
curl -X POST "$LEXO_URL/api/v1/queues" \
  -H "Authorization: Bearer $LEXO_API_KEY" -H "Content-Type: application/json" \
  -d '{"name": "Sales", "strategy": "ring_all", "ringTimeoutSec": 20, "maxWaitSec": 120, "wrapUpSec": 10, "waitInQueue": true, "fallback": {"type": "voicemail", "userId": "0b7e5d1c-2a3f-4e6d-8c9b-1a2b3c4d5e6f"}}'
```

```javascript
const sales = await lexo("POST", "/queues", { name: "Sales", strategy: "ring_all", ringTimeoutSec: 20, maxWaitSec: 120 });
await lexo("POST", `/queues/${sales.id}/members`, { userId: ana.id, priority: 1, position: 0 });
```

```python
sales = lexo("POST", "/queues", {"name": "Sales", "strategy": "sequential", "ringTimeoutSec": 15})
lexo("POST", f"/queues/{sales['id']}/members", {"userId": ana["id"], "priority": 1, "position": 0})
```

`fallback` decides what happens when nobody answers within `maxWaitSec`: `{"type": "voicemail", "userId": "..."}`, `{"type": "queue", "queueId": "..."}`, `{"type": "external", "target": "+1..."}` or `{"type": "hangup"}`. `PATCH /queues/{id}` changes some fields, `PUT` replaces the queue, `DELETE` removes it (`409` while a number still routes to it). `DELETE /queues/{id}/members/{userId}` removes a member.

## IVR call flows

A call flow is a graph: `nodes` (steps of type `start`, `play`, `menu`, `hours`, `ring_user`, `queue`, `voicemail`, `ai_agent`, `transfer_external` and `hangup`) connected by `edges`. A `menu` node has one exit per key (`0`–`9`, `*`, `#`) plus `timeout`; an `hours` node has `open` and `closed`; `ring_user` has `noanswer`; `queue` has `timeout`. The easiest way to build one is in the LexoConnect call flow designer; `GET /callflows/{id}` then shows the JSON you can copy, change and save back with `PUT /callflows/{id}` or create with `POST /callflows`. The [API reference](/docs/api) shows a complete example graph. Route a number to it with `routeType: "callflow"`.

`GET /reports/ivr-logs` (scope `reports:read`) shows, per call, the path taken through the menu, the keys pressed and the outcome.

## Business hours

```bash
curl -X POST "$LEXO_URL/api/v1/schedules" \
  -H "Authorization: Bearer $LEXO_API_KEY" -H "Content-Type: application/json" \
  -d '{"name": "Office", "timezone": "America/New_York", "weekly": {"mon": [{"start": "09:00", "end": "17:00"}], "tue": [{"start": "09:00", "end": "17:00"}], "wed": [{"start": "09:00", "end": "17:00"}], "thu": [{"start": "09:00", "end": "17:00"}], "fri": [{"start": "09:00", "end": "17:00"}]}}'
```

```javascript
await lexo("PATCH", `/schedules/${officeId}`, { holidays: [{ date: "2026-12-25", name: "Christmas" }] });
```

```python
lexo("PATCH", f"/schedules/{office_id}", {"holidays": [{"date": "2026-12-25", "name": "Christmas"}]})
```

`timezone` must be an IANA time zone name (for example `Europe/London`, `Asia/Karachi`).

## Caller ID on outbound calls

A caller ID profile picks the number customers see:

| `mode` | Picks |
| --- | --- |
| `fixed` | always the same number |
| `local_presence` | a company number with the customer's area code (`match: "area"`) or state (`match: "area_state"`), else the fallback |
| `rotate` | the next number from a list |
| `url` | asks your server (an HTTPS URL) for the number for each call |

`POST /caller-id-profiles/{id}/test` with `{"to": "+12125550123"}` shows which number a call would use. Assign profiles to users, queues or campaigns in the app, or with the `callerIdProfileId` field of a campaign.

## Voicemail

Callers reach a user's voicemail box when the user does not answer or when a number or queue routes there. Each new message sends the `voicemail.created` webhook with a transcript (when enabled) and a signed audio link. `GET /voicemails` lists messages; see [Calls](#recordings-and-voicemail) for audio downloads.

---

# Contact center

_Dialer campaigns and their modes, lead upload, dispositions and callbacks, the wallboard, call scripts, and do-not-call compliance._

## Dialer campaigns

A campaign dials a list of leads and connects answered calls to its agents. Scopes: `campaigns:read` to read, `campaigns:write` to create, change, start and stop campaigns and to upload leads.

| `mode` | How it dials |
| --- | --- |
| `preview` | the agent sees the lead first and clicks to dial |
| `progressive` | one call per available agent, dialed automatically |
| `predictive` | several calls per available agent, adapting the ratio to keep abandoned calls under `maxAbandonPct` |
| `power` | a fixed number of lines per ready agent (`linesPerAgent`, 1–5) |
| `super_power` | a higher fixed number of lines per agent; extra answered calls follow the `noAgent` action |
| `ai` | an AI agent (`aiAgentId`) talks instead of a human; `dialRatio` is the number of concurrent AI calls |
| `voicemail` | leaves a voicemail message per lead (ringless voicemail or voicemail drop); see [AI agents and ringless voicemail](#ai-agents-and-ringless-voicemail) |

### Create and start a campaign

```bash
curl -X POST "$LEXO_URL/api/v1/campaigns" \
  -H "Authorization: Bearer $LEXO_API_KEY" -H "Content-Type: application/json" \
  -d '{"name": "Renewals", "object": "lead", "mode": "progressive", "windowStart": "09:00", "windowEnd": "18:00", "timezone": "America/New_York", "useLeadTimezone": true, "agentIds": ["0b7e5d1c-2a3f-4e6d-8c9b-1a2b3c4d5e6f"], "maxAttempts": 3, "retryMinutes": 60, "amdEnabled": true, "amdAction": "hangup"}'
```

```javascript
const campaign = await lexo("POST", "/campaigns", {
  name: "Renewals", object: "lead", mode: "progressive",
  windowStart: "09:00", windowEnd: "18:00", timezone: "America/New_York", useLeadTimezone: true,
  agentIds: [ana.id], maxAttempts: 3, retryMinutes: 60, amdEnabled: true, amdAction: "hangup",
});
```

```python
campaign = lexo("POST", "/campaigns", {
    "name": "Renewals", "object": "lead", "mode": "progressive",
    "windowStart": "09:00", "windowEnd": "18:00", "timezone": "America/New_York", "useLeadTimezone": True,
    "agentIds": [ana["id"]], "maxAttempts": 3, "retryMinutes": 60, "amdEnabled": True, "amdAction": "hangup",
})
```

Useful fields:

- `object`: the CRM object the leads are (`lead`, `contact`, …).
- `windowStart` / `windowEnd` and `timezone`: the calling hours. With `useLeadTimezone: true` each lead is called only inside the window in **its own** time zone.
- `maxAttempts`, `retryMinutes` and `retryRules` (minutes per result, for example `{"busy": 7, "no_answer": 45, "machine": 240}`); `rotatePhones` tries a lead's next phone number on a retry.
- `amdEnabled` and `amdAction` (`hangup`, `message` with `amdMessage`, or `connect`): what to do when an answering machine picks up.
- `callerIdProfileId`: the caller ID profile (see [Phone system](#caller-id-on-outbound-calls)).
- `noAgent`: what happens when a customer answers and no agent is free: `{"action": "hangup"}`, `{"action": "message", "message": "..."}`, `{"action": "voice_drop", "vmMessageId": "..."}` or `{"action": "callflow", "callflowId": "..."}`.
- `scriptId`: the call script shown to agents (see below); `nationalDnc`: also check national do-not-call registries.

Add leads (next section), then start the campaign:

```bash
curl -X POST "$LEXO_URL/api/v1/campaigns/CAMPAIGN_ID/status" \
  -H "Authorization: Bearer $LEXO_API_KEY" -H "Content-Type: application/json" -d '{"status": "running"}'
```

```javascript
await lexo("POST", `/campaigns/${campaign.id}/status`, { status: "running" }); // or "paused", "completed"
```

```python
lexo("POST", f"/campaigns/{campaign['id']}/status", {"status": "running"})
```

A campaign without leads cannot start (`409`). `PUT /campaigns/{id}` changes the settings; `DELETE /campaigns/{id}` deletes a paused campaign.

## Leads

`POST /campaigns/{id}/leads/upload` adds up to 10 000 leads at a time, as JSON rows or a CSV file. LexoConnect creates or reuses CRM records (deduplicated by phone number) and skips numbers on the do-not-call list and invalid numbers.

```bash
curl -X POST "$LEXO_URL/api/v1/campaigns/CAMPAIGN_ID/leads/upload" \
  -H "Authorization: Bearer $LEXO_API_KEY" -H "Content-Type: application/json" \
  -d '{"rows": [{"name": "Grace Hopper", "phone": "+12125550123", "email": "grace@example.com", "timezone": "America/New_York"}]}'
```

```javascript
const result = await lexo("POST", `/campaigns/${campaign.id}/leads/upload`, {
  rows: customers.map((c) => ({ name: c.fullName, phone: c.mobile, email: c.email })),
});
console.log(result); // { added: 120, duplicates: 3, dnc: 2, invalid: 1 }
```

```python
with open("leads.csv", "rb") as f:
    result = lexo("POST", f"/campaigns/{campaign_id}/leads/upload",
                  files={"file": f}, data={"mapping": '{"name": "Full name", "phone": "Mobile"}'})
print(result)
```

`POST /campaigns/{id}/leads/load` adds existing CRM records of the campaign's object instead (optionally filtered by `ownerId`, `stageId` or a search `q`). `GET /campaigns/{id}/leads` lists leads with their status, attempts and last result. When a lead reaches a final state, LexoConnect sends `campaign.lead.completed`. `GET /reports/lead-uploads` lists every upload with its counts.

## Dispositions and callbacks

Dispositions are the outcomes agents pick at wrap-up ("Sale", "Not interested", "Call back"). `GET /dispositions` lists them; `PUT /dispositions` replaces the list (scope `campaigns:write`). A disposition can schedule a callback; the agent (or your system) then gives a follow-up time.

- Agents save the outcome in the LexoConnect app, or your product saves it with `POST /calls/wrapup` (see [Calls](#wrap-up-after-a-call)).
- A follow-up time creates a task for the agent; `GET /crm/tasks` lists the key user's open tasks, and LexoConnect's callback queue shows every due callback to agents and supervisors.
- For a dialer lead, the disposition decides whether the lead is retried later or completed.
- Every saved outcome sends the `call.dispositioned` webhook with the disposition, note, follow-up, record, lead and campaign, which is the easiest way to copy outcomes into your own CRM.

## Wallboard and reports

- `GET /supervisor/board` (scope `calls:monitor`): live queues, agents and their state, live calls and missed calls today.
- `GET /reports?from=2026-11-01&to=2026-11-30` (scope `reports:read`): calls, agents, queues, dispositions, campaigns and pipelines for a date range.
- `GET /reports/missed-calls` and `GET /reports/call-qa` (AI quality scores of reviewed calls).
- The `agent.state` webhook reports every agent state change (for example `available`, `ringing`, `on_call`, `wrap_up`, `break` and `offline`).

## Call scripts

A call script is text with merge fields shown to the agent beside the lead during a call, for example `Hi {{first_name}}, this is {{agent_first_name}} from {{company_name}}.`

```bash
curl -X POST "$LEXO_URL/api/v1/call-scripts" \
  -H "Authorization: Bearer $LEXO_API_KEY" -H "Content-Type: application/json" \
  -d '{"name": "Opener", "body": "Hi {{first_name}}, this is {{agent_first_name}} from {{company_name}}."}'
```

```javascript
const script = await lexo("POST", "/call-scripts", { name: "Opener", body: "Hi {{first_name}}, this is {{agent_first_name}}." });
await lexo("PUT", `/campaigns/${campaign.id}`, { ...campaignSettings, scriptId: script.id });
```

```python
script = lexo("POST", "/call-scripts", {"name": "Opener", "body": "Hi {{first_name}}, this is {{agent_first_name}}."})
lexo("PUT", f"/queues/{queue_id}/script", {"scriptId": script["id"]})
```

`GET /call-scripts/render?campaignId=...&recordId=...` returns the script with the merge fields filled in, for your own agent screen.

## Do-not-call and consent

| Need | Endpoint |
| --- | --- |
| Company do-not-call list | `GET /dnc`, `POST /dnc` `{"phones": ["+1..."], "reason": "..."}`, `DELETE /dnc/{phone}` |
| National registries (uploaded lists) | `GET /dnc/registries`, `POST /dnc/registries`, `PATCH`/`DELETE /dnc/registries/{id}`, `POST /dnc/registries/{id}/refresh` |
| Check one number | `GET /dnc/check?phone=%2B12125550123` |
| Emergency (E911) addresses | `GET /emergency/addresses`, `PUT /users/{id}/emergency-address` (scope `users:write`) |

Dialer campaigns skip numbers on the company list (and on enabled national registries when `nationalDnc` is on), and only call inside the calling window. Recipients who opt out of messages (for example by replying STOP to an SMS) are refused on that channel with `409 opted_out`. Calling and messaging consent rules (TCPA and similar laws) remain the company's responsibility.

---

# Messaging

_Send and receive SMS, WhatsApp, email and chat messages, work with conversations, attach files and use templates._

## Channels and conversations

LexoConnect's inbox is omnichannel: SMS and MMS, WhatsApp, email, the website chat widget, Facebook Messenger, Instagram, Telegram, Viber and LINE all land in **conversations**. A conversation is the thread with one customer address on one **channel account** (for example one SMS number or one support mailbox).

- `GET /omni/channels` (scope `messages:read`): the channel accounts the company can send from, with their `id`, `kind` and address.
- `GET /omni/conversations`: conversations, filtered by `status` (`open`, `pending`, `closed`), `channel` or a search `q`; paged with `cursor`.
- `GET /omni/conversations/{id}/messages`: the messages of one conversation.

Channel accounts are connected by the company's admins in the app (or by the platform operator for shared accounts); the API sends and reads through them.

## Send a message

`POST /messages` (scope `messages:write`) is the simplest way to send: give `to` and either a `channel` (the company's first enabled account of that kind is used) or a specific `channelAccountId`. LexoConnect reuses the open conversation with that address, or starts one.

```bash
curl -X POST "$LEXO_URL/api/v1/messages" \
  -H "Authorization: Bearer $LEXO_API_KEY" -H "Content-Type: application/json" \
  -d '{"channel": "sms", "to": "+12125550123", "body": "Your appointment is confirmed for 3 pm."}'
```

```javascript
const conv = await lexo("POST", "/messages", { channel: "sms", to: "+12125550123", body: "Your appointment is confirmed for 3 pm." });
console.log(conv.id); // the conversation, with the message sent
```

```python
conv = lexo("POST", "/messages", {"channel": "email", "to": "grace@example.com",
                                  "subject": "Your quote", "body": "Hi Grace, your quote is attached."})
```

Fields:

- `channel`: `sms`, `whatsapp`, `email`, `messenger`, `instagram`, `telegram`, `viber` or `line`;
- `channelAccountId`: send from this exact account instead;
- `subject`: email only;
- `recordId`: link the conversation to a CRM record (otherwise LexoConnect links it by phone or email when it can);
- `template`: a WhatsApp template `{"name": "...", "language": "en", "params": ["..."]}`, required outside WhatsApp's 24-hour customer service window (`GET /omni/channels/{id}/templates` lists the approved templates);
- `attachments`: files uploaded first with `POST /omni/attachments` (see below).

Delivery progress (sent, delivered, read, failed) arrives with the `message.status` webhook. Recipients who opted out on a channel (for example replied STOP to an SMS) are refused with `409 opted_out`; Opt-out keywords (STOP, UNSUBSCRIBE, …), opt-in keywords (START, …) and HELP are answered automatically; the company can change the words and replies in the app.

## Reply in a conversation

```bash
curl -X POST "$LEXO_URL/api/v1/omni/conversations/CONVERSATION_ID/messages" \
  -H "Authorization: Bearer $LEXO_API_KEY" -H "Content-Type: application/json" \
  -d '{"body": "Thanks, we will call you tomorrow."}'
```

```javascript
await lexo("POST", `/omni/conversations/${conversationId}/messages`, { body: "Thanks, we will call you tomorrow." });
await lexo("POST", `/omni/conversations/${conversationId}/read`);
```

```python
lexo("POST", f"/omni/conversations/{conversation_id}/messages", {"body": "Thanks, we will call you tomorrow."})
```

`POST /omni/conversations` starts a new conversation from a given `channelAccountId` (same fields as `POST /messages`).

## Assign, close, snooze and link

`PATCH /omni/conversations/{id}` changes:

- `status`: `open`, `pending` or `closed`;
- `assigneeId`: the user who owns the conversation (`null` to unassign);
- `snoozedUntil`: hide the conversation until a time (RFC 3339); it comes back earlier if the customer replies;
- `recordId`: link it to a CRM record.

```javascript
await lexo("PATCH", `/omni/conversations/${conversationId}`, { assigneeId: ana.id, status: "open" });
```

```python
lexo("PATCH", f"/omni/conversations/{conversation_id}", {"status": "closed"})
```

## Attachments

Upload a file (at most 10 MB) as `multipart/form-data`, then send it:

```bash
curl -X POST "$LEXO_URL/api/v1/omni/attachments" \
  -H "Authorization: Bearer $LEXO_API_KEY" -F "file=@invoice.pdf"
```

```python
with open("invoice.pdf", "rb") as f:
    att = lexo("POST", "/omni/attachments", files={"file": f})
lexo("POST", "/messages", {"channel": "email", "to": "grace@example.com", "subject": "Invoice",
                           "body": "Your invoice is attached.", "attachments": [att]})
```

The answer `{url, name, mime, size}` is what goes into `attachments`. MMS, WhatsApp and email accept attachments; other channels may not.

## Receive messages

Inbound messages are not polled: subscribe a webhook endpoint to `message.received` (and `message.status` for delivery updates). The event carries the conversation, the message, the channel and the sender. See [Webhooks](#webhooks) and the [auto-reply recipe](#receive-an-sms-and-reply-automatically).

## Your own channel (custom API channel)

To connect a messaging network LexoConnect does not support, the company admin can add a **Custom API** channel in the app with the URL of your service. LexoConnect then:

- POSTs every outbound message to your URL as JSON `{conversationId, to, text, attachments}` with the headers `X-NovaComm-Timestamp` (unix seconds) and `X-NovaComm-Signature: sha256=<hex HMAC-SHA256(secret, timestamp + "." + body)>`;
- accepts inbound messages from your service on the webhook URL shown on the channel, signed the same way: `{"from": "...", "name": "...", "text": "...", "externalId": "..."}` for a new message, or `{"type": "status", "externalId": "...", "status": "delivered"}` for a delivery update. The timestamp must be within a few minutes of LexoConnect's clock.

The header names keep the product's former name so that existing integrations keep working.

---

# AI agents and ringless voicemail

_Create AI voice agents that answer and place calls and act in your systems, read AI call history, and send ringless voicemails and voicemail drops._

## AI voice agents

An AI agent is a voice bot that talks to callers in natural language. It can answer a company number, run outbound calls (one at a time or as a dialer campaign), look things up in its knowledge, collect information, update the CRM, send a text or email, transfer to a human, and call **your own API** while it talks. Scopes: `ai:read` and `ai:write`.

### Create an agent

```bash
curl -X POST "$LEXO_URL/api/v1/ai-agents" \
  -H "Authorization: Bearer $LEXO_API_KEY" -H "Content-Type: application/json" \
  -d '{"name": "Front desk", "language": "en", "greeting": "Thanks for calling Northwind Dental, how can I help?", "instructions": "Answer questions about opening hours and book cleanings. Be brief and friendly.", "maxDurationSec": 600, "tools": {"hangup": {"enabled": true}, "transfer": {"enabled": true, "targets": [{"name": "Reception", "description": "A human receptionist", "type": "queue", "value": "6f1e2d3c-4b5a-4968-8776-5a4b3c2d1e0f", "mode": "warm"}]}}}'
```

```javascript
const agent = await lexo("POST", "/ai-agents", {
  name: "Front desk",
  language: "en",
  greeting: "Thanks for calling Northwind Dental, how can I help?",
  instructions: "Answer questions about opening hours and book cleanings. Be brief and friendly.",
  tools: { hangup: { enabled: true } },
});
```

```python
agent = lexo("POST", "/ai-agents", {
    "name": "Front desk", "language": "en",
    "greeting": "Thanks for calling Northwind Dental, how can I help?",
    "instructions": "Answer questions about opening hours and book cleanings.",
    "tools": {"hangup": {"enabled": True}},
})
```

Main fields: `greeting` (first sentence), `instructions` (how the agent behaves), `businessDescription`, `voice` (an id from `GET /ai-agents/voices`), `language`, `maxDurationSec`, `silenceTimeoutSec`, outbound answering machine detection (`amdEnabled`, `amdAction`), the outbound caller ID `callerIdNumberId`, and `tools`:

| Tool | What the agent can do |
| --- | --- |
| `hangup` | end the call politely |
| `transfer` | hand the caller to named `targets` (`extension`, `queue`, `number` or `ai_agent`; `cold` or `warm`) |
| `sendMessage` | send an SMS, WhatsApp or email from a template with `{{variables}}` |
| `crmUpdate` | update listed fields of the caller's CRM record |
| `scheduleCallback` | book a callback task for a user |
| `collect` | collect typed fields (`string`, `number`, `boolean`, `date`, `email`, `phone`), optionally saved to CRM fields |
| `httpActions` | call your API (up to 10 actions; see below) |
| `knowledge` | answer from the agent's knowledge sources |

Add knowledge with `POST /ai-agents/{id}/knowledge` (`{"type": "url", "source": "https://www.example.com"}` to crawl a site, or `type` `text` / `faq`). Every save of an agent is a **version**: `GET /ai-agents/{id}/versions` lists them and `POST /ai-agents/{id}/versions/{version}/publish` rolls back to one.

### Answer inbound calls

Route a number to the agent: `PATCH /numbers/{id}` with `{"routeType": "ai_agent", "routeId": "AGENT_ID"}` (see [Phone system](#numbers-and-inbound-routing)), or use an `ai_agent` step in an IVR call flow. Use a schedule to let the agent answer only after hours.

### Place an outbound AI call

```bash
curl -X POST "$LEXO_URL/api/v1/ai-agents/AGENT_ID/calls" \
  -H "Authorization: Bearer $LEXO_API_KEY" -H "Content-Type: application/json" \
  -d '{"to": "+12125550123", "variables": {"name": "Grace", "appointment": "Tuesday 3 pm"}}'
```

```javascript
const aiCall = await lexo("POST", `/ai-agents/${agent.id}/calls`, { to: "+12125550123", variables: { name: "Grace" } });
```

```python
ai_call = lexo("POST", f"/ai-agents/{agent['id']}/calls", {"to": "+12125550123", "variables": {"name": "Grace"}})
```

`variables` are available to the agent (and to message templates) as `{{name}}`. `recordId` links the call to a CRM record. The prepaid balance, fraud checks, caller ID rules and least-cost routing apply. For many numbers, create a dialer campaign with `mode: "ai"` instead.

### AI call history

- `GET /ai-agents/calls` (filter by `agentId`, `direction`, `outcome`) and `GET /ai-agents/calls/{id}`: transcript, summary, tool log, collected fields, recording and price.
- The `ai.call.ended` webhook delivers the same data when the call ends.
- `GET /reports/call-qa` (scope `reports:read`): AI quality scorecards of reviewed calls.

### Call your API during a call (HTTP actions)

An HTTP action is a function the agent may call while talking, for example `book_appointment` or `check_order_status`. You give it a `name`, a `description` the model reads, your `url`, the `method`, and a JSON Schema of its arguments:

```json
{
  "tools": {
    "httpActions": [
      {
        "name": "book_appointment",
        "description": "Book a cleaning. Use after the caller confirmed a date and time.",
        "url": "https://api.example.com/lexo/book",
        "method": "POST",
        "parameters": {
          "type": "object",
          "properties": {
            "date": { "type": "string", "description": "YYYY-MM-DD" },
            "time": { "type": "string", "description": "HH:MM, 24-hour" },
            "patientName": { "type": "string" }
          },
          "required": ["date", "time", "patientName"]
        }
      }
    ]
  }
}
```

LexoConnect POSTs to your URL (8-second timeout):

```json
{
  "type": "ai.action",
  "action": "book_appointment",
  "timestamp": "2026-11-13T15:04:05Z",
  "tenantId": "…",
  "data": {
    "arguments": { "date": "2026-11-18", "time": "15:00", "patientName": "Grace Hopper" },
    "aiCallId": "…", "agentId": "…", "callUuid": "…",
    "from": "+12125550123", "to": "+14155550100", "direction": "inbound",
    "variables": {}
  }
}
```

Answer with `2xx` and a short text or JSON (up to 4 000 characters) that the agent reads back to the caller, for example `{"booked": true, "confirmation": "Tuesday 18 November at 3 pm"}`. A non-2xx answer tells the agent the action failed. Requests carry the Standard Webhooks headers, signed with the agent's own secret. The secret is not yet available through the API, so also protect the endpoint with a long random token in the URL. A complete example is in [Recipes](#an-ai-agent-that-books-appointments).

## Ringless voicemail and voicemail drops

Leave a recorded message in a customer's voicemail box. Scopes: `rvm:read` and `rvm:write`.

**1. Create a message**: upload a recording, or have the AI voice read a text.

```bash
# Upload a WAV or MP3 recording
curl -X POST "$LEXO_URL/api/v1/voicemail-messages" \
  -H "Authorization: Bearer $LEXO_API_KEY" -F "name=Spring offer" -F "file=@offer.mp3"

# Or generate it from text with the AI voice
curl -X POST "$LEXO_URL/api/v1/voicemail-messages" \
  -H "Authorization: Bearer $LEXO_API_KEY" -H "Content-Type: application/json" \
  -d '{"name": "Cleaning reminder", "text": "Hi, this is Northwind Dental. Your cleaning is due; call us back at 415 555 0100."}'
```

**2. Send one voicemail:**

```bash
curl -X POST "$LEXO_URL/api/v1/rvm/drops" \
  -H "Authorization: Bearer $LEXO_API_KEY" -H "Content-Type: application/json" \
  -d '{"phone": "+14155550142", "messageId": "7c1d2e3f-4a5b-4c6d-8e9f-0a1b2c3d4e5f", "method": "native", "humanAction": "hangup", "consentAttested": true}'
```

```javascript
const drop = await lexo("POST", "/rvm/drops", {
  phone: "+14155550142", messageId: message.id, method: "native", humanAction: "hangup", consentAttested: true,
});
```

```python
drop = lexo("POST", "/rvm/drops", {"phone": "+14155550142", "messageId": message["id"],
                                   "method": "call", "humanAction": "message",
                                   "humanMessageId": live_message["id"], "consentAttested": True})
```

| `method` | How it is delivered |
| --- | --- |
| `native` | ringless, through the company's own carriers (carrier voicemail deposit, or a double dial where the second call lands in voicemail) |
| `call` | a normal call with answering machine detection; the message plays after the beep |
| `vendor` | through a ringless voicemail vendor account (`accountId`) |

`humanAction` says what happens if a person answers: `hangup`, `message` (play `humanMessageId`) or `transfer` (to `queueId`). `consentAttested: true` confirms the recipient gave prior express consent; it is required. Do-not-call and blocked numbers are refused, and so are times outside 08:00–21:00 in the recipient's time zone.

The result arrives with the `rvm.delivered` or `rvm.failed` webhook and on `GET /rvm/drops/{id}`; `GET /rvm/drops` lists drops with counts per status. To send to a list, create a dialer campaign with `mode: "voicemail"`.

> Ringless voicemail is treated as a call by the US FCC (TCPA). Only send it to people who agreed to receive it.

---

# CRM

_Read the company's CRM objects, create and search records, find a caller by phone number, and work with the timeline, notes and tasks._

## Objects and records

The LexoConnect CRM stores **records** of **objects**. Every company has contacts, companies, leads and deals out of the box, and can add its own objects and fields. `GET /crm/objects` (scope `crm:read`) lists the objects with their fields and pipelines, so your integration can discover custom fields instead of hard-coding them.

A record has an `object`, a `title`, its field values in `data`, an `ownerId`, optionally a pipeline `stageId`, and the phone numbers and emails LexoConnect uses to link calls and messages to it automatically.

## Create, read, update and delete

```bash
curl -X POST "$LEXO_URL/api/v1/crm/records" \
  -H "Authorization: Bearer $LEXO_API_KEY" -H "Content-Type: application/json" \
  -d '{"object": "contact", "data": {"name": "Grace Hopper", "phone": "+12125550123", "email": "grace@example.com"}}'
```

```javascript
const grace = await lexo("POST", "/crm/records", {
  object: "contact",
  data: { name: "Grace Hopper", phone: "+12125550123", email: "grace@example.com" },
});
await lexo("PATCH", `/crm/records/${grace.id}`, { data: { email: "grace.hopper@example.com" } });
```

```python
grace = lexo("POST", "/crm/records", {"object": "contact",
                                      "data": {"name": "Grace Hopper", "phone": "+12125550123"}})
lexo("PATCH", f"/crm/records/{grace['id']}", {"data": {"email": "grace.hopper@example.com"}})
```

| Need | Endpoint |
| --- | --- |
| List or search | `GET /crm/records?object=contact&q=grace&ownerId=...&limit=50` |
| Get one | `GET /crm/records/{id}` |
| Update fields (only those sent) | `PATCH /crm/records/{id}` `{"data": {...}, "ownerId": "...", "stageId": "..."}` |
| Delete | `DELETE /crm/records/{id}` |
| Simple contact directory | `GET /contacts`, `POST /contacts`, `PATCH /contacts/{id}`, `DELETE /contacts/{id}` (name, phone, email, company) |

Writes need `crm:write`. Without the supervisor role, the creator of the key sees the records they own or handled calls for.

## Find a caller by phone number

`GET /crm/lookup?phone=+12125550123` returns the records with that number. Use it for a **screen pop** in your product when a `call.ringing` webhook arrives.

```bash
curl "$LEXO_URL/api/v1/crm/lookup?phone=%2B12125550123" -H "Authorization: Bearer $LEXO_API_KEY"
```

```javascript
const { items } = await lexo("GET", `/crm/lookup?phone=${encodeURIComponent("+12125550123")}`);
```

```python
matches = lexo("GET", "/crm/lookup", params={"phone": "+12125550123"})["items"]
```

## Timeline, notes and tasks

Every record has a **timeline**: calls, messages, voicemails, AI calls, notes, tasks and wrap-ups, newest first.

```bash
curl "$LEXO_URL/api/v1/crm/records/RECORD_ID/activities" -H "Authorization: Bearer $LEXO_API_KEY"
```

Add a note or a task (`type` `note` or `task`; tasks take a `dueAt` and are assigned to the key's user):

```bash
curl -X POST "$LEXO_URL/api/v1/crm/records/RECORD_ID/activities" \
  -H "Authorization: Bearer $LEXO_API_KEY" -H "Content-Type: application/json" \
  -d '{"type": "task", "body": "Send the quote", "dueAt": "2026-11-20T15:00:00Z"}'
```

```javascript
await lexo("POST", `/crm/records/${grace.id}/activities`, { type: "note", body: "Asked for a quote for 20 seats." });
const { items: tasks } = await lexo("GET", "/crm/tasks"); // open tasks of the key's user
await lexo("PATCH", `/crm/activities/${tasks[0].id}`, { done: true });
```

```python
lexo("POST", f"/crm/records/{grace['id']}/activities", {"type": "note", "body": "Asked for a quote."})
tasks = lexo("GET", "/crm/tasks")["items"]
```

`PATCH /crm/activities/{id}` edits a note's `body` or a task's `dueAt`, or completes a task with `{"done": true}`; `DELETE` removes it.

## Keep another CRM in sync

To mirror LexoConnect into your own CRM, subscribe to `contact.created` and `contact.updated` (any CRM object; `data.object` names it), plus `call.ended`, `call.dispositioned`, `message.received` and `voicemail.created` to log activity. To push records from your CRM into LexoConnect, create them with `POST /crm/records` after checking `GET /crm/lookup` for an existing match. See the [call logging recipe](#log-every-call-into-your-crm).

## Documents and generated PDFs

Records hold documents: uploaded files and PDFs generated from the company's PDF templates. `GET /crm/records/{id}/documents` lists them, `POST /crm/records/{id}/documents` uploads one (multipart form with `file`, at most 25 MB, and an optional `typeId` from `GET /crm/document-types`), and `GET /crm/documents/{id}/download` returns the file. To produce a contract or letter, call `POST /crm/records/{id}/documents/generate` with a `templateId` from `GET /crm/pdf-templates`: LexoConnect fills the template's `{{merge}}` fields from the record and saves the PDF on it.

```bash
curl -X POST "$LEXO_URL/api/v1/crm/records/$RECORD_ID/documents" \
  -H "Authorization: Bearer $LEXO_API_KEY" \
  -F "file=@statement.pdf" -F "typeId=$TYPE_ID"
```

## Meetings in Google Calendar

When the key's owner has connected Google Calendar in LexoConnect (My calendar), `POST /crm/records/{id}/meetings` books a meeting for the record: LexoConnect checks free/busy first and answers `409` with `error.code` `slot_busy` and `error.fields.nextFree` when the time is taken. `GET /crm/records/{id}/meetings` lists the meetings booked for a record.

```javascript
const res = await lexo("POST", `/crm/records/${recordId}/meetings`, {
  start: "2026-11-20T15:00:00-05:00", durationMinutes: 30, title: "Intro call", attendeeEmail: "grace@example.com",
});
```

---

# Webhooks

_Receive events from LexoConnect in real time, verify their signatures, and handle retries, duplicates and replays._

## How webhooks work

When something happens in a company (a call rings, a message arrives, an agent saves an outcome), LexoConnect sends an HTTP `POST` to every webhook **endpoint** of that company that subscribed to the event. Deliveries are signed per the [Standard Webhooks](https://www.standardwebhooks.com) specification, retried when your server fails, and logged for 30 days.

Manage endpoints in *Admin → Developer → Webhooks*, or with the API (scope `webhooks`):

```bash
curl -X POST "$LEXO_URL/api/v1/webhooks/endpoints" \
  -H "Authorization: Bearer $LEXO_API_KEY" -H "Content-Type: application/json" \
  -d '{"url": "https://api.example.com/lexo/webhooks", "description": "Production CRM sync", "events": ["call.ended", "call.dispositioned", "message.received"]}'
```

```javascript
const { endpoint, secret } = await lexo("POST", "/webhooks/endpoints", {
  url: "https://api.example.com/lexo/webhooks",
  events: ["call.ended", "call.dispositioned", "message.received"],
});
// Store `secret` ("whsec_...") with your server's configuration; read it again any time with
// GET /webhooks/endpoints/{id}/secret.
await lexo("POST", `/webhooks/endpoints/${endpoint.id}/test`); // sends a webhook.test event now
```

```python
created = lexo("POST", "/webhooks/endpoints", {"url": "https://api.example.com/lexo/webhooks",
                                               "events": ["*"]})
endpoint, secret = created["endpoint"], created["secret"]  # secret is "whsec_..."
```

The create answer is `{"endpoint": {...}, "secret": "whsec_..."}`. `events: ["*"]` subscribes to every event, including ones added later. The URL must be public HTTPS. `PATCH /webhooks/endpoints/{id}` changes the URL, events or `active`; `POST .../rotate-secret` issues a new signing secret.

## Events

`GET /webhooks/events` returns the same list at run time.

<!-- gen:events -->
| Event | When it is sent |
| --- | --- |
| `call.ringing` | A call started ringing (inbound or outbound) |
| `call.answered` | A call was answered and connected |
| `call.ended` | A call ended; data is the call record |
| `call.transferred` | A call was transferred (blind, attended, REFER or API) |
| `call.dispositioned` | An agent saved the outcome of a call: disposition, note, follow-up, record, lead and campaign |
| `recording.ready` | A call recording finished and can be downloaded |
| `voicemail.created` | A caller left a voicemail |
| `message.received` | An inbound SMS, WhatsApp, email or chat message arrived |
| `message.status` | The delivery status of an outbound message changed |
| `contact.created` | A CRM record was created (any object; data.object names it) |
| `contact.updated` | A CRM record was updated |
| `campaign.lead.completed` | A dialer campaign lead reached a final state |
| `rvm.delivered` | A ringless voicemail or voicemail drop was left in the mailbox |
| `rvm.failed` | A ringless voicemail or voicemail drop could not be delivered |
| `agent.state` | A contact center agent changed state |
| `ai.call.ended` | An AI agent call ended; data has the transcript, summary, outcome, tool calls and cost |
<!-- /gen -->

`webhook.test` is sent by the **Send test event** button and `POST /webhooks/endpoints/{id}/test`. New event types may be added at any time; ignore types you do not handle.

## The payload

Every delivery has the same envelope:

```json
{
  "type": "message.received",
  "timestamp": "2026-11-13T10:06:00Z",
  "tenantId": "9c8b7a6d-5e4f-4a3b-2c1d-0e9f8a7b6c5d",
  "data": {
    "conversationId": "1f2e3d4c-5b6a-4798-8a9b-0c1d2e3f4a5b",
    "channel": "sms",
    "channelAccountId": "2a3b4c5d-6e7f-4809-1a2b-3c4d5e6f7a8b",
    "from": "+12125550123",
    "message": { "id": "3b4c5d6e-7f80-4912-a3b4-c5d6e7f8a9b0", "direction": "inbound", "body": "Can you call me back?", "status": "delivered", "createdAt": "2026-11-13T10:06:00Z" }
  }
}
```

A few other `data` shapes:

```json
{ "type": "call.ringing", "data": { "callUuid": "3f0c1d8e-…", "direction": "inbound", "from": "+12125550123", "to": "+14155550100", "userId": "0b7e5d1c-…", "at": "2026-11-13T10:00:01Z" } }
```

```json
{ "type": "recording.ready", "data": { "callId": "8a7c2b4e-…", "callUuid": "3f0c1d8e-…", "kind": "full", "durationSec": 186, "url": "/api/v1/calls/8a7c2b4e-…/recording", "signedUrl": "https://telco.lexogenix.com/api/v1/calls/8a7c2b4e-…/recording?sig=…" } }
```

```json
{ "type": "campaign.lead.completed", "data": { "leadId": "5e6f7a8b-…", "campaignId": "6f7a8b9c-…", "recordId": "5d1f8e2a-…", "phone": "+12125550123", "status": "completed", "result": "Interested", "dispositionId": "4b5c6d7e-…", "attempts": 2 } }
```

`call.ended` carries the full call record (the same fields as `GET /calls/{id}`) plus `callUuid`. The [API reference](/docs/api#webhooks) has an example for every event.

## Verify the signature

Each delivery carries three headers:

| Header | Value |
| --- | --- |
| `webhook-id` | a unique message id (`msg_…`), the same on every retry of this message |
| `webhook-timestamp` | unix seconds when this attempt was signed |
| `webhook-signature` | `v1,<base64 HMAC-SHA256>`, possibly several separated by spaces (during a secret rotation) |

The signed content is `webhook-id + "." + webhook-timestamp + "." + raw body`, and the HMAC key is the **base64-decoded** part of the secret after `whsec_`. Always verify against the **raw** request body (before any JSON parsing), compare in constant time, and reject timestamps more than 5 minutes from your clock.

```javascript
// Node.js / Express
import crypto from "node:crypto";
import express from "express";

const SECRET = process.env.LEXO_WEBHOOK_SECRET; // "whsec_..."

function verify(headers, rawBody) {
  const id = headers["webhook-id"], ts = headers["webhook-timestamp"], sigs = headers["webhook-signature"];
  if (!id || !ts || !sigs) return false;
  if (Math.abs(Date.now() / 1000 - Number(ts)) > 300) return false;
  const key = Buffer.from(SECRET.slice("whsec_".length), "base64");
  const expected = "v1," + crypto.createHmac("sha256", key).update(`${id}.${ts}.${rawBody}`).digest("base64");
  return sigs.split(" ").some((s) => s.length === expected.length && crypto.timingSafeEqual(Buffer.from(s), Buffer.from(expected)));
}

const app = express();
app.post("/lexo/webhooks", express.raw({ type: "application/json" }), (req, res) => {
  if (!verify(req.headers, req.body.toString("utf8"))) return res.sendStatus(401);
  const event = JSON.parse(req.body);
  res.sendStatus(204); // answer fast, then work
  handle(event).catch(console.error);
});
app.listen(3000);
```

```python
# Python / Flask
import base64, hashlib, hmac, json, os, time
from flask import Flask, request, abort

SECRET = os.environ["LEXO_WEBHOOK_SECRET"]  # "whsec_..."
app = Flask(__name__)

def verify(headers, raw: bytes) -> bool:
    msg_id, ts, sigs = headers.get("webhook-id"), headers.get("webhook-timestamp"), headers.get("webhook-signature")
    if not (msg_id and ts and sigs) or abs(time.time() - int(ts)) > 300:
        return False
    key = base64.b64decode(SECRET.removeprefix("whsec_"))
    digest = hmac.new(key, f"{msg_id}.{ts}.".encode() + raw, hashlib.sha256).digest()
    expected = "v1," + base64.b64encode(digest).decode()
    return any(hmac.compare_digest(s, expected) for s in sigs.split(" "))

@app.post("/lexo/webhooks")
def webhook():
    if not verify(request.headers, request.get_data()):
        abort(401)
    event = json.loads(request.get_data())
    # queue the event for processing, then answer quickly
    return "", 204
```

```php
<?php
// PHP
$secret = getenv('LEXO_WEBHOOK_SECRET'); // "whsec_..."
$raw = file_get_contents('php://input');
$id = $_SERVER['HTTP_WEBHOOK_ID'] ?? '';
$ts = $_SERVER['HTTP_WEBHOOK_TIMESTAMP'] ?? '';
$sigs = $_SERVER['HTTP_WEBHOOK_SIGNATURE'] ?? '';

$key = base64_decode(substr($secret, strlen('whsec_')));
$expected = 'v1,' . base64_encode(hash_hmac('sha256', "$id.$ts.$raw", $key, true));
$ok = $id && $ts && abs(time() - (int)$ts) <= 300;
$ok = $ok && count(array_filter(explode(' ', $sigs), fn($s) => hash_equals($expected, $s))) > 0;
if (!$ok) { http_response_code(401); exit; }

$event = json_decode($raw, true);
http_response_code(204);
// handle $event['type'] / $event['data']
```

```go
// Go
package main

import (
	"crypto/hmac"
	"crypto/sha256"
	"crypto/subtle"
	"encoding/base64"
	"io"
	"math"
	"net/http"
	"os"
	"strconv"
	"strings"
	"time"
)

func verify(secret string, h http.Header, body []byte) bool {
	id, ts, sigs := h.Get("webhook-id"), h.Get("webhook-timestamp"), h.Get("webhook-signature")
	t, err := strconv.ParseInt(ts, 10, 64)
	if id == "" || err != nil || math.Abs(float64(time.Now().Unix()-t)) > 300 {
		return false
	}
	key, err := base64.StdEncoding.DecodeString(strings.TrimPrefix(secret, "whsec_"))
	if err != nil {
		return false
	}
	m := hmac.New(sha256.New, key)
	m.Write([]byte(id + "." + ts + "."))
	m.Write(body)
	want := "v1," + base64.StdEncoding.EncodeToString(m.Sum(nil))
	for _, s := range strings.Fields(sigs) {
		if subtle.ConstantTimeCompare([]byte(s), []byte(want)) == 1 {
			return true
		}
	}
	return false
}

func main() {
	http.HandleFunc("/lexo/webhooks", func(w http.ResponseWriter, r *http.Request) {
		body, _ := io.ReadAll(io.LimitReader(r.Body, 1<<20))
		if !verify(os.Getenv("LEXO_WEBHOOK_SECRET"), r.Header, body) {
			http.Error(w, "bad signature", http.StatusUnauthorized)
			return
		}
		w.WriteHeader(http.StatusNoContent)
		// handle the event asynchronously
	})
	_ = http.ListenAndServe(":3000", nil)
}
```

Any Standard Webhooks library also works (for example `standardwebhooks` for Node.js and Python, or `svix` libraries): pass it the `whsec_…` secret.

## Retries, duplicates and order

- Answer with any **2xx** within **15 seconds**. Do the real work after answering (put the event on a queue).
- Any other answer, a timeout or a connection error is retried **9 times** with exponential back-off: after 10 s, 30 s, 90 s, 4.5 min, 13.5 min, 40.5 min, about 2 h, 6 h and 12 h.
- A message can arrive more than once. **Deduplicate on `webhook-id`**; it stays the same across retries and replays.
- Events are not guaranteed to arrive in order (a retried `call.answered` can come after `call.ended`). Use the `timestamp` and the object's own state when order matters.
- LexoConnect sends deliveries with the `User-Agent: LexoConnect-Webhooks/1.0` header.

## Delivery log and replay

`GET /webhooks/deliveries` lists deliveries of the last 30 days (filter by `endpointId`, `status`, `event`), and `GET /webhooks/deliveries/{id}` shows the payload, every attempt, the status code and the start of your server's answer. After fixing a bug on your side, send a failed message again with `POST /webhooks/deliveries/{id}/replay`: same `webhook-id`, new timestamp and signature. The same log is in the app under *Admin → Developer → Webhooks*.

---

# Embedding

_Put the LexoConnect webphone inside your own product with an iframe or the JavaScript SDK, add click-to-call buttons, build your own phone UI on LexoConnect's WebRTC service, and embed the chat widget._

## How embedding is secured

The browser never sees an API key. Instead:

1. Your **server** asks LexoConnect for a short-lived **webphone token** for one user: `POST /webphone/tokens` with an API key that has the `webphone` scope.
2. Your page gives the token to the LexoConnect iframe or SDK, which exchanges it for that user's phone session.
3. The token works **once** and expires after 5 minutes by default (30 seconds to 1 hour, `ttlSec`).

A company admin lists the websites that may embed the phone in *Admin → Developer → Webphone embed* (allowed origins, for example `https://crm.example.com`). Other origins are refused.

```bash
curl -X POST "$LEXO_URL/api/v1/webphone/tokens" \
  -H "Authorization: Bearer $LEXO_API_KEY" -H "Content-Type: application/json" \
  -d '{"userId": "0b7e5d1c-2a3f-4e6d-8c9b-1a2b3c4d5e6f", "ttlSec": 300}'
```

```javascript
// Your server (Node.js / Express): give the signed-in CRM user a LexoConnect phone token.
app.get("/api/lexo-phone-token", requireLogin, async (req, res) => {
  const lexoUserId = req.user.lexoUserId; // your mapping from your user to the LexoConnect user
  const t = await lexo("POST", "/webphone/tokens", { userId: lexoUserId, ttlSec: 300 });
  res.json({ token: t.token, embedUrl: t.embedUrl });
});
```

```python
# Your server (Flask)
@app.get("/api/lexo-phone-token")
def phone_token():
    t = lexo("POST", "/webphone/tokens", {"userId": current_user.lexo_user_id, "ttlSec": 300})
    return {"token": t["token"], "embedUrl": t["embedUrl"]}
```

The answer has `token` (`ncwp_…`), `expiresAt`, a ready `embedUrl` and the `sdkUrl`.

## Option 1: the iframe

```html
<iframe id="lexo-phone" src="https://telco.lexogenix.com/embed/phone?token=TOKEN"
        allow="microphone; autoplay" style="width:360px;height:560px;border:0"></iframe>
<script>
  const LEXO = "https://telco.lexogenix.com";
  const phone = document.getElementById("lexo-phone").contentWindow;

  window.addEventListener("message", (e) => {
    if (e.origin !== LEXO || e.data?.source !== "novawebphone") return;
    // e.data.type: ready | registered | incoming | connected | ended | error
    console.log(e.data.type, e.data);
  });

  // Commands: dial, answer, hangup
  function dial(number) { phone.postMessage({ source: "novawebphone", type: "dial", number }, LEXO); }
  function answer() { phone.postMessage({ source: "novawebphone", type: "answer" }, LEXO); }
  function hangup() { phone.postMessage({ source: "novawebphone", type: "hangup" }, LEXO); }
</script>
```

The iframe shows a complete phone with a dial pad, the incoming call screen and the in-call controls. Messages use `source: "novawebphone"`; the name stays the same for compatibility.

## Option 2: the JavaScript SDK

The SDK gives you the same phone as an object with events, so you can draw your own buttons:

```html
<div id="phone"></div>
<button id="call">Call Grace</button>
<script src="https://telco.lexogenix.com/sdk/webphone.js"></script>
<script>
  async function start() {
    const { token } = await (await fetch("/api/lexo-phone-token")).json(); // your server, see above
    const phone = NovaWebphone.init({ token, container: "#phone" });

    phone.on("incoming", ({ call }) => showScreenPop(call.remoteNumber));
    phone.on("connected", ({ call }) => console.log("Talking to", call.remoteNumber));
    phone.on("ended", ({ call }) => console.log("Ended:", call.endReason));
    phone.on("error", ({ message }) => console.error(message));

    document.querySelector("#call").onclick = () => phone.dial("+12125550123");
  }
  start();
</script>
```

Methods: `dial(number)`, `answer(callId?)`, `hangup(callId?)`. Events (each listener gets one object): `ready` `{user}`, `registered` `{user}`, `registration` `{state}`, `incoming` / `connected` / `ended` `{call}` (with `id`, `remoteNumber`, `answeredAt`, `endReason`, …), `calls` `{calls}` and `error` `{message}`. The global keeps its original name `NovaWebphone` so that existing pages keep working. Ask for a new token when the page loads again; each token works once.

## Click-to-call buttons

There are two ways to put "Call" buttons next to phone numbers in your product:

| Approach | When to use it |
| --- | --- |
| **In the page**: `dial(number)` on the embedded iframe or SDK phone | The user works in your web app with the LexoConnect phone embedded. The call starts on their browser phone at once. |
| **From your server**: `POST /calls/originate` | The user's phone is elsewhere (a desk phone, the LexoConnect app, a softphone). LexoConnect rings that phone first, then dials the customer. See [Calls](#place-a-call-click-to-call). |

## Build your own phone UI

For full control, write your own WebRTC client and use LexoConnect's SIP over WebSocket service. Exchange a webphone token for SIP credentials (no API key; the token is the credential and works once):

```bash
curl -X POST "$LEXO_URL/api/v1/webphone/session" \
  -H "Content-Type: application/json" -H "Origin: https://crm.example.com" \
  -d '{"token": "ncwp_..."}'
```

The answer:

```json
{
  "sip": {
    "wsUri": "wss://telco.lexogenix.com:8443",
    "sipUri": "sip:150@acme.sip.example.com",
    "authUser": "150",
    "password": "…",
    "domain": "acme.sip.example.com",
    "displayName": "Ana Agent",
    "iceServers": [{ "urls": "stun:…" }]
  },
  "user": { "id": "…", "name": "Ana Agent", "extension": "150" },
  "tenant": { "id": "…", "name": "Acme Inc" },
  "allowedOrigins": ["https://crm.example.com"],
  "expiresAt": "2026-11-13T18:00:00Z"
}
```

Register with any SIP-over-WebSocket library, for example [SIP.js](https://sipjs.com):

```javascript
import { UserAgent, Registerer, Inviter } from "sip.js";

const { sip } = await (await fetch(`${LEXO}/api/v1/webphone/session`, {
  method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ token }),
})).json();

const ua = new UserAgent({
  uri: UserAgent.makeURI(sip.sipUri),
  transportOptions: { server: sip.wsUri },
  authorizationUsername: sip.authUser,
  authorizationPassword: sip.password,
  displayName: sip.displayName,
  sessionDescriptionHandlerFactoryOptions: { peerConnectionConfiguration: { iceServers: sip.iceServers } },
});
await ua.start();
await new Registerer(ua).register();

// Outbound call: dial the number at the company's SIP domain.
const target = UserAgent.makeURI(`sip:+12125550123@${sip.domain}`);
await new Inviter(ua, target).invite();
```

All company rules apply to calls from your client (caller ID, routing, recording, billing). Calls of the user ring your client like any other phone of that user, and appear in call history and webhooks as usual. Before the credentials expire (`expiresAt`), mint a new token and register again.

## Website chat widget

When the company has connected a **Web chat** channel, paste its snippet on the website. Chats arrive in LexoConnect's inbox as conversations (see [Messaging](#messaging)) and send the `message.received` webhook.

```html
<script src="https://telco.lexogenix.com/widget.js" data-key="CHANNEL_KEY" async></script>
```

The admin copies the snippet, with the right `data-key`, from the Web chat channel's settings in LexoConnect.

## Single sign-on

LexoConnect does not offer SAML or OpenID Connect sign-in for embedded use. Map your users to LexoConnect users once (by email or extension, from `GET /users`) and mint webphone tokens for them on your server; your own login stays the only login your users see.

---

# Recipes

_Complete, end-to-end examples you can copy: click-to-call, call logging, SMS auto-reply, dialer campaigns, your own softphone and an AI agent that books appointments._

Each recipe uses the `lexo()` helper and the environment variables from [Getting started](#base-url-and-authentication), and the signature check from [Webhooks](#verify-the-signature).

## A click-to-call button in your CRM

**Goal:** a "Call" button next to every phone number in your CRM. The agent's LexoConnect phone rings, and when they pick up LexoConnect dials the customer.

**You need:** an API key with `calls:write` and `users:read`; each CRM user mapped to a LexoConnect user.

1. Once, map your users to LexoConnect users by email:

```javascript
const { items } = await lexo("GET", "/users");
const lexoUserByEmail = new Map(items.map((u) => [u.email.toLowerCase(), u.id]));
```

```python
users = lexo("GET", "/users")["items"]
lexo_user_by_email = {u["email"].lower(): u["id"] for u in users}
```

2. Add a server endpoint your button calls:

```javascript
// Express. The browser sends { to } only; the server decides whose phone rings.
app.post("/api/click-to-call", requireLogin, express.json(), async (req, res) => {
  const userId = lexoUserByEmail.get(req.user.email.toLowerCase());
  if (!userId) return res.status(400).json({ error: "No LexoConnect phone for this user" });
  try {
    const call = await lexo("POST", "/calls/originate", { userId, to: req.body.to });
    res.json({ callUuid: call.callUuid });
  } catch (err) {
    res.status(502).json({ error: String(err.message) });
  }
});
```

```python
@app.post("/api/click-to-call")
@login_required
def click_to_call():
    user_id = lexo_user_by_email.get(current_user.email.lower())
    if not user_id:
        return {"error": "No LexoConnect phone for this user"}, 400
    call = lexo("POST", "/calls/originate", {"userId": user_id, "to": request.json["to"]})
    return {"callUuid": call["callUuid"]}
```

3. In the page: `fetch("/api/click-to-call", {method: "POST", headers: {"Content-Type": "application/json"}, body: JSON.stringify({to: "+12125550123"})})`.

**Variant:** if the LexoConnect phone is embedded in your page (see [Embedding](#embedding)), call `phone.dial(number)` directly instead.

## Log every call into your CRM

**Goal:** every call, its recording and the agent's outcome appear on the right customer in your CRM, within seconds.

**You need:** a webhook endpoint subscribed to `call.ended`, `recording.ready` and `call.dispositioned`; an API key with `calls:read` if you download recordings.

```javascript
const seen = new Set(); // use a database table with a unique index in production

app.post("/lexo/webhooks", express.raw({ type: "application/json" }), async (req, res) => {
  if (!verify(req.headers, req.body.toString("utf8"))) return res.sendStatus(401);
  const id = req.headers["webhook-id"];
  res.sendStatus(204);
  if (seen.has(id)) return; // retries and replays reuse the same webhook-id
  seen.add(id);

  const { type, data } = JSON.parse(req.body);
  const customer = data.direction === "inbound" ? data.from : data.to;
  switch (type) {
    case "call.ended":
      await crm.upsertCallActivity({
        externalId: data.id, phone: customer, direction: data.direction, status: data.status,
        startedAt: data.startedAt, durationSec: data.durationSec, agentId: data.userId,
      });
      break;
    case "recording.ready":
      await crm.attachRecording({ externalId: data.callId, url: data.signedUrl }); // valid 24 hours: copy the file if you keep it
      break;
    case "call.dispositioned":
      // data: callId, recordId, number, direction, agentId, dispositionId, disposition (label), outcome, note,
      //       followUpAt, campaignId, campaignLeadId, at
      await crm.setOutcome({ phone: data.number, disposition: data.disposition, note: data.note, followUpAt: data.followUpAt });
      break;
  }
});
```

```python
@app.post("/lexo/webhooks")
def lexo_webhooks():
    raw = request.get_data()
    if not verify(request.headers, raw):
        abort(401)
    if already_processed(request.headers["webhook-id"]):  # unique index on webhook-id
        return "", 204
    event = json.loads(raw)
    queue.enqueue(process_lexo_event, event)               # do the work outside the request
    return "", 204

def process_lexo_event(event):
    data = event["data"]
    if event["type"] == "call.ended":
        crm.upsert_call(external_id=data["id"], status=data["status"], duration=data["durationSec"],
                        phone=data["from"] if data["direction"] == "inbound" else data["to"])
    elif event["type"] == "recording.ready":
        audio = requests.get(data["signedUrl"], timeout=120).content
        crm.attach_recording(data["callId"], audio)
```

Field names of `call.dispositioned` and the other events are listed with examples in the [API reference](/docs/api#webhooks). To fill gaps after an outage, page through `GET /calls` for the missing time range.

## Receive an SMS and reply automatically

**Goal:** answer "hours" questions by SMS automatically and leave everything else for the team.

**You need:** a webhook subscribed to `message.received`; an API key with `messages:write`.

```javascript
app.post("/lexo/webhooks", express.raw({ type: "application/json" }), async (req, res) => {
  if (!verify(req.headers, req.body.toString("utf8"))) return res.sendStatus(401);
  res.sendStatus(204);
  const { type, data } = JSON.parse(req.body);
  if (type !== "message.received" || data.channel !== "sms") return;
  const text = (data.message.body || "").toLowerCase();
  if (text.includes("hours") || text.includes("open")) {
    await lexo("POST", `/omni/conversations/${data.conversationId}/messages`, {
      body: "We are open Monday to Friday, 9 am to 5 pm. Reply with your question and a person will answer.",
    });
  }
});
```

```python
def process_lexo_event(event):
    if event["type"] != "message.received" or event["data"]["channel"] != "sms":
        return
    data = event["data"]
    if "hours" in (data["message"].get("body") or "").lower():
        lexo("POST", f"/omni/conversations/{data['conversationId']}/messages",
             {"body": "We are open Monday to Friday, 9 am to 5 pm."})
```

Your own replies come back as outbound messages, not as `message.received`, so the bot cannot loop. Opt-out words (STOP, …) are handled by LexoConnect before your webhook sees them.

## Start a dialer campaign from your system

**Goal:** your system decides who to call today, LexoConnect dials them with its agents, and the outcomes flow back.

**You need:** an API key with `campaigns:write`, `campaigns:read` and `users:read`; a webhook subscribed to `campaign.lead.completed` and `call.dispositioned`.

```javascript
const { items: users } = await lexo("GET", "/users");
const agents = users.filter((u) => u.role === "agent" && u.status === "active").map((u) => u.id);

const campaign = await lexo("POST", "/campaigns", {
  name: `Renewals ${new Date().toISOString().slice(0, 10)}`,
  object: "lead", mode: "progressive",
  windowStart: "09:00", windowEnd: "18:00", timezone: "America/New_York", useLeadTimezone: true,
  agentIds: agents, maxAttempts: 3, retryMinutes: 90, amdEnabled: true, amdAction: "hangup",
});

const leads = await myDb.customersDueForRenewal(); // [{ name, phone, email }]
for (let i = 0; i < leads.length; i += 5000) {
  const r = await lexo("POST", `/campaigns/${campaign.id}/leads/upload`, { rows: leads.slice(i, i + 5000) });
  console.log(r); // { added, duplicates, dnc, invalid }
}
await lexo("POST", `/campaigns/${campaign.id}/status`, { status: "running" });
```

```python
users = lexo("GET", "/users")["items"]
agents = [u["id"] for u in users if u["role"] == "agent" and u["status"] == "active"]
campaign = lexo("POST", "/campaigns", {
    "name": "Renewals", "object": "lead", "mode": "progressive",
    "windowStart": "09:00", "windowEnd": "18:00", "timezone": "America/New_York", "useLeadTimezone": True,
    "agentIds": agents, "maxAttempts": 3, "retryMinutes": 90,
})
rows = [{"name": c.name, "phone": c.phone, "email": c.email} for c in customers_due()]
for i in range(0, len(rows), 5000):
    print(lexo("POST", f"/campaigns/{campaign['id']}/leads/upload", {"rows": rows[i:i + 5000]}))
lexo("POST", f"/campaigns/{campaign['id']}/status", {"status": "running"})
```

When each lead is finished, `campaign.lead.completed` tells you its final `status`, `result`, `dispositionId` and `attempts`; `call.dispositioned` carries the agent's note and follow-up. Pause the campaign at the end of the day with `{"status": "paused"}`, or mark it `completed`.

## Build your own softphone UI

**Goal:** a phone that looks like your product, inside your product.

1. Your server mints a webphone token for the signed-in user (`POST /webphone/tokens`, scope `webphone`).
2. The browser exchanges it for SIP credentials (`POST /webphone/session`) and registers to LexoConnect over WebSocket with SIP.js (or any SIP-over-WebSocket library).
3. Draw your own dial pad, incoming-call banner and call controls on top of the SIP.js session events.
4. Use the REST API for what is not in SIP: `POST /calls/current/transfer`, `.../recording`, `.../park`, `GET /crm/lookup` for screen pops, and `POST /calls/wrapup` for outcomes.

The complete client code is in [Embedding → Build your own phone UI](#build-your-own-phone-ui). If you only need a working phone, the ready-made iframe or SDK takes minutes instead.

## An AI agent that books appointments

**Goal:** an AI receptionist answers your number around the clock, checks free slots in your booking system and books the appointment.

**You need:** an API key with `ai:write` and `numbers:write`; an HTTPS endpoint in your booking system.

1. Create the agent with two HTTP actions and a human fallback:

```javascript
const agent = await lexo("POST", "/ai-agents", {
  name: "Booking assistant",
  language: "en",
  greeting: "Hi, thanks for calling Northwind Dental. Would you like to book an appointment?",
  instructions:
    "Help callers book a cleaning. Ask for their name and preferred day. Call find_slots, offer at most three " +
    "slots, then call book_appointment with the slot the caller chose. Confirm the booking and say goodbye.",
  maxDurationSec: 600,
  tools: {
    hangup: { enabled: true },
    transfer: { enabled: true, targets: [{ name: "Reception", description: "A person, for anything else", type: "queue", value: receptionQueueId, mode: "warm" }] },
    httpActions: [
      {
        name: "find_slots",
        description: "Find free appointment slots on a day.",
        url: "https://booking.example.com/lexo/ACTION_TOKEN/find-slots",
        method: "POST",
        parameters: { type: "object", properties: { date: { type: "string", description: "YYYY-MM-DD" } }, required: ["date"] },
      },
      {
        name: "book_appointment",
        description: "Book a slot returned by find_slots.",
        url: "https://booking.example.com/lexo/ACTION_TOKEN/book",
        method: "POST",
        parameters: {
          type: "object",
          properties: { slotId: { type: "string" }, patientName: { type: "string" } },
          required: ["slotId", "patientName"],
        },
      },
    ],
  },
});
```

2. Answer the actions in your booking system. The agent reads your answer back to the caller:

```javascript
app.post("/lexo/:token/find-slots", express.json(), async (req, res) => {
  if (req.params.token !== process.env.ACTION_TOKEN) return res.sendStatus(404);
  const { date } = req.body.data.arguments;
  const slots = await booking.freeSlots(date); // [{ id, label: "Tuesday 18 November, 3 pm" }]
  res.json({ slots: slots.slice(0, 3) });
});

app.post("/lexo/:token/book", express.json(), async (req, res) => {
  if (req.params.token !== process.env.ACTION_TOKEN) return res.sendStatus(404);
  const { slotId, patientName } = req.body.data.arguments;
  const caller = req.body.data.from;
  const ok = await booking.book({ slotId, patientName, phone: caller });
  res.json(ok ? { booked: true, message: "The appointment is booked." } : { booked: false, message: "That slot was just taken." });
});
```

```python
@app.post("/lexo/<token>/book")
def book(token):
    if token != os.environ["ACTION_TOKEN"]:
        abort(404)
    args = request.json["data"]["arguments"]
    ok = booking.book(slot_id=args["slotId"], patient=args["patientName"], phone=request.json["data"]["from"])
    return {"booked": ok, "message": "The appointment is booked." if ok else "That slot was just taken."}
```

3. Route the number to the agent (only after hours, if you prefer, with a schedule):

```bash
curl -X PATCH "$LEXO_URL/api/v1/numbers/NUMBER_ID" \
  -H "Authorization: Bearer $LEXO_API_KEY" -H "Content-Type: application/json" \
  -d '{"routeType": "ai_agent", "routeId": "AGENT_ID"}'
```

4. Subscribe to `ai.call.ended` to store the transcript, summary and outcome of every AI call.

Answer each action within 8 seconds; keep the answer short, because the agent reads it to the caller.
