WebRTC client

Configuration

Configure your WebRTC SIP client with the following settings.

Client settings

Parameter Value
Servers wss://voip.46elks.com/w1/websocket
Username Client number without the + sign like 4600100100.
Password The password for the number it is the value "secret" on the number object in the API.
URI The server and number in combination like 4600100100@voip.46elks.com

Outgoing phone calls

Special configuration is required to enable outgoing phone calls directly from a SIP or webRTC client. Our support team would gladly help you get the right voice setup for your use case.

Sample code

Using JsSIP found at: https://jssip.net/

<!DOCTYPE html>
<input id="numberInput" placeholder="+46701740605">
<button id="callButton" onclick="callButtonClick()">
  Make call
</button>

<script src="/jssip-3.10.0.js"></script>
<script>
  // A webrtc-enabled SIP number from 46elks.
  const webrtcUser = "4600XXXXXX";
  // The password for the SIP number.
  const webrtcPassword = "ABCDEF12345678901234567890123456";

  const webrtcUri = "sip:" + webrtcUser + "@voip.46elks.com";
  const webrtcNumber = "+" + webrtcUser;

  var session = null;
  const audio = document.createElement("audio");
  const callButton = document.getElementById("callButton");

  function callButtonClick() {
    if (session && session.isEstablished()) {
      session.terminate()
    } else {
      let numberInput = document.getElementById("numberInput");
      let phonenumber = numberInput.value;
      let formData = new FormData();
      formData.append("phoneNumber", phonenumber);
      formData.append("webrtcNumber", webrtcNumber);
      // Tell our server to initiate a call with 46elks.
      fetch("/make-call", {method: "post", body: formData});
    }
  }

  var socket = new JsSIP.WebSocketInterface(
    "wss://voip.46elks.com/w1/websocket"
  );
  var configuration = {
    sockets: [socket],
    uri: webrtcUri,
    password: webrtcPassword
  };

  var ua = new JsSIP.UA(configuration);

  ua.on("connected", (e) => {
    console.log("Connected:", e);
  });
  ua.on("registered", (e) => {
    console.log("Registered:", e);
  });
  ua.on("registrationFailed", (e) => {
    console.log("Registration failed:", e);
  });

  ua.on("newRTCSession", (e) => {
    // Incoming call! (from initiating a call with the API)
    console.log("NewRTCSession:", e);
    session = e.session;
    session.answer(
      {"mediaConstraints": {"audio": true, "video": false}}
    );
    session.connection.ontrack = (e) => {
      audio.srcObject = e.streams[0];
      audio.play();
    };
    callButton.innerHTML = "Hangup";
    session.on("ended", (e) => {
      callButton.innerHTML = "Make call";
    });
  });
  ua.start();
</script>

And a Bottle.py webserver making requests to the 46elks API:

import json
import urllib.parse
import urllib.request
from base64 import b64encode
from urllib.error import HTTPError, URLError

from bottle import get, post, request, run, static_file

# Your 46elks API credentials.
elks_username = "API username"
elks_password = "API password"

# A number bought through the 46elks dashboard or the one
# you registered with at 46elks. It will be used as caller id.
elks_number = "+4676686..."

auth_bytes = f"{elks_username}:{elks_password}".encode()
auth_token = b64encode(auth_bytes).decode()
headers = {
    "Authorization": f"Basic {auth_token}"
}


@get('/')
def index():
    return static_file('webrtc.html', root='.')


@get('/jssip-3.10.0.js')
def jssip():
    return static_file('jssip-3.10.0.js', root='.')


@post('/make-call')
def make_call():
    phone_number = request.forms.phoneNumber
    webrtc_number = request.forms.webrtcNumber

    # When the webrtc phone has answered, we connect to
    # the number we want to call.
    voice_start = {'connect': phone_number,
                   'callerid': elks_number}

    # Initiate call to our webrtc phone.
    data = urllib.parse.urlencode([
        ('from', elks_number),
        ('to', webrtc_number),
        ('voice_start', json.dumps(voice_start))
    ])
    req = urllib.request.Request(
        'https://api.46elks.com/a1/calls',
        data=data.encode(),
        headers=headers,
        method='POST'
    )
    try:
        response = urllib.request.urlopen(req)
    except HTTPError as e:
        print(e.code, e.reason)
        print(e.read().decode())
    except URLError as e:
        print("Could not reach server.")
        print(e.reason)
    else:
        print(response.read().decode())


run(host='localhost', port=8080)

You can download the full example here (zip file).

There is also an example using PHP over at the 46elks-getting-started repo on GitHub.