Event Subscriptions via Websocket
Overview
This service allows connections to Dialpad events using WebSocket, including from frontend applications. It provides the same events as the current Webhook-based event subscription service, without requiring your own Webhook or backend service.
Authentication
You will need an access token/API Key to use this functionality. Please refer to the authentication guide if you need to learn how to generate an access token/API Key.
Steps to Use Events with WebSockets
Listening to events via WebSocket is a 3-step process.
Step 1. Create WebSocket and Event Subscriptions
Similar to event logging via Webhook, you need to create a WebSocket entity and an event subscription via our api before logging.
- First, create a WebSocket by using our Create a WebSocket API, and note down the
idandwebsocket_urlthat is returned in the response; you'll need them later. - Then, use any of the Event Subscription APIs to create a new Event Subscription. Use the
idreturned in the previous step to provide as theendpoint_idin the Create request.
Note: You need to use the same api_key throughout.
Step 2. Connect from the client
From the client where you want to connect to the WebSocket, use the value of websocket_urlreturned in Step 1.1 to open a connection.
The URL patterns for the WebSocket service are:
| Environment | URL |
|---|---|
| Sandbox | wss://platform-websockets-5bwy6zprxa-uc.a.run.app/events/<token> |
| Production | wss://platform-websockets-6kqb5ajsla-uc.a.run.app/events/<token> |
Here, the <token> is a temporary token encoded when you create a new WebSocket or event subscription, which is included in the websocket_url field of the response.
The token will expire in 1 hour after issue. To refresh the token, make a GET request to the corresponding websocket or event subscription endpoint.
Notes:
- If you are using a token from an event subscription api, the token will build a connection that access to this event subscription only. If you get the token from a WebSocket api, the token will allow you to receive payloads from all event subscriptions under this WebSocket entity.
- You may be using our old WebSocket service at https://platform-websockets.uw.r.appspot.com/. That service is deprecated, although still accessible. We recommend you use the new service for security and future updates. We may stop the deprecated service at any time.
- WSS is recommended for security.
Step 3. Process Events and Reconnect
Once you open a new WebSocket connection to the URL from your client, you will start receiving events as they occur. As long as the connection is maintained, event logging payloads will be sent to the client when they are available.
Reconnecting
The WebSocket connection will be disconnected after 1 hour to ensure the connections remain secure.
Once the connection expires, use the GET Websockets by ID API to get a new URL to connect to.
To know when to reconnect, you can either rely on the socker.onclose() callback, or add a timer in your implementation to reconnect as a failsafe measure.
Sample Code
Here's a sample JavaScript code explaining how you could handle the socket connection. This code assumes it will be run on the web frontend, inside a browser:
// The URL to your service which handles the authenticated API requests to get fresh WebSocket URLs to listen to
const API_URL = 'https://www.example.com/websocketUrl';
let socket = null;
/**
* Main function to initialize or re-initialize the connection
*/
async function startEventStream() {
console.log("Initializing stream...");
try {
// 1. Fetch the fresh URL from the backend
const response = await fetch(API_URL);
if (!response.ok) throw new Error('Error while fetching WebSocket URL');
// Parse the WebSocket URL from the response
const { websocket_url } = await response.json();
// 2. Open the connection
socket = new WebSocket(websocket_url);
// 3. Define Event Listeners
socket.onopen = () => {
console.log("Connected to WebSocket successfully.");
};
// 4. Process Events
socket.onmessage = (event) => {
const data = JSON.parse(event.data);
processIncomingEvents(data);
};
// 5. Handle connection closure
socket.onclose = (event) => {
console.warn("Connection closed (likely 1-hour expiry). Reconnecting...");
// Cleanup current instance
socket = null;
// Recursive call to get a new URL and reconnect
startEventStream();
};
socket.onerror = (error) => {
console.error("Socket encountered an error:", error);
socket.close(); // This triggers the onclose logic above
};
} catch (err) {
console.error("Initialization failed:", err);
}
}
/**
* Handle the data from the incoming events
*/
function processIncomingEvents(data) {
// Process the Event's data
}
/**
* Clean disconnect for page navigation
*/
function handlePageExit() {
if (socket) {
console.log("Closing connection before page exit.");
socket.onclose = null; // Prevent the reconnection loop
socket.close();
}
}
// Start on load
startEventStream();
// Listen for tab close or navigation
window.addEventListener('beforeunload', handlePageExit);WebSocket Demo
A demo WebSocket application is available for production (live) and for sandbox.
Features
- Multiple clients can be connected to the same event subscription. As long as a valid api key is provided, you can receive the logging payloads in different clients.
- WebSocket subscriptions are independent of Webhook-based subscriptions, so both types of subscriptions can be created for the same target.
- You can monitor one event subscription in one client, or you can monitor all subscriptions under a single WebSocket (same as using a single Webhook for multiple subscriptions).
Updated 7 days ago