Integrations

Use TryVox as the Telephony Layer for Your Platform

Keep your app. Add a Call button that places a real phone call through TryVox and shows its status.

This example uses an existing TryVox account with its own KYC, wallet and number. To run many customers under one account, each with its own KYC, numbers and API key, follow the multi-customer platform guide.

If you already run a SaaS product, CRM, support or sales tool, voice-AI product, or your own backend, you don't need to rebuild anything to add calling. Your app keeps its UI, users and data. Your backend asks TryVox to place calls, and TryVox tells your backend what happened.

Your platform ──── TryVox REST API ────▶ TryVox ──── phone network ────▶ the person you call

the phone network ─▶ TryVox ──── webhook ────▶ your backend

What you will build

A Call customer button in your app that places a real call, then shows ringing → answered → completed as it happens.

Your UI          POST /api/call
   │                  │
   ▼                  ▼
Your backend ── POST /v1/voice/accounts/{auth_id}/calls ──▶ TryVox ──▶ customer's phone

TryVox ── POST /webhooks/tryvox (signed) ──▶ Your backend ──▶ your database / UI
  1. The user clicks Call customer. Your frontend calls your backend.
  2. Your backend calls TryVox with your credentials.
  3. TryVox rings the customer.
  4. When they answer, TryVox asks your backend what to do (answer_url). Here it reads out a short message.
  5. TryVox sends ringing, answered and ended events to your webhook. Your backend updates the call.
  6. Afterwards you can look up the call record and recording. See Next step.

Before you start

  • API credentials, approved KYC, wallet balance, and an active TryVox number. See Before any guide.
  • Node.js 20.6 or newer.
  • A public HTTPS URL for your machine, so TryVox can reach your webhooks. For example run ngrok http 3000.

Try it

Create a folder with these four files. This example needs nothing installed beyond Node.js.

The shared helper

tryvox.js holds your settings, the TryVox API call with your credentials, and the webhook signature check. Every example in these guides uses it, so you write them once.

tryvox.js
// Shared helpers for the TryVox examples: settings, API calls, webhook
// signatures, and two tiny HTTP helpers. Server-side only — this file holds
// your Auth Token and must never be sent to a browser.

import crypto from 'node:crypto';

export const API_URL = process.env.TRYVOX_API_URL ?? 'https://api.tryvox.io';

// Reads settings from the environment (.env), failing loudly if one is missing.
export function env(...names) {
  const values = {};
  for (const name of names) {
    if (!process.env[name]) throw new Error(`${name} is not set. Copy .env.example to .env and fill it in.`);
    values[name] = process.env[name];
  }
  return values;
}

// HTTP Basic auth: your Auth ID and Auth Token.
export function authHeader() {
  const { TRYVOX_AUTH_ID, TRYVOX_AUTH_TOKEN } = env('TRYVOX_AUTH_ID', 'TRYVOX_AUTH_TOKEN');
  return 'Basic ' + Buffer.from(`${TRYVOX_AUTH_ID}:${TRYVOX_AUTH_TOKEN}`).toString('base64');
}

// Calls the TryVox API and returns the parsed JSON. "{auth_id}" in the path is
// filled in for you. Throws with .status and .code when TryVox returns an error.
export async function tryvox(method, path, body) {
  const url = API_URL + path.replace('{auth_id}', env('TRYVOX_AUTH_ID').TRYVOX_AUTH_ID);
  const res = await fetch(url, {
    method,
    headers: { Authorization: authHeader(), 'Content-Type': 'application/json' },
    body: body === undefined ? undefined : JSON.stringify(body),
  });
  const text = await res.text();
  const data = text ? JSON.parse(text) : {};
  if (!res.ok) {
    const err = new Error(data.error?.message ?? `TryVox returned ${res.status}`);
    err.status = res.status;
    err.code = data.error?.code;
    throw err;
  }
  return data;
}

// Checks X-TryVox-Signature: t=<unix seconds>,v1=<hex HMAC-SHA256 of "<t>.<raw body>">,
// signed with your webhook_secret. Rejects anything older than 5 minutes.
export function isFromTryVox(signatureHeader, rawBody, secret = process.env.TRYVOX_WEBHOOK_SECRET) {
  if (!secret) return false;
  const parts = Object.fromEntries(String(signatureHeader ?? '').split(',').map((p) => p.split('=', 2)));
  const t = Number(parts.t);
  if (!parts.v1 || !Number.isFinite(t) || Math.abs(Date.now() / 1000 - t) > 300) return false;
  const expected = crypto.createHmac('sha256', secret).update(`${parts.t}.`).update(rawBody).digest();
  const received = Buffer.from(parts.v1, 'hex');
  return received.length === expected.length && crypto.timingSafeEqual(received, expected);
}

// --- Tiny HTTP helpers for the examples' node:http servers ------------------

