Log every call to your CRM
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, checks their signatures, and writes to the CRM.
How it works
Section titled “How it works”Three events carry everything, each as soon as it is ready:
| Event | When | What the CRM gets |
|---|---|---|
call.ended |
The call ended | Direction, numbers, start time, duration, end reason, and the call’s metadata |
call.analyzed |
A few seconds later, when the post-call analysis is ready | Summary, intent, outcome, action items |
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
Section titled “Before you start”- A test key (
mv_test_sk_…) from DevelopersAPI keys: see 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-tobrings the events to your machine without one, or use a tunnel (ngrok, Cloudflare Tunnel).
Build it
Section titled “Build it”-
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.
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_KEYconst endpoint = await mv.webhookEndpoints.create({url: process.env.WEBHOOK_URL!, // e.g. https://crm-bridge.example.com/webhooks/morevoiceenabled_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}`); -
Connect your CRM. The server talks to the CRM through two operations: create-or-update the call’s activity, and attach the recording. Replace
JsonFileCrmwith your CRM’s API; as written, it keeps everything in a JSON file so you can watch it work.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 });}} -
Run the bridge. It verifies each delivery (an unsigned or changed request gets
400), skips events it has already handled, and answers204once the CRM has the data. If the CRM is down it answers500, and MoreVoice retries with backoff for up to 72 hours, so nothing is lost.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.tsconst 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 callphone: 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_atif (!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
Section titled “Try it in test mode”Place a test call with the contact’s ID in its metadata, and wait for it to end:
// 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"}`);MOREVOICE_API_KEY=mv_test_sk_… ASSISTANT_ID=asst_… npx tsx test-call.tsWithin 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 DevelopersWebhooks lists each delivery with your server’s answer, which is the first place to look when something is missing.
Go live
Section titled “Go live”- Run
setup.tsagain 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.