# Your own CRM

> For a CRM you built yourself. Start AI calls from it and get the outcome, the note and the transcript back, with working Node and Python code.

This is for a team that built its own CRM and wants it to start CallView's AI calls and get the results back. It's the three moves in [How every recipe works](https://developers.callview.ai/recipes/), with the code written out:

1. Your CRM sends each new lead to `POST /leads`, and the AI calls it within seconds.
2. When someone in the CRM wants a lead called again, the CRM sends `POST /calls`.
3. When a call is over, CallView sends `call.completed` to a small receiver in your CRM. It checks the signature, writes the outcome back to the record and, if you want it, fetches the transcript.

The code below is complete. It needs Node 20 or later with no packages, or Python 3.8 or later with `requests` (and Flask for the receiver).

## 1. Make a key

In CallView, open **Settings > API** and click **+ Create API key**, then fill it in like this:

| Setting | What to pick |
| --- | --- |
| Test or Live | Test, while you build. A test key doesn't dial anyone and costs nothing. |
| What it can do | The **CRM speed to lead** set: Leads (read and write), Start calls, Calls (read) and Events (read). Then tick Webhooks (read and write), so the CRM can set up its own webhook endpoint (step 5), and Calls: write if the CRM will call leads again (step 4). |
| Recordings & transcripts | Tick it only if your CRM stores transcripts or recordings. Outcomes and notes don't need it. |
| Which campaigns | Only the ones the CRM should fill. The key can't see or add leads anywhere else. |
| Allowed IP addresses | Optional. Your CRM server's outgoing addresses, if they're fixed. Requests from other addresses are refused. |
| Calls per day, Daily spend cap | Optional. Limits for this key alone, on top of your organization's spend cap. Set them a little above your busiest real day, so a CRM bug that sends the same leads over and over can't run up a bill. See [Money guards](https://developers.callview.ai/guides/money-guards/#limits-for-one-key). |

The secret is shown once. Keep it on the CRM's server, out of web pages, and pass it in through the environment:

```bash
export CALLVIEW_KEY_ID=ck_test_paste_yours_here
export CALLVIEW_SECRET=cs_test_paste_yours_here
export CALLVIEW_CAMPAIGN_ID=paste_the_campaign_id_here
```

`GET /campaigns` lists the campaign IDs the key can use. [Keys and authentication](https://developers.callview.ai/guides/authentication/#the-permissions) explains each permission.

## 2. Talk to CallView

One small module handles the CRM's side: it adds leads, calls them again, and fetches transcripts.

Each write carries an `Idempotency-Key`. We keep the first answer to a key for 24 hours, errors such as `403` and `409` included (`5xx` and `429` answers aren't kept). The same key again gets that kept answer back, and the same key with a different body gets `409 idempotency_mismatch`. So the module builds the key from three things: the record's ID, a send number, and a short hash of the data it sends. A retry of the same send is answered from the kept reply instead of making a second lead. A changed record gets a new key. When someone sends a record again on purpose (after fixing the key, say), the CRM passes the next send number. See [Safe retries](https://developers.callview.ai/guides/idempotency/).

The module retries network errors, `5xx` answers and short `429` waits, with the same key each time. It doesn't wait out a long `Retry-After` (for `429 call_limit_reached` that can be hours). It hands the answer back with `retryAfter`, in seconds, so the CRM can try again then. See [Rate limits](https://developers.callview.ai/guides/rate-limits/).

```js title="callview.mjs"
// callview.mjs: your CRM's side of CallView (Node 20 or later, no packages).
// The key comes from the environment: CALLVIEW_KEY_ID and CALLVIEW_SECRET.
import crypto from 'node:crypto';

const HOST = 'https://v2-api.callview.ai';
const BASE = `${HOST}/api/v1/external`;
const AUTH = `Basic ${Buffer.from(`${process.env.CALLVIEW_KEY_ID}:${process.env.CALLVIEW_SECRET}`).toString('base64')}`;

// Answers worth waiting for and sending again, with the same Idempotency-Key.
const RETRY_CODES = new Set(['rate_limited', 'too_many_concurrent_requests', 'lead_rate_limited', 'idempotency_in_progress', 'test_flows_busy']);
const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));

// One request, tried up to 5 times. Answers { status, body, retryAfter, requestId }.
export async function callview(method, path, { body, idempotencyKey } = {}) {
  const url = path.startsWith('/api/') ? HOST + path : BASE + path;
  for (let attempt = 1; attempt <= 5; attempt++) {
    let res;
    try {
      res = await fetch(url, {
        method,
        headers: {
          Authorization: AUTH,
          ...(body === undefined ? {} : { 'Content-Type': 'application/json' }),
          ...(idempotencyKey ? { 'Idempotency-Key': idempotencyKey } : {}),
        },
        body: body === undefined ? undefined : JSON.stringify(body),
        signal: AbortSignal.timeout(30_000),
      });
    } catch (err) {
      if (attempt === 5) throw err;
      await sleep(500 * 2 ** attempt);
      continue;
    }
    const isJson = (res.headers.get('content-type') ?? '').includes('application/json');
    const data = isJson ? await res.json() : await res.text();
    const code = isJson ? data.error?.code : undefined;
    const retryAfter = Number(res.headers.get('retry-after') ?? 0) || 0;
    const worthRetrying = res.status >= 500 || (RETRY_CODES.has(code) && retryAfter <= 60);
    if (!worthRetrying || attempt === 5) return { status: res.status, body: data, retryAfter, requestId: res.headers.get('request-id') };
    await sleep(Math.max(retryAfter * 1000, 500 * 2 ** attempt));
  }
}

// What the CRM gets back: { ok: true, ...the reply } or { ok: false, status, error, retryAfter }.
// retryAfter is in seconds, 0 when there's none: after queue_full or call_limit_reached, try again then.
function answer(r, okStatuses) {
  if (okStatuses.includes(r.status)) return { ok: true, ...r.body.data };
  const error = r.body && typeof r.body === 'object' && r.body.error ? r.body.error : { message: String(r.body) };
  return { ok: false, status: r.status, error, retryAfter: r.retryAfter, requestId: r.requestId };
}

// Send one CRM record to CallView, to be called now. `record` is your CRM's own lead.
// `sendNo` is 1 the first time. Pass 2, 3 and so on when someone sends the record
// again on purpose, so it isn't answered with an earlier send's kept reply.
export async function sendLead(record, sendNo = 1) {
  const lead = {
    campaign_id: process.env.CALLVIEW_CAMPAIGN_ID,
    external_id: `crm-${record.id}`, // comes back on every call and event about this lead
    phone: record.phone, // +1 and 10 digits
    name: record.name,
    ...(record.email ? { email: record.email } : {}), // leave it out rather than send null
    // Your own fields, as text. The campaign's script can use them.
    fields: { product: record.product ?? '', budget: String(record.budget ?? '') },
    consent: { source: 'web_form', agreed_at: record.consentAt, url: record.consentUrl },
    call_now: true,
  };
  // The same send of the same data reuses its key; changed data gets a new one.
  const version = crypto.createHash('sha256').update(JSON.stringify(lead)).digest('hex').slice(0, 16);
  const r = await callview('POST', '/leads', { body: lead, idempotencyKey: `crm-${record.id}-send${sendNo}-${version}` });
  return answer(r, [200, 201]);
}

// Call a lead that's already in CallView, now. `clickId` is new for each click in
// the CRM, so each click is its own call and a retry of the same click isn't.
export async function callAgain(record, clickId) {
  const r = await callview('POST', '/calls', {
    idempotencyKey: `crm-${record.id}-call-${clickId}`,
    body: { external_id: `crm-${record.id}` },
  });
  return answer(r, [202]);
}

// The transcript as plain text, one "Name: text" line a turn. `transcriptPath`
// is call.completed's transcript_path. Needs Recordings & transcripts on the key.
export async function fetchTranscript(transcriptPath) {
  const r = await callview('GET', `${transcriptPath}?format=text`);
  if (r.status === 200) return r.body;
  if (r.status === 403) return null; // the key hasn't got recordings:read
  throw new Error(`CallView ${r.status} ${r.body?.error?.code ?? ''} (request ${r.requestId})`);
}
```

```python title="callview.py"
# callview.py: your CRM's side of CallView (Python 3.8 or later). pip install requests
# The key comes from the environment: CALLVIEW_KEY_ID and CALLVIEW_SECRET.
import hashlib
import json
import os
import time

import requests

HOST = "https://v2-api.callview.ai"
BASE = HOST + "/api/v1/external"
AUTH = (os.environ["CALLVIEW_KEY_ID"], os.environ["CALLVIEW_SECRET"])

# Answers worth waiting for and sending again, with the same Idempotency-Key.
RETRY_CODES = {"rate_limited", "too_many_concurrent_requests", "lead_rate_limited", "idempotency_in_progress", "test_flows_busy"}

def callview(method, path, body=None, idempotency_key=None):
    """One request, tried up to 5 times. Answers (status, body, retry_after, request_id)."""
    url = HOST + path if path.startswith("/api/") else BASE + path
    headers = {"Idempotency-Key": idempotency_key} if idempotency_key else {}
    for attempt in range(1, 6):
        try:
            res = requests.request(method, url, auth=AUTH, headers=headers, json=body, timeout=30)
        except requests.RequestException:
            if attempt == 5:
                raise
            time.sleep(0.5 * 2 ** attempt)
            continue
        is_json = "application/json" in res.headers.get("Content-Type", "")
        data = res.json() if is_json else res.text
        code = (data.get("error") or {}).get("code") if is_json else None
        retry_after = int(res.headers.get("Retry-After") or 0)
        worth_retrying = res.status_code >= 500 or (code in RETRY_CODES and retry_after <= 60)
        if not worth_retrying or attempt == 5:
            return res.status_code, data, retry_after, res.headers.get("Request-Id")
        time.sleep(max(retry_after, 0.5 * 2 ** attempt))

def _answer(status, data, retry_after, request_id, ok_statuses):
    """What the CRM gets back: {"ok": True, ...the reply} or {"ok": False, "status", "error", "retry_after"}.
    retry_after is in seconds, 0 when there's none: after queue_full or call_limit_reached, try again then."""
    if status in ok_statuses:
        return {"ok": True, **data["data"]}
    error = data.get("error", {}) if isinstance(data, dict) else {"message": str(data)}
    return {"ok": False, "status": status, "error": error, "retry_after": retry_after, "request_id": request_id}

def send_lead(record, send_no=1):
    """Send one CRM record to CallView, to be called now. `record` is your CRM's own lead.
    `send_no` is 1 the first time. Pass 2, 3 and so on when someone sends the record
    again on purpose, so it isn't answered with an earlier send's kept reply."""
    lead = {
        "campaign_id": os.environ["CALLVIEW_CAMPAIGN_ID"],
        "external_id": f"crm-{record['id']}",  # comes back on every call and event about this lead
        "phone": record["phone"],  # +1 and 10 digits
        "name": record["name"],
        # Your own fields, as text. The campaign's script can use them.
        "fields": {"product": record.get("product") or "", "budget": str(record.get("budget") or "")},
        "consent": {"source": "web_form", "agreed_at": record["consent_at"], "url": record["consent_url"]},
        "call_now": True,
    }
    if record.get("email"):
        lead["email"] = record["email"]  # leave it out rather than send None
    # The same send of the same data reuses its key; changed data gets a new one.
    version = hashlib.sha256(json.dumps(lead, sort_keys=True).encode("utf-8")).hexdigest()[:16]
    key = f"crm-{record['id']}-send{send_no}-{version}"
    return _answer(*callview("POST", "/leads", body=lead, idempotency_key=key), (200, 201))

def call_again(record, click_id):
    """Call a lead that's already in CallView, now. `click_id` is new for each
    click in the CRM, so each click is its own call and a retry of it isn't."""
    key = f"crm-{record['id']}-call-{click_id}"
    return _answer(*callview("POST", "/calls", body={"external_id": f"crm-{record['id']}"}, idempotency_key=key), (202,))

def fetch_transcript(transcript_path):
    """The transcript as plain text, one "Name: text" line a turn. `transcript_path`
    is call.completed's transcript_path. Needs Recordings & transcripts on the key."""
    status, data, _retry_after, request_id = callview("GET", transcript_path + "?format=text")
    if status == 200:
        return data
    if status == 403:
        return None  # the key hasn't got recordings:read
    raise RuntimeError(f"CallView {status} (request {request_id})")
```

Change the consent to match how your leads really agree to be called. Only the fields in the [API reference](https://developers.callview.ai/reference/leads/) are taken: unknown ones are refused, so don't send the CRM's whole record.

## 3. Read the answer to POST /leads

`sendLead` gives back the reply's `data`, or the error. Show it on the record:

| You get | What it means | In the CRM |
| --- | --- | --- |
| `201`, `"status": "dialing"` | A line was free. The AI is calling now. | "Calling now" |
| `201`, `"status": "queued"` | Waiting for a free line. `place_in_line` 1 is next. | "In line" |
| `201`, `"status": "scheduled"` | Outside the lead's calling hours, or another of your campaigns called the number in the last 24 hours. `scheduled_for` says when. | "Calls at ..." |
| `201`, `"status": "held"` | Kept, not dialing yet. `held_reason` says why (below). | "Waiting" |
| `200`, `"requeued": true` | The lead was already there, from before the campaign's repeat window (30 days unless it's changed), and it's back in line. | As `queued` |
| `409 duplicate_lead` | Already in the campaign. `error.lead_id` is the lead you have. | Use `callAgain` to call it now, or `PATCH /leads/{id}` to change its details |
| `409 idempotency_mismatch` | Not a duplicate lead. The same `Idempotency-Key` came with a different body, so the key is being made wrong. The module above doesn't do this. | Fix how the key is made |
| `422 on_dnc_list` | The number is on your Do Not Call list. | Mark it do-not-call |
| `400 invalid_phone`, `422 consent_required` | The record needs fixing. `error.param` names the field. | Flag the record, then send it with the next send number |
| `403 permission_denied` | The key is missing a permission, named in `error.missing_permission` (for example `dialing:write`). | Fix the key, then send with the next send number |
| `429 queue_full` | The campaign has 5,000 API leads waiting. | Send it again after `retryAfter` seconds |

The `held_reason` words:

| `held_reason` | Why | It's called |
| --- | --- | --- |
| `campaign_paused` | The campaign is paused. | When someone resumes it |
| `campaign_not_started` | The campaign hasn't been started. | When someone starts it |
| `spend_cap_reached` | Your organization's daily or monthly API spend cap is reached. | When the cap lifts |
| `key_limit_reached` | This key's own calls per day or daily spend cap is reached. | After midnight in your organization's time zone |

A held lead isn't lost and you don't need to send it again. It's called in its turn once the hold lifts. [Speed to lead](https://developers.callview.ai/guides/speed-to-lead/) has the whole story of a lead after `POST /leads`.

## 4. Call a lead again

For a lead that's already in CallView, a "Call now" button in the CRM can use `callAgain`. It answers `202` with the same `status` words as `POST /leads`, plus `calls_left_today`. The key needs Calls: write and Start calls for this, so tick Calls: write too if you use it.

| You get | What it means |
| --- | --- |
| `409 lead_busy` | The lead is being dialed or is on a call right now. |
| `429 call_limit_reached` | The lead was called through the API 3 times in 24 hours. `retryAfter` says how many seconds until you can again. |
| `422 on_dnc_list` | The number is on your Do Not Call list. |
| `404 not_found` | No lead with that `external_id` in the key's campaigns. Send it with `sendLead` first. |

## 5. Get the outcome back

Point a webhook endpoint at your receiver. Do it once, with the CRM's key:

```bash
curl -X POST 'https://v2-api.callview.ai/api/v1/external/webhook_endpoints' \
  -u "$CALLVIEW_KEY_ID:$CALLVIEW_SECRET" \
  -H 'Content-Type: application/json' \
  -d '{
    "url": "https://crm.example.com/callview",
    "events": ["call.completed", "lead.opted_out"],
    "campaign_ids": ["7c1f2b9e-4a3d-4e8f-9b21-5d6a7e8f9a01"]
  }'
```

Put the key's campaigns in `campaign_ids`. An endpoint without it covers every campaign, and a key limited to some campaigns can't make one of those: it gets `403 permission_denied`.

The reply has a `secret` that starts with `whsec_`. It's shown this once. Give it to the receiver as `CALLVIEW_WEBHOOK_SECRET`.

The receiver below checks every delivery's `CallView-Signature` with the code from [Webhooks and signatures](https://developers.callview.ai/guides/webhooks/#check-the-signature). Save that page's `verify-signature.js` next to it as `verify-signature.mjs` (the `.mjs` name makes Node load it as a module), or `verify_signature.py` for Python. The check is an HMAC-SHA256 over the raw body with your `whsec_` secret, and anything older than 5 minutes is refused, so a stranger can't send your CRM fake outcomes or replay old ones.

Then it:

- refuses a body over 1 MB before checking it (events are a few KB);
- answers `200` straight away (we wait at most 10 seconds) and does the slow part after;
- skips an event `id` it has already handled, because the same event can arrive twice;
- leaves out test sends (`"sample": true`) and test-mode events (`"livemode": false`), which carry example data and placeholders, unless you set `CALLVIEW_ACCEPT_TEST_EVENTS=1` on a test copy of your CRM;
- writes `outcome`, `outcome_label`, `note`, `handled_by` and `callback_at` to the record found by `lead.external_id`, but only when that call's `revision` is newer than the one stored, checked and written in one step, because a corrected outcome arrives as a new `call.completed` for the same call;
- saves the outcome first, then fetches the transcript, so a failed fetch doesn't lose the outcome;
- marks the record do-not-call on `lead.opted_out`;
- logs IDs and the outcome only, not the lead's details or the transcript.

```js title="receiver.mjs"
// receiver.mjs: CallView's events into your CRM (Node 20 or later, no packages).
// Save verify-signature.js (from the Webhooks and signatures page) next to it as verify-signature.mjs.
import http from 'node:http';
import { verifyCallViewSignature } from './verify-signature.mjs';
import { fetchTranscript } from './callview.mjs';

const MAX_BODY = 1024 * 1024; // events are a few KB: refuse anything over 1 MB
const ACCEPT_TEST_EVENTS = process.env.CALLVIEW_ACCEPT_TEST_EVENTS === '1'; // only on a test copy of your CRM
const handled = new Set(); // event ids you've handled: use your database in real life

// Your CRM. Replace these with your own database updates.
const revisions = new Map(); // call id -> the revision written: stands in for your database

// Writes the outcome only if it's newer than the one stored for this call, and says
// whether it did. Check and write in one step. In SQL: INSERT INTO call_outcomes ...
// ON CONFLICT (call_id) DO UPDATE SET ... WHERE call_outcomes.revision < EXCLUDED.revision
async function saveOutcomeIfNewer(externalId, callId, revision, fields) {
  if ((revisions.get(callId) ?? 0) >= revision) return false;
  revisions.set(callId, revision); // nothing awaited between the check and the write
  console.log('outcome', externalId, callId, revision, fields.outcome); // IDs and the outcome only
  return true;
}
async function saveTranscript(externalId, callId, text) {
  console.log('transcript', externalId, callId, `${text.length} characters`);
}
async function markDoNotCall(externalId) {
  console.log('do not call', externalId);
}

async function handle(event) {
  const obj = event.data.object;
  if (event.type === 'call.completed') {
    const externalId = obj.lead?.external_id;
    if (!externalId) return; // a lead your CRM didn't send
    const saved = await saveOutcomeIfNewer(externalId, obj.id, obj.revision, {
      outcome: obj.outcome, // a fixed word: build your rules on this
      outcome_label: obj.outcome_label, // your team's name for it: show this
      note: obj.note, // what was said, in a sentence or two
      handled_by: obj.handled_by?.name, // "AI", or the person who took the call
      callback_at: obj.callback_at, // when outcome is "callback"
      duration_seconds: obj.duration_seconds,
    });
    if (!saved || !obj.transcript_path) return; // an older version, or no transcript
    try {
      const text = await fetchTranscript(obj.transcript_path);
      if (text !== null) await saveTranscript(externalId, obj.id, text);
    } catch (err) {
      console.error(`transcript for call ${obj.id}: ${err.message}`); // the outcome is saved already
    }
  } else if (event.type === 'lead.opted_out' && obj.external_id) {
    await markDoNotCall(obj.external_id);
  }
}

http
  .createServer((req, res) => {
    if (req.method !== 'POST' || req.url !== '/callview') {
      res.writeHead(404).end();
      return;
    }
    if (Number(req.headers['content-length'] ?? 0) > MAX_BODY) {
      res.writeHead(413).end();
      return;
    }
    const chunks = [];
    let size = 0;
    req.on('data', (chunk) => {
      size += chunk.length;
      if (size > MAX_BODY) {
        res.writeHead(413).end();
        req.destroy();
        return;
      }
      chunks.push(chunk);
    });
    req.on('end', () => {
      const raw = Buffer.concat(chunks); // the raw bytes: the signature is over these
      if (!verifyCallViewSignature(raw, req.headers['callview-signature'], process.env.CALLVIEW_WEBHOOK_SECRET)) {
        res.writeHead(400).end('bad signature');
        return;
      }
      const event = JSON.parse(raw.toString('utf8'));
      res.writeHead(200).end(); // answer first: the slow part runs after
      if (event.sample || (!event.livemode && !ACCEPT_TEST_EVENTS)) return; // example data, not a real call
      if (handled.has(event.id)) return; // a repeat: already handled
      handled.add(event.id);
      handle(event).catch((err) => console.error(`event ${event.id}: ${err.message}`));
    });
  })
  .listen(3000, () => console.log('Listening on http://localhost:3000/callview'));
```

```python title="receiver.py"
# receiver.py: CallView's events into your CRM. pip install flask requests
# Save verify_signature.py (from the Webhooks and signatures page) next to it.
import json
import os
import threading

from flask import Flask, request

from callview import fetch_transcript
from verify_signature import verify_callview_signature

app = Flask(__name__)
app.config["MAX_CONTENT_LENGTH"] = 1024 * 1024  # events are a few KB: Flask refuses over 1 MB with 413
ACCEPT_TEST_EVENTS = os.environ.get("CALLVIEW_ACCEPT_TEST_EVENTS") == "1"  # only on a test copy of your CRM
handled = set()  # event ids you've handled: use your database in real life
handled_lock = threading.Lock()

# Your CRM. Replace these with your own database updates.
revisions = {}  # call id -> the revision written: stands in for your database
revisions_lock = threading.Lock()

def save_outcome_if_newer(external_id, call_id, revision, fields):
    """Writes the outcome only if it's newer than the one stored for this call, and
    says whether it did. Check and write in one step. In SQL: INSERT INTO call_outcomes
    ... ON CONFLICT (call_id) DO UPDATE SET ... WHERE call_outcomes.revision < EXCLUDED.revision"""
    with revisions_lock:  # two threads can't both pass the check
        if revisions.get(call_id, 0) >= revision:
            return False
        revisions[call_id] = revision
        print("outcome", external_id, call_id, revision, fields["outcome"])  # IDs and the outcome only
        return True

def save_transcript(external_id, call_id, text):
    print("transcript", external_id, call_id, f"{len(text)} characters")

def mark_do_not_call(external_id):
    print("do not call", external_id)

def handle(event):
    obj = event["data"]["object"]
    if event["type"] == "call.completed":
        external_id = (obj.get("lead") or {}).get("external_id")
        if not external_id:
            return  # a lead your CRM didn't send
        saved = save_outcome_if_newer(external_id, obj["id"], obj["revision"], {
            "outcome": obj["outcome"],  # a fixed word: build your rules on this
            "outcome_label": obj["outcome_label"],  # your team's name for it: show this
            "note": obj["note"],  # what was said, in a sentence or two
            "handled_by": (obj.get("handled_by") or {}).get("name"),  # "AI", or the person who took the call
            "callback_at": obj["callback_at"],  # when outcome is "callback"
            "duration_seconds": obj["duration_seconds"],
        })
        if not saved or not obj.get("transcript_path"):
            return  # an older version, or no transcript
        try:
            text = fetch_transcript(obj["transcript_path"])
            if text is not None:
                save_transcript(external_id, obj["id"], text)
        except Exception as err:  # the outcome is saved already
            print(f"transcript for call {obj['id']}: {err}")
    elif event["type"] == "lead.opted_out" and obj.get("external_id"):
        mark_do_not_call(obj["external_id"])

@app.post("/callview")
def callview_events():
    raw = request.get_data()  # the raw bytes: the signature is over these
    header = request.headers.get("CallView-Signature", "")
    if not verify_callview_signature(raw, header, os.environ["CALLVIEW_WEBHOOK_SECRET"]):
        return "bad signature", 400
    event = json.loads(raw)
    if event.get("sample") or (not event["livemode"] and not ACCEPT_TEST_EVENTS):
        return "", 200  # example data, not a real call
    with handled_lock:
        if event["id"] in handled:
            return "", 200  # a repeat: already handled
        handled.add(event["id"])
    # Answer first: the slow part runs after.
    threading.Thread(target=handle, args=(event,), daemon=True).start()
    return "", 200

if __name__ == "__main__":
    app.run(port=3000)
```

In real life, save each event to a table or a queue before you answer, and work through it from there. If your server was down or a write failed, `GET /events?type=call.completed&created[gte]=...` lists what you missed (we keep events for 30 days). The [outcome words](https://developers.callview.ai/guides/outcomes/) page says what each `outcome` means.

## 6. The transcript

`call.completed` carries `transcript_path` and `recording_path` when there is one, not the text or the audio itself. `fetchTranscript` asks for `?format=text`, one "Name: text" line a turn. Leave that off for JSON, with each line's speaker (`ai`, `lead` or `agent`), name and time.

Both need Calls: read and Recordings & transcripts (`recordings:read`) on the key. Without it you get `403 permission_denied` with `"missing_permission": "recordings:read"`, and `fetchTranscript` returns nothing. The receiver saves the outcome before it asks, so a missing permission or a failed fetch costs only the transcript. For the recording, `GET /calls/{id}/recording` gives a link that works for 5 minutes, so fetch it when someone presses play, and don't store the link.

## 7. Test, then go live

Run the receiver against a test copy of your CRM with `CALLVIEW_ACCEPT_TEST_EVENTS=1`, so it writes test-mode events. With the test key, send leads with the [magic numbers](https://developers.callview.ai/guides/test-mode/) as the phone. `+15550100001` plays an interested lead whom someone on your team takes over, with `call.completed` about 4 minutes later. `+15550100002` leaves a voicemail and `+15550100005` asks not to be called again, which sends `lead.opted_out`. Test events have placeholders like `LEAD_NAME` and `AI_NOTE` instead of real data, and the transcript lines read `AI_LINE_1`, `LEAD_LINE_1` and so on.

To send your receiver a signed sample at any time, use `POST /webhook_endpoints/{id}/test` with `{ "type": "call.completed" }`. It's marked `"sample": true`, so the receiver checks its signature and answers `200` but doesn't write it to a record.

When it all works:

1. Make a live key with the same settings, and put its ID and secret in the environment instead of the test ones.
2. Make the webhook endpoint again with the live key and the same `campaign_ids` (an endpoint made with a test key only ever gets test events), and give the receiver its new `whsec_` secret. On the real CRM, leave `CALLVIEW_ACCEPT_TEST_EVENTS` unset.
3. Send one real lead you can answer yourself, and watch the outcome land on the record.

The campaign ID stays the same: a test key sees your real campaigns.