export function readBody(req) {
  return new Promise((resolve, reject) => {
    const chunks = [];
    req.on('data', (c) => chunks.push(c));
    req.on('end', () => resolve(Buffer.concat(chunks)));
    req.on('error', reject);
  });
}

export function send(res, status, body, type = 'application/json') {
  res.writeHead(status, { 'Content-Type': type });
  res.end(type === 'application/json' ? JSON.stringify(body) : body);
}

The app

platform.js
// TryVox as the telephony layer for your own app.
//
//   Browser  --POST /api/call-->  this backend  --TryVox API-->  phone call
//   TryVox   --POST /webhooks/tryvox-->  this backend  (call status)
//
// Run: npm run platform   (Node 20.6+; uses tryvox.js from this folder)

import http from 'node:http';
import { env, tryvox, isFromTryVox, readBody, send } from './tryvox.js';

const { TRYVOX_NUMBER, PUBLIC_URL } = env('TRYVOX_NUMBER', 'TRYVOX_WEBHOOK_SECRET', 'PUBLIC_URL');
const PORT = Number(process.env.PORT ?? 3000);

// Stands in for your database: request_uuid -> call record.
const calls = new Map();

// 1. Your backend asks TryVox to place the call.
async function placeCall(to) {
  const { data } = await tryvox('POST', '/v1/voice/accounts/{auth_id}/calls', {
    from: TRYVOX_NUMBER,
    to,
    answer_url: `${PUBLIC_URL}/webhooks/tryvox/answer`, // what to do when they pick up
    status_callback_url: `${PUBLIC_URL}/webhooks/tryvox`, // ringing / answered / hangup
    hangup_url: `${PUBLIC_URL}/webhooks/tryvox`, // final result
    webhook_secret: process.env.TRYVOX_WEBHOOK_SECRET, // TryVox signs this call's webhooks with it
  });
  return data; // { request_uuid, status: "queued", ... }
}

// 2. TryVox calls you back: ring, answered and hangup updates, and the final
// result. The same handler works for inbound calls on a number whose Voice
// Application points here.
function handleCallEvent(event) {
  const id = event.CallUUID;
  const call = calls.get(id) ?? { id, to: event.To, from: event.From, direction: event.Direction };

  if (event.Event === 'Hangup') {
    // Final result. Can arrive more than once, so just overwrite.
    Object.assign(call, { status: event.Status, duration: event.Billsec ?? 0, endedAt: event.EndTime, done: true });
  } else if (!call.done) {
    call.status = event.Status; // ringing | answered | hangup
  }
  calls.set(id, call);
  console.log(`[${id}] ${event.Event}: ${call.status}`);
}

// When the call is answered TryVox asks what to do. Reply with VoxML.
function answerVoxml() {
  return {
    voxml_version: '1.0',
    instructions: [
      { verb: 'Say', text: 'Hello! This is a test call from TryVox. Goodbye.', language: 'en-IN' },
      { verb: 'Hangup' },
    ],
  };
}

const page = `<!doctype html><meta charset="utf-8"><title>Call customer</title>
<input id="phone" placeholder="+919812345678"> <button id="call">Call customer</button>
<pre id="out"></pre>
<script>
  // The browser talks to YOUR backend only. TryVox credentials never reach it.
  document.getElementById('call').onclick = async () => {
    const res = await fetch('/api/call', {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({ phone: document.getElementById('phone').value }),
    });
    const call = await res.json();
    const out = document.getElementById('out');
    out.textContent = JSON.stringify(call, null, 2);
    if (!res.ok) return;
    const timer = setInterval(async () => {
      const latest = await (await fetch('/api/calls/' + call.id)).json();
      out.textContent = JSON.stringify(latest, null, 2);
      if (latest.done) clearInterval(timer);
    }, 2000);
  };
</script>`;

http
  .createServer(async (req, res) => {
    const url = new URL(req.url, 'http://localhost');
    try {
      if (req.method === 'GET' && url.pathname === '/') return send(res, 200, page, 'text/html');

      if (req.method === 'POST' && url.pathname === '/api/call') {
        const { phone } = JSON.parse((await readBody(req)).toString() || '{}');
        if (!/^\+[1-9]\d{6,14}$/.test(phone ?? '')) return send(res, 400, { error: 'phone must be E.164, e.g. +919812345678' });
        const data = await placeCall(phone);
        const call = { id: data.request_uuid, to: phone, status: data.status };
        calls.set(call.id, call);
        return send(res, 201, call);
      }

      if (req.method === 'GET' && url.pathname.startsWith('/api/calls/')) {
        const call = calls.get(url.pathname.slice('/api/calls/'.length));
        return call ? send(res, 200, call) : send(res, 404, { error: 'unknown call' });
      }

      if (req.method === 'POST' && url.pathname.startsWith('/webhooks/tryvox')) {
        const raw = await readBody(req);
        if (!isFromTryVox(req.headers['x-tryvox-signature'], raw)) return send(res, 401, { error: 'bad signature' });
        if (url.pathname === '/webhooks/tryvox/answer') return send(res, 200, answerVoxml());
        handleCallEvent(JSON.parse(raw.toString()));
        return send(res, 200, { ok: true });
      }

      send(res, 404, { error: 'not found' });
    } catch (err) {
      console.error(err);
      send(res, err.status ?? 500, { error: err.message, code: err.code });
    }
  })
  .listen(PORT, () => console.log(`Open http://localhost:${PORT}  (webhooks: ${PUBLIC_URL}/webhooks/tryvox)`));
