If your SIP account is set up with JWT authentication, you can integrate calling functionality via CommPeak right into your own web page using WebRTC technology and make and receive calls directly from your browser.
Using JsSIP for WebRTC Integration
Before you start with integrating JsSiP for WebRTC Calling, make sure you have the following in place:
SIP Account with JWT Authentication Enabled
You'll need a SIP account configured to use JWT authentication. Follow this guide if you haven’t set one up yet.
JWT Token Generation Endpoint
Set up an HTTP endpoint capable of generating and signing JWT tokens using the secret key configured for your SIP account.
Secure Hosting with HTTPS
WebRTC requires a secure context, so your web application MUST be served over HTTPS.
Basic Knowledge of JavaScript
A working understanding of JavaScript is helpful, as you'll write scripts to initialize and control WebRTC Softphone with CommPeak.
Modern Web Browser
Ensure you use an up-to-date browser that supports WebRTC (e.g., Chrome, Firefox, Edge).
Creating Your First WebRTC Softphone
Adding Required HTML Elements
To start using the JsSIP library on your website, insert the following snippet into your HTML page. This will load JsSIP directly from a CDN and add additional HTML elements to the page required for operating the WebRTC Softphone, so you're ready to go without any extra setup.
<!-- Add JsSIP script from CDN -->
<script type="text/javascript" src="https://jssip.net/download/releases/jssip-3.10.0.min.js"></script>
<!-- HTML Element to handle the Audio Stream (required) -->
<audio id="remoteAudio"></audio>
<!-- DIV element holding current connection status (optional) -->
<div id="callStatus">offline</div>
<!-- DIV element holding current call duration (optional) -->
<div id="durationTimer">N/A</div>
Defining Authentication Function
To authenticate your application, you’ll need to fetch a JWT token. Check the code below that uses the fetch function, as outlined in the official documentation (replace with the actual link if available):
const getJwtToken = async function() {
try {
const response = await fetch('https://your-auth-endpoint.com/token');
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
// handle response from your endpoint, this is a simple example of plain text answer
const token = await response.text();
return token;
} catch (error) {
console.error('Failed to retrieve JWT token:', error);
}
}
❗️
IMPORTANT
Make sure the payload of JWT token includes the sub specified for your SIP account (Edit SIP Account > Authentication section, next to the JWT signature secret)
Editing SIP account: allowing JWT authentication
Expiration timestamp (exp) is required too, best practice to set it to 1 minute.
To initialize the library and establish a connection with CommPeak Cloud, follow the instructions below:
// function to update contents of status DIV
let updateCallStatus = function(msg) {
document.getElementById('callStatus').innerText = msg;
}
// variable holding WebRTC phone
let commpeakPhone = null;
// function updating JWT token for connection
let updateJwtToken = async function() {
const token = await getJwtToken();
commpeakPhone.set('authorization_jwt', `Bearer ${token}`);
}
async function initializeJsSIP() {
// getting initial JWT Token
const token = await getJwtToken(); // we have defined this function in previous step
// defining websocket connection to connect to
const socket = new JsSIP.WebSocketInterface('wss://sip.commpeak.com:7443');
// setting configuration for WebRTC Phone
const configuration = {
sockets: [socket],
uri: 'sip:[email protected]', // replace your_username with actual SIP Account username
authorization_jwt: `Bearer ${token}`,
session_timers: true,
register_expires: 60
};
// initializing CommPeak WebRTC Softphone
commpeakPhone = new JsSIP.UA(configuration);
commpeakPhone.start();
// defining basic events for the CommPeak WebRTC Softphone
commpeakPhone.on('connected', function() {
updateCallStatus('Connected to CommPeak Cloud');
});
commpeakPhone.on('registered', function() {
updateCallStatus('Successfully registered');
});
commpeakPhone.on('registrationFailed', function(e) {
updateCallStatus('Registration failed:', e.cause);
});
commpeakPhone.on('disconnected', function() {
updateCallStatus('Disconnected from CommPeak Cloud');
});
// setting interval to preserve validity of JWT Token every 50 seconds, since usually token is being defined to be valid for 60 seconds only
let timer = setInterval(updateJwtToken, 50000);
}
// variable holding audio element for attaching audio streams
let remoteAudio = document.getElementById('remoteAudio');
// audio stream related variables
var onplaying = true,
onpause = false;
// toggle variables for audio
remoteAudio.onplaying = function() {
onplaying = true;
onpause = false;
};
// toggle variables for audio
remoteAudio.onpause = function() {
onplaying = false;
onpause = true;
};
// starting CommPeak WebRTC Phone
await initializeJsSIP();
Adding Dialing Functionality to CommPeak WebRTC Softphone
After initializing and registering your WebRTC Softphone with CommPeak Cloud, you can enable dialing to start making calls directly from your browser.
Please follow the steps below to add the calling functionality to your CommPeak WebRTC Softphone:
// variable that will hold the actuall running call
var callSession = null;
// variables that will hold duration timer function interval and actual duration counter
var durationInterval = null, callDuration = 0;
// function to originate an outgoing call
let issueCall = function(destination) {
if (!commpeakPhone.isConnected() || !commpeakPhone.isRegistered()) {
alert("Phone is not connected");
return;
}
callSession = commpeakPhone.call(
`sip:${destination}`,
{
mediaConstraints: { audio: true, video: false },
}
);
};
// function hangs up active call
let hangup = function () {
if (callSession != null) {
callSession.terminate();
}
}
// function handling duration counter
let tickDuration = function() {
callDuration += 1;
document.getElementById('durationTimer').innerText = `${callDuration} seconds`;
}
// function to be executed after call is being answered in order to enable counter
let callStartEvent = function() {
durationInterval = setInterval(tickDuration, 1000);
}
// function to be executed after call hangup, reset variables and stops duration timer interval
let callEndEvent = function() {
callSession = null;
clearInterval(durationInterval);
document.getElementById('durationTimer').innerText = 'N/A';
callDuration = 0;
};
// function handling normal or error hangup
let getCallEndReason = function (data) {
var msg = 'Call Ended';
if (data.message != null && typeof data.message.status_code != 'undefined' && data.message.status_code != 200) {
// getting call error in case session failed
msg += `: ${data.message.status_code} ${data.message.reason_phrase}`;
}
updateCallStatus(msg);
}
// handler of new call event for both incoming and outgoing calls, only outgoing call is being described here
commpeakPhone.on('newRTCSession', function(e) {
if (callSession != null) {
// this is required in order to handle second call while one is already ongoing, callSession holds actively running call, so we will hangup another session
e.session.terminate();
return;
}
// assiging current session to globally available variable
callSession = e.session;
updateCallStatus('dialing');
callSession.connection.ontrack = function(e){
// handle remote audio stream to connect it to local audio
remoteAudio.srcObject = e.streams[0];
if (remoteAudio.paused && !onplaying) {
remoteAudio.play();
}
};
// Fired when remote side starts ringing
callSession.on('progress', function(data) {
updateCallStatus('ringing');
});
// Fired when the call is answered
callSession.on('accepted', function(data) {
callStartEvent();
updateCallStatus('answered');
});
// Fired when an running call ends.
callSession.on('ended', function(data) {
callEndEvent();
getCallEndReason(data);
});
// Fired when the session was unable to establish (before an answer was received).
callSession.on('failed', function(data) {
callEndEvent();
getCallEndReason(data);
});
});
Issuing Your First WebRTC Call via CommPeak Cloud
By executing this function, you will dial CommPeak's special number to perform an echo test call, allowing you to verify audio quality and connectivity:
issueCall('07777712125552665')
To end the active call session, use the hangup function.