Skip to main content
Version: Next

WebSockets

Event Publisher delivers real-time events over a WebSocket connection that your client opens to PBXware. Instead of hosting an endpoint for PBXware to call, your client connects and receives each event the moment it happens.

Scope, event filtering and the event envelope apply to both delivery methods and are described in the Event Publisher overview.


How It Works​

  1. Create a subscription — provide the events to subscribe to; PBXware returns the subscription id and the url to connect to
  2. Connect — open a WebSocket connection to that url with the same API key that created the subscription
  3. Receive events — each matched event arrives as one text message containing the event envelope, the same JSON body a webhook receives

No retries: Delivery is live only. Each event is sent once to the connections open at that moment; events that occur while no connection is open are dropped and are not replayed. If you need failed deliveries retried, use Webhooks.

Because your client opens the connection, WebSockets work where PBXware cannot reach you — behind a firewall or NAT, with no public endpoint. The connection must be opened from a server-side application: the API key is sent in the Authorization header, which the browser WebSocket API cannot set.


Key Concepts​

Connection authentication — Only an API key can create a subscription. Connect to the url exactly as returned, sending the same API key as a Bearer token. Connecting to a subscription that no longer exists returns 404.

Staying connected — PBXware sends a ping every 30 seconds and closes a connection that does not answer; WebSocket libraries reply automatically while your code keeps reading. Process events quickly — a client that falls behind is disconnected. Every open connection on a subscription receives every event.

Subscription lifetime — Subscriptions are kept in memory: one with no open connection for about 10 minutes is deleted, and all are lost when the service restarts. Every close PBXware initiates carries its reason as text, except the one for a message from your client over 512 bytes; a dropped connection has none. After subscription deleted, subscription was removed, subscription expired after being idle or service shutting down, or a 404 when connecting, create a new subscription — after a restart, once the service is back. After tenant was removed or every subscribed event was removed, the subscription cannot be created again as it was. After any other reason, or a dropped connection, reconnect.

See the Event Publisher API Reference for all websocket subscription management endpoints.


Example: Receiving Events​

This client creates a subscription, connects, passes each event to handleEvent, and when the connection closes reconnects, creates a new subscription, or stops, depending on the close reason. While PBXware is unreachable or restarting, it keeps retrying the create. Set PBXWARE_URL (for example https://pbxware.domain.com), PBXWARE_API_KEY, and TENANT_CODE (default on Contact Center).

Requires Node.js 18 or later. Save it as an ES module, for example client.mjs, and install the ws package: npm install ws

import WebSocket from 'ws';

const baseUrl = process.env.PBXWARE_URL;
const apiKey = process.env.PBXWARE_API_KEY;
const tenantCode = process.env.TENANT_CODE;

const RECREATE_REASONS = new Set([
'subscription deleted',
'subscription was removed',
'subscription expired after being idle',
'service shutting down',
]);
const FINAL_REASONS = new Set([
'tenant was removed',
'every subscribed event was removed',
]);

const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));

function handleEvent(event) {
console.log(event.event, event.event_id);
}

async function createSubscription() {
for (;;) {
const response = await fetch(
`${baseUrl}/api/org/${tenantCode}/v2/event-publisher/websockets/subscription`,
{
method: 'POST',
headers: { Authorization: `Bearer ${apiKey}`, 'Content-Type': 'application/json' },
body: JSON.stringify({
name: 'Call feed',
events: ['call.event_call_started', 'call.event_call_finished'],
}),
},
).catch(() => null);

if (response?.ok) {
return (await response.json()).url;
}
if (response && response.status < 500) {
throw new Error(`Create failed: ${response.status} ${await response.text()}`);
}
await sleep(5000);
}
}

function listen(url) {
return new Promise((resolve) => {
const ws = new WebSocket(url, { headers: { Authorization: `Bearer ${apiKey}` } });

ws.on('message', (data) => handleEvent(JSON.parse(data.toString())));
ws.on('unexpected-response', (request, response) => {
resolve({ status: response.statusCode });
request.destroy();
});
ws.on('close', (code, reason) => resolve({ reason: reason.toString() }));
ws.on('error', () => {});
});
}

let url = await createSubscription();
for (;;) {
const { status, reason } = await listen(url);
console.log('Disconnected:', status ?? reason);

if (status === 401 || status === 403 || FINAL_REASONS.has(reason)) {
throw new Error(`Stopped: ${status ?? reason}`);
}
if (status === 404 || RECREATE_REASONS.has(reason)) {
url = await createSubscription();
continue;
}
await sleep(5000);
}

The Call Events and SMS Events pages show what handleEvent can do with each event.