Overview
When you start a call with click-to-call, the audio goes through the Hipcall app on the agent's computer or phone. If you want agents to talk from inside your CRM tab instead, the browser has to connect to the Hipcall PBX itself. The @hipcall/webrtc-sdk package handles that connection.
The connection takes three steps:
- The user signs in with their Hipcall account and your app receives an
access_token(OAuth2). - The SDK uses that token to get a SIP token for the user from
POST /api/v3/sip/token. - The SDK connects to the PBX over WebSocket and sends a
REGISTERrequest with the SIP token. Once the PBX accepts it, the browser can make and receive calls.
This guide walks through those three steps. Placing and answering calls, mute and hold are in the second part of the series: How to Build a Browser Webphone with the Hipcall WebRTC SDK.
sequenceDiagram
actor Agent as Agent (browser)
participant Proxy as Your server (proxy)
participant API as Hipcall API
participant PBX as Hipcall PBX (WSS)
Agent->>API: Signs in with Hipcall
API-->>Agent: /callback?code=...
Agent->>Proxy: code
Proxy->>API: POST /oauth/token (+ client_secret)
API-->>Agent: access_token
Agent->>API: POST /api/v3/sip/token (through the proxy)
API-->>Agent: sip_username, wss_url, sip_token
Agent->>PBX: REGISTER
PBX-->>Agent: 200 OK
Before you start
You need:
- Node.js 20 or later (
node --version). - A Hipcall plan with API access. The user who signs in must have an extension.
- A Hipcall OAuth2 application with a
Client ID,Client SecretandRedirect URI. You can request these credentials from the Hipcall team. The application needs theprofile,email,offline_accessandcontacts:readscopes. - An HTTPS address. Browsers only allow microphone access and the crypto functions PKCE relies on over
https://or onlocalhost, and Hipcall requires an HTTPS redirect URI. During development, expose Vite's port 5173 with ngrok:
ngrok http 5173
Set the environment variables. HIPCALL_CLIENT_SECRET has no VITE_ prefix, so Vite leaves it out of the code it sends to the browser. The secret stays on the proxy server.
export HIPCALL_CLIENT_ID="..."
export HIPCALL_CLIENT_SECRET="..."
export VITE_HIPCALL_CLIENT_ID="$HIPCALL_CLIENT_ID"
export VITE_HIPCALL_REDIRECT_URI="https://your-tunnel.ngrok-free.dev/callback"
On Windows PowerShell:
$env:HIPCALL_CLIENT_ID = "..."
$env:HIPCALL_CLIENT_SECRET = "..."
$env:VITE_HIPCALL_CLIENT_ID = $env:HIPCALL_CLIENT_ID
$env:VITE_HIPCALL_REDIRECT_URI = "https://your-tunnel.ngrok-free.dev/callback"
HIPCALL_BASE_URL is optional. If you leave it unset, https://use.hipcall.com is used.
Your account's region
Hipcall runs two sets of servers: use.hipcall.com (global) and use.hipcall.com.tr (Türkiye). Tell the SDK which one your account is on with the region option:
| Account address | region |
HIPCALL_BASE_URL |
|---|---|---|
use.hipcall.com |
'global' (default) |
https://use.hipcall.com |
use.hipcall.com.tr |
'tr' |
https://use.hipcall.com.tr |
The examples in this guide use region: 'global'. region sets the SDK's sign-in and PBX addresses, and HIPCALL_BASE_URL sets where the proxy forwards requests. Both must point to the same region.
Step 1: Install the package and create the client
npm install @hipcall/webrtc-sdk
The browser cannot call Hipcall's token and API addresses directly, for two reasons. Hipcall does not allow cross-origin (CORS) requests from browsers on those addresses, and the token exchange needs client_secret, which must never reach the browser. So the requests go through a small proxy on your own server. Point tokenUrl and apiBaseUrl at the proxy routes:
import { HipcallClient } from '@hipcall/webrtc-sdk';
const state = sessionStorage.getItem('hipcall_oauth_state') ?? crypto.randomUUID();
sessionStorage.setItem('hipcall_oauth_state', state);
const client = new HipcallClient({
authorizeUrl: 'https://use.hipcall.com/oauth/authorize',
tokenUrl: '/hipcall-oauth/token',
apiBaseUrl: '/hipcall-api',
clientId: import.meta.env.VITE_HIPCALL_CLIENT_ID,
redirectUri: import.meta.env.VITE_HIPCALL_REDIRECT_URI,
state,
});
The state value travels to Hipcall during sign-in and comes back with the redirect. The SDK checks that it matches what it sent. Keeping it in sessionStorage means the same value is still there when the user returns from the Hipcall sign-in page and the app reloads.
Step 2: Sign the user in with OAuth2
When the user presses the sign-in button, call client.loginWithOAuth(). The SDK creates a random code_verifier, saves it in sessionStorage and sends the user to the Hipcall sign-in page:
GET https://use.hipcall.com/oauth/authorize
?response_type=code
&client_id=YOUR_CLIENT_ID
&redirect_uri=https%3A%2F%2Fyour-tunnel.ngrok-free.dev%2Fcallback
&scope=profile+email+offline_access+contacts%3Aread
&state=8f9d2a1c-4b3e-4f1a-9c2d-1a2b3c4d5e6f
&code_challenge=E9Melhoa2OwvFrGMTJguCHaoeK1t8URWbuGJSstw-cM
&code_challenge_method=S256
After the user signs in and grants access, Hipcall redirects the browser to /callback?code=...&state=.... On that page, clear the address bar first, then pass the code to client.handleOAuthCallback():
const url = new URL(window.location.href);
const code = url.searchParams.get('code');
const returnedState = url.searchParams.get('state');
window.history.replaceState({}, document.title, '/');
if (code) {
const tokens = await client.handleOAuthCallback(code, returnedState);
console.log('Access token received, expires_in (s):', tokens.expires_in);
}
The SDK sends the code and the code_verifier to your proxy. The proxy adds client_id and client_secret and forwards the request to Hipcall, which receives this:
POST https://use.hipcall.com/oauth/token
Content-Type: application/x-www-form-urlencoded
Accept: application/json
grant_type=authorization_code&code=AUTH_CODE&redirect_uri=https%3A%2F%2Fyour-tunnel.ngrok-free.dev%2Fcallback&code_verifier=PKCE_VERIFIER&client_id=YOUR_CLIENT_ID&client_secret=YOUR_CLIENT_SECRET
If the exchange succeeds, Hipcall returns 200 OK with the tokens:
{
"access_token": "SFMyNTY.g2gD...",
"token_type": "Bearer",
"expires_in": 3599,
"refresh_token": "YTFjTxd_Mfen...",
"scope": "profile email offline_access contacts:read"
}
The SDK stores this response in localStorage under hipcall_sdk:tokens, so the user does not have to sign in again after a page refresh.
Step 3: Get a SIP token and register with the PBX
Once you have an access_token, call client.connectSIP(). The SDK first sends a request to POST /api/v3/sip/token:
POST https://use.hipcall.com/api/v3/sip/token
Authorization: Bearer SFMyNTY.g2gD...
Content-Type: application/json
Accept: application/json
{}
With an empty body ({}), Hipcall returns the SIP details of the user who owns the token:
{
"user_id": 4200,
"expires_at": 1794317238,
"sip_username": "997549",
"wss_url": "wss://mgw.hipcall.com:8443",
"sip_realm": "sip.hipcall.com",
"sip_token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9..."
}
Two fields matter here. wss_url is the PBX address the browser connects to. sip_token is a short-lived token the PBX uses to authenticate the user. expires_at gives its expiry time as a Unix timestamp.
The SDK opens a WebSocket connection to wss_url and sends REGISTER, with sip_token in an Authorization: Bearer header. You can watch the SIP messages on the WebSocket with client.on('sipLog', ...):
REGISTER sip:sip.hipcall.com SIP/2.0
Via: SIP/2.0/WSS 8pdcgc4dt0rv.invalid;branch=z9hG4bK1670014
Max-Forwards: 69
To: <sip:997549@sip.hipcall.com>
From: <sip:997549@sip.hipcall.com>;tag=aoi857p9q4
Call-ID: j6s9ml05favqpich5hphj6
CSeq: 1 REGISTER
Authorization: Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...
Expires: 300
Contact: <sip:59pfd178@8pdcgc4dt0rv.invalid;transport=ws>;+sip.ice;reg-id=1;expires=300
User-Agent: hipcall-webrtc-sdk/0.1
Content-Length: 0
When the PBX accepts the registration, it replies 200 OK and the SDK fires the registered event:
SIP/2.0 200 OK
Via: SIP/2.0/WSS 8pdcgc4dt0rv.invalid;received=203.0.113.10;rport=6118;branch=z9hG4bK1670014
To: <sip:997549@sip.hipcall.com>;tag=5051.87444f4ef98372c92f67f1594c4993d9
From: <sip:997549@sip.hipcall.com>;tag=aoi857p9q4
Call-ID: j6s9ml05favqpich5hphj6
CSeq: 1 REGISTER
Contact: <sip:59pfd178@8pdcgc4dt0rv.invalid;transport=ws>;expires=60;received="sip:203.0.113.10:6118;transport=wss"
Server: OpenSIPS (3.4.10 (x86_64/linux))
Content-Length: 0
Expires: 300 means the registration is valid for 300 seconds. The SDK renews it before it runs out.
The full script
Create the five files below in an empty folder. The webphone in the second part of the series builds on them.
package.json:
{
"name": "hipcall-webphone-demo",
"private": true,
"type": "module",
"scripts": {
"proxy": "node server.mjs",
"dev": "vite"
},
"dependencies": {
"@hipcall/webrtc-sdk": "^1.0.0"
},
"devDependencies": {
"typescript": "^5.6.3",
"vite": "^5.4.10"
}
}
server.mjs is the proxy. It adds client_secret to the token exchange and forwards /hipcall-api/* requests to the Hipcall API:
import { createServer } from 'node:http';
function env(name) {
const value = process.env[name];
if (!value) {
throw new Error(`${name} is not set.`);
}
return value;
}
const clientId = env('HIPCALL_CLIENT_ID');
const clientSecret = env('HIPCALL_CLIENT_SECRET');
const origin = process.env.HIPCALL_BASE_URL ?? 'https://use.hipcall.com';
const port = Number(process.env.PORT ?? 8787);
async function readBody(req) {
const chunks = [];
for await (const chunk of req) {
chunks.push(chunk);
}
return Buffer.concat(chunks);
}
async function reply(res, upstream) {
res.writeHead(upstream.status, {
'Content-Type': upstream.headers.get('content-type') ?? 'application/json',
});
res.end(Buffer.from(await upstream.arrayBuffer()));
}
const server = createServer(async (req, res) => {
try {
const url = new URL(req.url ?? '/', 'http://localhost');
// Token exchange: attach client_id and client_secret on the server so they never reach the browser.
if (req.method === 'POST' && url.pathname === '/hipcall-oauth/token') {
const params = new URLSearchParams((await readBody(req)).toString());
params.set('client_id', clientId);
params.set('client_secret', clientSecret);
await reply(
res,
await fetch(`${origin}/oauth/token`, {
method: 'POST',
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
Accept: 'application/json',
},
body: params,
}),
);
return;
}
// API requests: /hipcall-api/sip/token -> https://use.hipcall.com/api/v3/sip/token
if (url.pathname.startsWith('/hipcall-api/')) {
const path = url.pathname.slice('/hipcall-api'.length);
const hasBody = req.method !== 'GET' && req.method !== 'HEAD';
await reply(
res,
await fetch(`${origin}/api/v3${path}${url.search}`, {
method: req.method,
headers: {
Authorization: req.headers.authorization ?? '',
'Content-Type': req.headers['content-type'] ?? 'application/json',
Accept: 'application/json',
},
body: hasBody ? await readBody(req) : undefined,
}),
);
return;
}
res.writeHead(404).end();
} catch (error) {
res.writeHead(502, { 'Content-Type': 'application/json' });
res.end(JSON.stringify({ error: 'proxy_error', error_description: String(error) }));
}
});
server.listen(port, () => {
console.log(`Hipcall proxy listening on http://localhost:${port}`);
});
vite.config.ts:
import { defineConfig } from 'vite';
export default defineConfig({
server: {
port: 5173,
host: true,
allowedHosts: ['.ngrok-free.dev', '.ngrok.app'],
proxy: {
'/hipcall-oauth': 'http://localhost:8787',
'/hipcall-api': 'http://localhost:8787',
},
},
});
index.html:
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8" />
<title>Hipcall WebRTC SDK</title>
</head>
<body>
<p>Status: <strong id="status">Disconnected</strong></p>
<button id="login" type="button">Sign in with Hipcall</button>
<button id="logout" type="button" hidden>Sign out</button>
<pre id="log"></pre>
<script type="module" src="/src/main.ts"></script>
</body>
</html>
src/main.ts:
import { HipcallClient } from '@hipcall/webrtc-sdk';
function env(name: string): string {
const value = import.meta.env[name];
if (!value) {
throw new Error(`${name} is not set.`);
}
return value;
}
const statusEl = document.getElementById('status')!;
const loginBtn = document.getElementById('login') as HTMLButtonElement;
const logoutBtn = document.getElementById('logout') as HTMLButtonElement;
const logEl = document.getElementById('log')!;
function writeLog(line: string): void {
logEl.textContent += `${line}\n`;
}
const state = sessionStorage.getItem('hipcall_oauth_state') ?? crypto.randomUUID();
sessionStorage.setItem('hipcall_oauth_state', state);
const client = new HipcallClient({
authorizeUrl: 'https://use.hipcall.com/oauth/authorize',
tokenUrl: '/hipcall-oauth/token',
apiBaseUrl: '/hipcall-api',
clientId: env('VITE_HIPCALL_CLIENT_ID'),
redirectUri: env('VITE_HIPCALL_REDIRECT_URI'),
state,
});
client.on('connecting', () => {
statusEl.textContent = 'Connecting...';
});
client.on('registered', () => {
statusEl.textContent = 'Registered';
loginBtn.hidden = true;
logoutBtn.hidden = false;
writeLog('Registered with the Hipcall PBX.');
});
client.on('registrationFailed', ({ cause, code }) => {
statusEl.textContent = `Registration failed: ${cause} (${code ?? ''})`;
});
client.on('sipLog', ({ direction, message }) => {
const firstLine = message.split('\r\n')[0];
writeLog(`[${direction.toUpperCase()}] ${firstLine}`);
});
loginBtn.addEventListener('click', () => {
void client.loginWithOAuth();
});
logoutBtn.addEventListener('click', () => {
client.logout();
statusEl.textContent = 'Disconnected';
loginBtn.hidden = false;
logoutBtn.hidden = true;
});
async function init(): Promise<void> {
const url = new URL(window.location.href);
if (url.pathname === '/callback') {
const code = url.searchParams.get('code');
const error = url.searchParams.get('error');
window.history.replaceState({}, document.title, '/');
if (error) {
writeLog(`OAuth error: ${error}`);
return;
}
if (code) {
await client.handleOAuthCallback(code, url.searchParams.get('state'));
await client.connectSIP();
}
return;
}
if (client.isAuthenticated) {
await client.connectSIP();
}
}
init().catch((err) => {
writeLog(`Error: ${err instanceof Error ? err.message : String(err)}`);
});
Install the dependencies and start the proxy:
npm install
npm run proxy
Start Vite in a second terminal:
npm run dev
Open your ngrok address (https://your-tunnel.ngrok-free.dev) in the browser, not http://localhost:5173, and select Sign in with Hipcall. Using the ngrok address from the start matters because each address has its own sessionStorage. If sign-in starts on localhost, the state and code_verifier are missing when the redirect comes back to ngrok.
After you grant access, the log shows REGISTER sip:sip.hipcall.com SIP/2.0 followed by SIP/2.0 200 OK, and the status reads Registered.
When it fails
403 Forbidden: permission_denied (POST /api/v3/sip/token)
If you send a user_id in the body, you may get:
{
"error": "permission_denied",
"message": "You don't have permission to generate tokens for other users"
}
An OAuth2 token can only create a SIP token for its own user. Sending another user's ID returns this error. For the signed-in user, send an empty body ({}). When client.connectSIP() gets this error, it retries with an empty body.
400 Bad Request: invalid_grant (POST /oauth/token)
{
"error": "invalid_grant",
"error_description": "The provided authorization grant is invalid, expired, revoked, does not match the redirection URI used in the authorization request, or was issued to another client."
}
There are three likely causes:
- The same
codewas sent twice. Codes are single-use. Callwindow.history.replaceState({}, document.title, '/')beforehandleOAuthCallbackso a page refresh does not send the code again. - Sign-in started on
localhostand the redirect came back to the ngrok address. Each address has its ownsessionStorage, so thecode_verifiercannot be found. Open the app on the ngrok address from the start. VITE_HIPCALL_REDIRECT_URIdoes not match the address registered with Hipcall exactly. Even a trailing/counts.
401 Unauthorized
When the access_token expires, the API returns:
{
"errors": {
"detail": "Not authorized. Check your API token is valid and not expired."
}
}
If you request the offline_access scope, Hipcall also returns a refresh_token. Before the SDK asks for a SIP token, it checks whether the access_token has expired and, if so, uses the refresh_token to get a new one. Without a refresh_token, the user has to sign in again.
registrationFailed, or REGISTER gets no reply
- Check that the client connects to the
wss_urlfrom the/api/v3/sip/tokenresponse.client.connectSIP()takes it from the response for you. If you usesetManualCredentials(), passwss://mgw.hipcall.com:8443inwsServers. - The
sip_tokenmay have expired (expires_at). Callawait client.fetchSipCredentials()to get a new SIP token, thenawait client.connectSIP()to reconnect.
Parameter reference
HipcallClient options
| Parameter | Type | Required | Description |
|---|---|---|---|
clientId |
string | yes | OAuth2 Client ID. |
redirectUri |
string | yes | Redirect URI registered with Hipcall. |
tokenUrl |
string | no | Token exchange address. In the browser, use the proxy route (/hipcall-oauth/token). |
apiBaseUrl |
string | no | API base address. In the browser, use the proxy route (/hipcall-api). |
authorizeUrl |
string | no | Default: https://use.hipcall.com/oauth/authorize. |
state |
string | no | Value that goes to Hipcall and back during sign-in. Generate a random one per session. |
scope |
string | no | Default: profile email offline_access contacts:read. |
usePKCE |
boolean | no | Default: true. |
userId |
number | string | no | User to request the SIP token for. If empty, the token's owner is used. |
wsUrl |
string | no | Fallback address used when /sip/token returns no wss_url. |
registerExpires |
number | no | Registration lifetime in seconds. Default: 300. |
authMode |
'password' | 'bearer' | 'both' |
no | How sip_token is sent to the PBX. Default: 'both' (as the password and in an Authorization: Bearer header). |
POST /api/v3/sip/token
Request body:
| Field | Type | Required | Description |
|---|---|---|---|
user_id |
integer | no | User to create the SIP token for. Send {} for your own user. |
Response:
| Field | Type | Description |
|---|---|---|
user_id |
integer | User the token belongs to. |
expires_at |
integer | When the SIP token expires (Unix timestamp, seconds). |
sip_username |
string | SIP username on the PBX. |
sip_realm |
string | SIP domain. |
wss_url |
string | PBX WebSocket address to connect to. |
sip_token |
string | Token the PBX uses to authenticate the user. |
Next steps
- Place and answer calls over this connection in How to Build a Browser Webphone with the Hipcall WebRTC SDK.
- Find every endpoint in the Hipcall API Reference.
- Ask questions in the Hipcall Community.