# Log every call to your CRM

> A small server that receives MoreVoice's webhooks and logs each call on the contact in your CRM: the call when it ends, the summary and outcome when the analysis is ready, and the recording. Runs in test mode first.

Every call your assistants and agents handle ends up on the right contact in your CRM: when it happened, how long it took and why it ended, what was said and agreed, and the recording. A small server of yours receives MoreVoice's [webhooks](https://docs.morevoice.ai/webhooks/setup/), checks their signatures, and writes to the CRM.

> **A CRM MoreVoice connects to directly?**
>
> For CRMs with a built-in MoreVoice integration, calls are logged without code: see the [integrations](https://morevoice.ai/en/integrations/). This recipe is for your own CRM, an in-house system, or anything the integrations don't cover.

## How it works

Three events carry everything, each as soon as it is ready:

| Event | When | What the CRM gets |
| --- | --- | --- |
| [`call.ended`](https://docs.morevoice.ai/webhooks/events/#call.ended) | The call ended | Direction, numbers, start time, duration, end reason, and the call's `metadata` |
| [`call.analyzed`](https://docs.morevoice.ai/webhooks/events/#call.analyzed) | A few seconds later, when the post-call analysis is ready | Summary, intent, outcome, action items |
| [`recording.ready`](https://docs.morevoice.ai/webhooks/events/#recording.ready) | The recording is stored | A signed URL to download it, valid until `url_expires_at` |

They arrive separately and in no fixed order, so the server writes one activity per call (`call_…` ID) and fills it in as each event lands. To know which contact a call belongs to, put your CRM's contact ID in the call's `metadata` when you place it (`crm_contact_id` below): every event about the call carries it back. For inbound calls without one, look the contact up by the caller's number.

## Before you start

- A **test key** (`mv_test_sk_…`) from **Developers › API keys**: see [authentication](https://docs.morevoice.ai/get-started/authentication/). Test calls run on the virtual carrier, so nothing is dialled or billed.
- Node.js 18 or later, and the SDK: `npm install @morevoice/sdk`.
- A URL MoreVoice can reach for your server. While developing, [`morevoice listen --forward-to`](https://docs.morevoice.ai/guides/cli/) brings the events to your machine without one, or use a tunnel (ngrok, Cloudflare Tunnel).

## Build it

1. **Subscribe to the events.** Create a webhook endpoint for your server's URL. The answer holds the endpoint's signing secret, once: keep it for the next step.

   ```ts title="setup.ts"
   // Step 1: subscribe your server to the events the CRM needs. Run it once with a test key, and once with a live key:
   // each mode has its own endpoints and its own signing secret.
   import MoreVoice from "@morevoice/sdk";

   const mv = new MoreVoice(); // reads MOREVOICE_API_KEY

   const endpoint = await mv.webhookEndpoints.create({
   	url: process.env.WEBHOOK_URL!, // e.g. https://crm-bridge.example.com/webhooks/morevoice
   	enabled_events: ["call.ended", "call.analyzed", "recording.ready"],
   	description: "CRM call logging",
   });

   // The secret is shown this once: give it to server.ts as MOREVOICE_WEBHOOK_SECRET.
   console.log(`MOREVOICE_WEBHOOK_SECRET=${endpoint.secret}`);
   ```

2. **Connect your CRM.** The server talks to the CRM through two operations: create-or-update the call's activity, and attach the recording. Replace `JsonFileCrm` with your CRM's API; as written, it keeps everything in a JSON file so you can watch it work.

   ```ts title="crm.ts"
   // The CRM side. Replace JsonFileCrm with calls to your CRM's API: find the contact, then add a call activity to it.
   // This one keeps everything in a JSON file, so the recipe runs as it is.
   import { readFile, writeFile } from "node:fs/promises";

   export interface CallActivity {
   	callId: string;
   	contactId: string | null;
   	phone: string | null;
   	direction: string | null;
   	startedAt: string | null;
   	durationSeconds: number | null;
   	endReason: string | null;
   	summary?: string | null;
   	outcome?: string | null;
   	actionItems?: string[];
   	recordingFile?: string;
   }

   export interface Crm {
   	/** Creates the activity, or updates it when it exists: events about one call arrive separately, in any order. */
   	upsertActivity(activity: Partial<CallActivity> & { callId: string }): Promise<void>;
   	/** Stores the recording with the activity (the URL MoreVoice sends expires, so keep the file, not the link). */
   	attachRecording(callId: string, audio: Uint8Array, contentType: string): Promise<void>;
   }

   export class JsonFileCrm implements Crm {
   	constructor(private readonly file: string) {}

   	private async load(): Promise<Record<string, CallActivity>> {
   		try {
   			return JSON.parse(await readFile(this.file, "utf8")) as Record<string, CallActivity>;
   		} catch {
   			return {};
   		}
   	}

   	async upsertActivity(activity: Partial<CallActivity> & { callId: string }): Promise<void> {
   		const all = await this.load();
   		const current = all[activity.callId] ?? ({ callId: activity.callId, contactId: null, phone: null, direction: null, startedAt: null, durationSeconds: null, endReason: null } as CallActivity);
   		all[activity.callId] = { ...current, ...Object.fromEntries(Object.entries(activity).filter(([, v]) => v !== undefined)) };
   		await writeFile(this.file, `${JSON.stringify(all, null, 2)}\n`);
   	}

   	async attachRecording(callId: string, audio: Uint8Array, contentType: string): Promise<void> {
   		const ext = contentType.includes("mpeg") ? "mp3" : contentType.includes("ogg") ? "ogg" : "wav";
   		const recordingFile = `${this.file.replace(/\.json$/, "")}-${callId}.${ext}`;
   		await writeFile(recordingFile, audio);
   		await this.upsertActivity({ callId, recordingFile });
   	}
   }
   ```

3. **Run the bridge.** It verifies each delivery (an unsigned or changed request gets `400`), skips events it has already handled, and answers `204` once the CRM has the data. If the CRM is down it answers `500`, and MoreVoice retries with backoff for up to 72 hours, so nothing is lost.

   ```ts title="server.ts"
   // Step 2: the bridge between MoreVoice and your CRM. It checks each webhook's signature, then logs the call on the
   // contact: the call itself when it ends, the summary and outcome when the analysis is ready, the recording when it is.
   import { createServer } from "node:http";
   import { webhooks, WebhookVerificationError, type MoreVoiceEvent } from "@morevoice/sdk";
   import { JsonFileCrm } from "./crm.ts";

   const secret = process.env.MOREVOICE_WEBHOOK_SECRET!; // whsec_…, from setup.ts
   const crm = new JsonFileCrm(process.env.CRM_FILE ?? "crm.json");
   const handled = new Set<string>(); // event IDs already logged: a delivery can repeat (keep this in your database)

   createServer(async (req, res) => {
   	if (req.method !== "POST" || req.url !== "/webhooks/morevoice") return void res.writeHead(404).end();
   	const chunks: Buffer[] = [];
   	for await (const chunk of req) chunks.push(chunk as Buffer);
   	let event: MoreVoiceEvent;
   	try {
   		event = webhooks.constructEvent(Buffer.concat(chunks), req.headers, secret);
   	} catch (err) {
   		if (err instanceof WebhookVerificationError) return void res.writeHead(400).end(err.code);
   		throw err;
   	}
   	try {
   		if (!handled.has(event.id)) await logToCrm(event);
   		handled.add(event.id);
   		res.writeHead(204).end();
   	} catch (err) {
   		console.error(`${event.type} ${event.id}:`, err);
   		res.writeHead(500).end(); // MoreVoice retries with backoff, for up to 72 hours
   	}
   }).listen(Number(process.env.PORT ?? 3000));

   async function logToCrm(event: MoreVoiceEvent): Promise<void> {
   	switch (event.type) {
   		case "call.ended": {
   			const call = event.data.object;
   			if (!call.id) break;
   			await crm.upsertActivity({
   				callId: call.id,
   				contactId: typeof call.metadata?.crm_contact_id === "string" ? call.metadata.crm_contact_id : null, // set when you placed the call
   				phone: call.direction === "inbound" ? call.from : call.to,
   				direction: call.direction,
   				startedAt: call.started_at,
   				durationSeconds: call.duration_ms == null ? null : Math.round(call.duration_ms / 1000),
   				endReason: call.end_reason,
   			});
   			break;
   		}
   		case "call.analyzed": {
   			const analysis = event.data.object;
   			if (!analysis.id) break;
   			await crm.upsertActivity({ callId: analysis.id, summary: analysis.summary, outcome: analysis.outcome, actionItems: (analysis.action_items ?? []).map(String) });
   			break;
   		}
   		case "recording.ready": {
   			const recording = event.data.object;
   			if (!recording.url || !recording.call_id) break;
   			const res = await fetch(recording.url); // a signed URL: fetch it now, it expires at url_expires_at
   			if (!res.ok) throw new Error(`recording download: HTTP ${res.status}`);
   			await crm.attachRecording(recording.call_id, new Uint8Array(await res.arrayBuffer()), res.headers.get("content-type") ?? "audio/wav");
   			break;
   		}
   	}
   }
   ```

   Start it with the secret from step 1: `MOREVOICE_WEBHOOK_SECRET=whsec_… npx tsx server.ts`.

## Try it in test mode

Place a test call with the contact's ID in its metadata, and wait for it to end:

```ts title="test-call.ts"
// Step 3: try it in test mode. A test call to +972500000001 answers and talks on the virtual carrier; nothing is dialled
// or billed. `metadata` travels with the call into every event, so the bridge knows which contact it belongs to.
import MoreVoice from "@morevoice/sdk";

const mv = new MoreVoice(); // a test key: mv_test_sk_…

const call = await mv.calls.create({
	to: "+972500000001",
	assistant_id: process.env.ASSISTANT_ID!,
	purpose: "service",
	metadata: { crm_contact_id: "contact-1042" },
});
const ended = await mv.calls.waitUntilEnded(call.id, { waitForAnalysisMs: 30_000 });
console.log(`${ended.id} ${ended.status}: ${ended.summary?.text ?? "no summary yet"}`);
```

```sh
MOREVOICE_API_KEY=mv_test_sk_… ASSISTANT_ID=asst_… npx tsx test-call.ts
```

Within seconds of the end, `crm.json` holds the call on `contact-1042`: its duration and end reason, then the summary and outcome, and the recording next to it. The endpoint's page in **Developers › Webhooks** lists each delivery with your server's answer, which is the first place to look when something is missing.

## Go live

- Run `setup.ts` again with a **live** key: live and test endpoints, and their secrets, are separate.
- Keep the handled event IDs in your database, not in memory, so a restart doesn't log a call twice.
- Store the recording file, not its URL: the URL expires. Mind your retention rules: MoreVoice deletes recordings on its own schedule, your CRM keeps its copy as long as you do.
- Place outbound calls with `metadata: { crm_contact_id }` (and campaigns with a contact variable), so every call finds its contact without a lookup.
