Overview
In the first part of this series, How to Set Up the Hipcall WebRTC SDK with OAuth2 and SIP Tokens, we registered the browser with the Hipcall PBX. A registered browser can now work like a phone: it can dial out, take incoming calls and put a call on hold.
This guide builds a simple webphone screen on top of that connection. The screen lets the agent:
- Type a number and place a call
- Answer or reject an incoming call
- Mute, hold and send keypad tones (DTMF)
- Pick a speaker or headset
- Fetch the call record from the API when the call ends
sequenceDiagram
actor Agent as Agent (browser)
participant PBX as Hipcall PBX (WSS)
participant Customer as Customer phone
participant API as Hipcall API
Agent->>PBX: INVITE (places the call)
PBX->>Customer: Rings the number
PBX-->>Agent: 180 Ringing
Customer-->>PBX: Answers
PBX-->>Agent: 200 OK (audio starts)
Agent->>PBX: BYE (hangs up)
Agent->>API: GET /api/v3/calls
API-->>Agent: Call record
Before you start
You need:
- The setup from the first part, working:
package.json,server.mjsandvite.config.ts. - An active outbound number assigned to the signed-in user. The person you call sees this number. Check it in the dashboard under
Settings > Telephony > Phone Numbers (Ayarlar > Telefon Sistemi > Telefon Numaraları). - A microphone. The browser asks for microphone permission the first time.
As in part one, the examples use region: 'global'. If your account is on use.hipcall.com.tr, use region: 'tr'.
Step 1: Place a call
When the agent presses Call, open the microphone first, then pass the number and the audio stream to client.call():
callButton.addEventListener('click', async () => {
let stream: MediaStream | undefined;
try {
stream = await navigator.mediaDevices.getUserMedia({ audio: true });
client.call(numberInput.value, stream);
} catch (error) {
stream?.getTracks().forEach((track) => track.stop());
console.error(error);
}
});
Open the microphone inside the click handler. Browsers can block audio and microphone access that starts without a user click.
The SDK turns the number into a SIP address and sends an INVITE to the PBX. In sipLog it looks like this:
INVITE sip:+447700XXXXXX@sip.hipcall.com SIP/2.0
Via: SIP/2.0/WSS 8pdcgc4dt0rv.invalid;branch=z9hG4bK5587736
To: <sip:+447700XXXXXX@sip.hipcall.com>
From: <sip:997549@sip.hipcall.com>;tag=s3neg3hms0
Call-ID: rurcjplv7a8k364f81bj
CSeq: 1403 INVITE
Authorization: Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...
Content-Type: application/sdp
User-Agent: hipcall-webrtc-sdk/0.1
Calls to mobile phones
Some mobile carriers reject the call when the browser's audio description (SDP) is sent unchanged. The phone rings briefly, shows a video call warning, and the call drops with 488 Not Acceptable Here.
To prevent this, the SDK changes the SDP before the INVITE goes out. It removes the abs-send-time and transport-wide-cc lines that Chrome adds, and moves the PCMA and PCMU codecs, which phone networks commonly use, to the front of the list. You do not need to do anything for this.
Step 2: Handle incoming calls and in-call controls
Incoming calls
When a call comes in, the SDK plays a ringtone and fires incomingCall. The event carries the caller's number (remoteNumber) and, if available, their name (remoteName):
client.on('incomingCall', (call) => {
callerLabel.textContent = call.remoteName
? `${call.remoteName} (${call.remoteNumber})`
: call.remoteNumber;
incomingPanel.hidden = false;
});
Call client.answer() to answer and client.hangup() to reject:
answerButton.addEventListener('click', async () => {
const stream = await navigator.mediaDevices.getUserMedia({ audio: true });
stream.getTracks().forEach((track) => track.stop());
client.answer();
});
rejectButton.addEventListener('click', () => {
client.hangup();
});
If client.hangup() runs before the call is answered, the SDK sends 603 Decline. During a call, it ends the call with BYE.
Mute, hold and keypad tones
client.toggleMute() turns the microphone off and on. client.toggleHold() puts the call on hold or takes it off hold. client.sendDTMF() sends a keypad tone to an automated menu (IVR) on the other end:
muteButton.addEventListener('click', () => {
client.toggleMute();
});
holdButton.addEventListener('click', async () => {
await client.toggleHold();
});
client.on('muteChanged', ({ muted }) => {
muteButton.textContent = muted ? 'Unmute' : 'Mute';
});
client.on('holdChanged', ({ held }) => {
holdButton.textContent = held ? 'Resume' : 'Hold';
});
// Send digit "1" to an IVR menu
client.sendDTMF('1');
Update the button labels from the muteChanged and holdChanged events, so the screen stays correct when the state changes from the other side.
Choosing a speaker
client.getAudioDevices() lists the microphones and speakers on the computer. Call client.setAudioOutputDevice() to switch to the one the agent picks:
const devices = await client.getAudioDevices();
const speakers = devices.filter((d) => d.kind === 'audiooutput');
speakerSelect.addEventListener('change', async () => {
await client.setAudioOutputDevice(speakerSelect.value);
});
Step 3: Fetch the call record when the call ends
When a call ends, the SDK fires callEnded. At that point you can use the same access_token to call GET /api/v3/calls and get the latest call the PBX recorded. The request goes through the proxy from part one:
client.on('callEnded', async () => {
const raw = localStorage.getItem('hipcall_sdk:tokens');
if (!raw) return;
const { access_token } = JSON.parse(raw) as { access_token: string };
const response = await fetch('/hipcall-api/calls?limit=1&sort=started_at.desc', {
headers: { Authorization: `Bearer ${access_token}` },
});
const body = await response.json();
console.log('Latest call record:', body.data?.[0]);
});
A successful response (200 OK):
{
"data": [
{
"uuid": "e7850000-0000-4000-8000-0000000087e5",
"caller_number": "+442079XXXXXX",
"callee_number": "+447700XXXXXX",
"direction": "outbound",
"number_id": 943,
"user_id": 4200,
"started_at": "2026-11-11T11:20:04Z",
"answered_at": "2026-11-11T11:20:04Z",
"bridged_at": "2026-11-11T11:20:12Z",
"ended_at": "2026-11-11T11:20:35Z",
"call_duration": 23,
"missing_call": false,
"hangup_by": "user"
}
],
"meta": { "count": 1, "offset": 0, "limit": 1 }
}
call_duration is the length of the call in seconds. hangup_by shows who ended it.
The full script
Keep package.json, server.mjs and vite.config.ts from part one as they are. Replace index.html and src/main.ts with the versions below, and add src/phone.ts.
index.html:
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8" />
<title>Hipcall Webphone</title>
</head>
<body>
<p>Status: <strong id="status">Disconnected</strong> (<span id="timer">00:00</span>)</p>
<p id="message"></p>
<button id="login" type="button">Sign in with Hipcall</button>
<button id="logout" type="button" hidden>Sign out</button>
<hr />
<div>
<input id="number" type="tel" placeholder="+447700XXXXXX" />
<button id="call" type="button">Call</button>
<button id="hangup" type="button">Hang up</button>
<button id="mute" type="button">Mute</button>
<button id="hold" type="button">Hold</button>
</div>
<div id="keypad"></div>
<div id="incoming" hidden>
<p>Incoming call: <strong id="incoming-number"></strong></p>
<button id="answer" type="button">Answer</button>
<button id="reject" type="button">Reject</button>
</div>
<div>
<label for="output">Speaker:</label>
<select id="output"></select>
</div>
<pre id="cdr"></pre>
<script type="module" src="/src/main.ts"></script>
</body>
</html>
src/phone.ts wires every button on the webphone screen to the SDK and its events:
import type { HipcallClient } from '@hipcall/webrtc-sdk';
function byId<T extends HTMLElement>(id: string): T {
const element = document.getElementById(id);
if (!element) {
throw new Error(`#${id} not found. Check index.html.`);
}
return element as T;
}
function formatDuration(totalSeconds: number): string {
const minutes = Math.floor(totalSeconds / 60);
const seconds = totalSeconds % 60;
return `${String(minutes).padStart(2, '0')}:${String(seconds).padStart(2, '0')}`;
}
export function setupPhone(client: HipcallClient): void {
const status = byId('status');
const message = byId('message');
const numberInput = byId<HTMLInputElement>('number');
const timerLabel = byId('timer');
const muteButton = byId<HTMLButtonElement>('mute');
const holdButton = byId<HTMLButtonElement>('hold');
const incoming = byId('incoming');
const incomingNumber = byId('incoming-number');
const keypad = byId('keypad');
const output = byId<HTMLSelectElement>('output');
const cdrOutput = byId('cdr');
let timerId: number | undefined;
const showError = (error: unknown) => {
message.textContent = error instanceof Error ? `${error.name}: ${error.message}` : String(error);
};
const startTimer = (startedAt: number) => {
window.clearInterval(timerId);
const tick = () => {
timerLabel.textContent = formatDuration(Math.floor((Date.now() - startedAt) / 1000));
};
tick();
timerId = window.setInterval(tick, 1000);
};
const stopTimer = () => {
window.clearInterval(timerId);
timerLabel.textContent = '00:00';
};
const fillOutputDevices = async () => {
const devices = await client.getAudioDevices();
output.replaceChildren(
...devices
.filter((device) => device.kind === 'audiooutput')
.map((device) => new Option(device.label, device.deviceId)),
);
};
const fetchLatestCall = async () => {
const raw = localStorage.getItem('hipcall_sdk:tokens');
if (!raw) return;
const { access_token } = JSON.parse(raw) as { access_token: string };
const res = await fetch('/hipcall-api/calls?limit=1&sort=started_at.desc', {
headers: { Authorization: `Bearer ${access_token}` },
});
cdrOutput.textContent = await res.text();
};
client.on('registered', () => {
status.textContent = 'Ready';
void fillOutputDevices();
});
client.on('unregistered', () => {
status.textContent = 'Disconnected';
});
client.on('registrationFailed', ({ cause, code }) => {
status.textContent = `Registration failed: ${cause} ${code ?? ''}`;
});
client.on('callConnecting', (call) => {
message.textContent = '';
status.textContent = `Calling: ${call.remoteNumber}`;
});
client.on('callRinging', () => {
status.textContent = 'Ringing...';
});
client.on('callConnected', (call) => {
status.textContent = `In call: ${call.remoteNumber}`;
startTimer(call.startedAt ?? Date.now());
void fillOutputDevices();
});
client.on('incomingCall', (call) => {
incomingNumber.textContent = call.remoteName
? `${call.remoteName} (${call.remoteNumber})`
: call.remoteNumber;
incoming.hidden = false;
});
client.on('callFailed', ({ cause }) => {
message.textContent = `Call failed: ${cause}`;
});
client.on('callEnded', () => {
stopTimer();
incoming.hidden = true;
status.textContent = client.isRegistered ? 'Ready' : 'Disconnected';
void fetchLatestCall();
});
client.on('muteChanged', ({ muted }) => {
muteButton.textContent = muted ? 'Unmute' : 'Mute';
});
client.on('holdChanged', ({ held }) => {
holdButton.textContent = held ? 'Resume' : 'Hold';
});
byId('call').addEventListener('click', async () => {
let stream: MediaStream | undefined;
try {
stream = await navigator.mediaDevices.getUserMedia({ audio: true });
client.call(numberInput.value, stream);
} catch (error) {
stream?.getTracks().forEach((track) => track.stop());
showError(error);
}
});
byId('hangup').addEventListener('click', () => client.hangup());
muteButton.addEventListener('click', () => client.toggleMute());
holdButton.addEventListener('click', async () => {
try {
await client.toggleHold();
} catch (error) {
showError(error);
}
});
for (const tone of '123456789*0#') {
const button = document.createElement('button');
button.type = 'button';
button.textContent = tone;
button.addEventListener('click', () => client.sendDTMF(tone));
keypad.append(button);
}
byId('answer').addEventListener('click', async () => {
try {
const stream = await navigator.mediaDevices.getUserMedia({ audio: true });
stream.getTracks().forEach((track) => track.stop());
client.answer();
incoming.hidden = true;
} catch (error) {
showError(error);
}
});
byId('reject').addEventListener('click', () => {
client.hangup();
incoming.hidden = true;
});
output.addEventListener('change', () => {
client.setAudioOutputDevice(output.value).catch(showError);
});
}
src/main.ts creates the client and handles sign-in:
import { HipcallClient } from '@hipcall/webrtc-sdk';
import { setupPhone } from './phone';
function env(name: string): string {
const value = import.meta.env[name];
if (!value) {
throw new Error(`${name} is not set.`);
}
return value;
}
const loginBtn = document.getElementById('login') as HTMLButtonElement;
const logoutBtn = document.getElementById('logout') as HTMLButtonElement;
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('registered', () => {
loginBtn.hidden = true;
logoutBtn.hidden = false;
});
setupPhone(client);
loginBtn.addEventListener('click', () => {
void client.loginWithOAuth();
});
logoutBtn.addEventListener('click', () => {
client.logout();
loginBtn.hidden = false;
logoutBtn.hidden = true;
});
async function start(): 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) {
throw new Error(`Hipcall returned an error: ${error}`);
}
if (!code) {
throw new Error('The authorisation code is missing.');
}
await client.handleOAuthCallback(code, url.searchParams.get('state'));
await client.connectSIP();
return;
}
if (client.isAuthenticated) {
await client.connectSIP();
}
}
start().catch((error) => console.error(error));
As in part one, run npm run proxy and npm run dev in two terminals and open your ngrok address. After you sign in, the status reads Ready. Type a number and press Call.
When it fails
488 Not Acceptable Here
If a mobile phone rings briefly and the call drops with this response in sipLog:
SIP/2.0 488 Not Acceptable Here
Via: SIP/2.0/WSS 8pdcgc4dt0rv.invalid;received=203.0.113.10;rport=6118;branch=z9hG4bK5587736
Reason: Q.850;cause=88;text="INCOMPATIBLE_DESTINATION"
Content-Length: 0
The carrier rejected the call's audio settings. The SDK adjusts them for you. If the error continues, open the INVITE body in sipLog and check that the m=audio line starts with codecs 8 and 0 and that there is no abs-send-time line.
The call connects but there is no audio, or audio goes one way
- The browser may refuse to play audio if the user has not clicked anything on the page. Always start and answer calls from a button click.
- Corporate networks can block audio packets (UDP) or the STUN server. Look in the
INVITEbody insipLogfor ana=candidateline containingtyp srflx. If there is none, the browser could not find its public IP address. - If the computer runs WSL2, Docker or Hyper-V, the browser may put an unreachable virtual IP (
10.x.x.x) in the SDP. The SDK tries to replace it with the real IP from the candidate lines.
NotAllowedError: Permission denied
If Call or Answer throws this error:
- The page is open over
http://. Apart fromlocalhost, browsers only allow the microphone onhttps://pages. Open the app on your ngrok address. - Microphone permission was denied. Allow it from the icon on the left of the address bar and reload the page.
403 Forbidden or 486 Busy Here
SIP/2.0 403 Forbidden
Via: SIP/2.0/WSS 8pdcgc4dt0rv.invalid;branch=z9hG4bK5587736
Content-Length: 0
403 Forbidden: the user has no active outbound number, or the destination country is turned off in the user's profile (phone_countries). CheckSettings > Telephony > Phone Numbers (Ayarlar > Telefon Sistemi > Telefon Numaraları)in the dashboard.486 Busy Here: the number you called is on another call or rejected the call.
Parameter reference
Call methods
| Method | Returns | Description |
|---|---|---|
call(number, stream?) |
void |
Calls a number or an extension. |
answer() |
void |
Answers the ringing incoming call. |
hangup() |
void |
Ends the call. Rejects an unanswered incoming call with 603 Decline. |
toggleMute() |
boolean |
Turns the microphone off or on. Returns the new state. |
toggleHold() |
Promise<boolean> |
Puts the call on hold or takes it off hold. hold() and unhold() are also available. |
sendDTMF(tone) |
void |
Sends 0 to 9, * or #. |
getAudioDevices() |
Promise<AudioDeviceInfo[]> |
Lists microphones and speakers. |
setAudioOutputDevice(deviceId) |
Promise<void> |
Changes the speaker that plays the other side's audio. |
Events
| Event | Payload | When |
|---|---|---|
registered |
none | The PBX accepted the registration. |
unregistered |
none | The registration ended. |
registrationFailed |
{ cause, code? } |
The PBX rejected the registration. |
incomingCall |
CallInfo |
A call came in. |
callConnecting |
CallInfo |
An outbound call started. |
callRinging |
CallInfo |
The other side is ringing. |
callConnected |
CallInfo |
The conversation started. |
callFailed |
{ call, cause } |
The call dropped before it connected. |
callEnded |
{ call, cause } |
The call ended. Also fires after callFailed. |
muteChanged |
{ muted } |
The microphone was turned off or on. |
holdChanged |
{ held } |
The call was put on or taken off hold. |
sipLog |
{ direction, message, time } |
SIP messages and SDK log lines. |
Next steps
- Find every endpoint in the Hipcall API Reference.
- Ask questions in the Hipcall Community.