.env.example
# Dashboard → Account → API keys → Create. The Auth ID and the Key (shown once).
TRYVOX_AUTH_ID=TJxxxxxxxx
TRYVOX_AUTH_TOKEN=your-auth-token

# An active TryVox number on your account, in E.164.
TRYVOX_NUMBER=+918045671234

# Any long random string you choose. TryVox signs your calls' webhooks with it.
# Generate one with: openssl rand -hex 32
TRYVOX_WEBHOOK_SECRET=

# Public HTTPS address of this server, e.g. your ngrok URL. No trailing slash.
PUBLIC_URL=https://abc123.ngrok.app

PORT=3000

# crm.js: the phone to connect when a lead answers (yours, for testing).
AGENT_PHONE=+919876543210

# reminder.js: the AI integration's id (GET /v1/ai/integrations) and who to call.
INTEGRATION_ID=
TEST_PHONE=+919812345678
package.json
{
  "name": "tryvox-examples",
  "private": true,
  "type": "module",
  "engines": { "node": ">=20.6" },
  "scripts": {
    "platform": "node --env-file=.env platform.js",
    "crm": "node --env-file=.env crm.js",
    "webhooks": "node --env-file=.env webhooks-express.js",
    "call-results": "node --env-file=.env call-results.js",
    "reminder": "node --env-file=.env reminder.js"
  },
  "dependencies": {
    "express": "^4.21.2"
  }
}

Then:

cp .env.example .env    # fill in your values
ngrok http 3000         # another terminal; put the https URL in PUBLIC_URL
npm run platform

Open http://localhost:3000, enter a phone number in E.164 (+919812345678), and click Call customer.

Expected result

The phone rings, says "Hello! This is a test call from TryVox. Goodbye.", and hangs up. The page updates on its own:

{ "id": "550e8400-e29b-41d4-a716-446655440000", "to": "+919812345678", "status": "queued" }
{ "id": "550e8400-e29b-41d4-a716-446655440000", "to": "+919812345678", "status": "completed", "duration": 6, "done": true }

The terminal shows each event as it arrives:

[550e8400-…] Status: ringing
[550e8400-…] Status: answered
[550e8400-…] Hangup: completed

How the pieces fit

Frontend → your backend. The browser only ever calls /api/call on your own server:

await fetch('/api/call', {
  method: 'POST',
  headers: { 'Content-Type': 'application/json' },
  body: JSON.stringify({ phone: '+919812345678' }),
});

Always call TryVox from your backend. Never expose your TryVox credentials in frontend code. Anyone who has your Auth Token can place calls on your account.

Your backend → TryVox. placeCall() sends one Make a Call request through tryvox(), which adds HTTP Basic auth (Auth ID and Auth Token). TryVox answers 201 with a request_uuid. Save it next to your own record, such as the lead or ticket. Every later event for this call carries the same ID as CallUUID.

TryVox → your backend. Three URLs on the request tell TryVox where to reach you:

FieldWhen TryVox calls itWhat you return
answer_urlThe call is answeredVoxML: what the call should do
status_callback_urlRinging, answered, hung up200
hangup_urlThe call has ended, with its result and duration200

Every request is signed with your webhook_secret. isFromTryVox() rejects anything that isn't. Receive Call Events explains the signature.

Your database. The calls map stands in for it. Key your rows on request_uuid, and treat the Hangup event as the final result.

Next step

  • Ring a person or an AI agent instead of reading a message: change answerVoxml() to use Dial or Stream.
  • Receive calls with the same server: Receive Calls.
  • After the call, fetch history and audio: Call Records (GET /v1/account/{auth_id}/cdr/{uuid}) and Recordings (?call_uuid={request_uuid}).

Troubleshooting

ProblemFix
403 KYC_REQUIREDKYC isn't approved yet. Dashboard → Compliance (KYC).
402 INSUFFICIENT_BALANCETop up in Billing → Wallet.
201, but the phone never ringsTRYVOX_NUMBER must be an active number on your account. A number you don't own is accepted and then fails without a webhook. Check it with Get Call.
The call connects and then says "An application error has occurred"TryVox couldn't fetch your answer_url. Is PUBLIC_URL correct, public, and HTTPS? It must answer within 15 seconds.
Every webhook gets 401 bad signatureTRYVOX_WEBHOOK_SECRET changed after the call was placed, or your server's clock is more than 5 minutes off.

On this page