Use Telnyx for Real Time Communication embedded in your web applications.
- WebRTC is currently under development
The WebRTC product and SDK enables you to:
- Build mobile clients that embed real time communications
- Generate on-demand tokens for your clients
- Add real time video communication to your web applications
Use Postman
To play around with a few examples, we recommend a REST client called Postman.
Prior to the import, Please refer to this section of Postman Documentation to configure environment and learn more about utilizing Postman for Telnyx APIs.
Simply tap the button below to start using the WebRTC API
in seconds with a pre-made collection of examples.
Getting Started with WebRTC
Requirements
WebRTC calls can be received without requiring the purchase or porting of a number. You will need:
- An API Key
- A connection of type Credential Connection
- A Credential for that connection
- A Token for authenticating to Telnyx WebRTC
Configuration and Usage
Telnyx WebRTC is enabled using Credential Connections. You can set up several connections to differentiate between use cases. A Credential Connection groups configuration for your calls, such as which codecs to use (tip: enable VP8 coded for video).
A Credential Connection will be used to set up On-demand Credentials which provide expiring telephony credentials sharing the connection configuration. A JWT (JSON Web Token) can be created for these On-demand Credentials to be used by client-facing applications using a WebRTC SDK.
Every On-demand Credential and Access Token (JWT) can be used to receive Inbound Calls using SIP addresses and for placing Outbound Calls.
To create a Credential Connection, On-demand Credentials and JWTs, use our APIs and authenticate using the API Key associated with your Mission Control account under API Keys. Find out more about authenticating with API V2 here.
WebRTC functionality can be added to your app using one of our WebRTC SDKs. For testing purposes we provide a sample application that uses our Javascript SDK. With this application you can authenticate to Telnyx WebRTC servers using either a SIP username/password or a JWT and be able to receive and place calls using audio and video.
Glossary
Term | Description |
---|---|
Credential Connection | Used to configure inbound/outbound calls for one or more credential |
Outbound Voice Profile | Used to configure outbound traffic and billing for one or more phone numbers |
On-demand Credential | An expiring SIP credential associated with a Connection, created via API. |
JWT | JSON Web Token. A standard method for representing claims (https://jwt.io/) |
Access Token (JWT) | A token associated with an On-demand Credential and used for authenticating to Telnyx WebRTC |
API Key | Secret API Key generated via Portal and used to authenticate Telnyx API calls. |
WebRTC SDK | A library used to provide RTC features to your application using Telnyx WebRTC platform. |
JavaScript Client SDK
The Telnyx WebRTC Client SDK provides all the functionality you need to start making voice & video calls from a browser.
Adding Telnyx to your JavaScript client application
Include the @telnyx/webrtc
npm module as a dependency:
npm install @telnyx/webrtc --save
Then, import @telnyx/webrtc
in your application code.
// main.js
import { TelnyxRTC } from '@telnyx/webrtc';
Adding Telnyx to your React application
Our @telnyx/react-client
library is the quickest way to get up and running if your application is written in React. See react-client on GitHub for all available components and hooks.
npm install @telnyx/react-client --save
// App.js
import {
TelnyxRTCProvider,
/* Or, if you prefer React hooks: */
// useTelnyxRTC
} from '@telnyx/react-client';
Android Client SDK
Enable Telnyx real-time communication services on Android.
Project structure:
- SDK project: sdk module, containing all Telnyx SDK components as well as tests.
- Demo application: app module, containing a sample demo application utilizing the sdk module.
Project Setup:
- Clone the repository
- Open the cloned repository in Android Studio and hit the build button to build both the sdk and sample app:
- Connect a device or start an emulated device and hit the run button
Usage
- Add Jitpack.io as a repository within your root level build file:
allprojects {
repositories {
...
maven { url 'https://jitpack.io' }
}
}
- Add the dependency within the app level build file:
dependencies {
implementation 'com.github.team-telnyx:telnyx-webrtc-android:Tag'
}
Tag should be replaced with the release version.
Then, import the WebRTC SDK into your application code at the top of the class:
import com.telnyx.webrtc.sdk.*
The ‘*’ symbol will import the whole SDK which will then be available for use within that class.
NOTE: Remember to add and handle INTERNET, RECORD_AUDIO and ACCESS_NETWORK_STATE permissions in order to properly use the SDK
Telnyx Client
To initialize the TelnyxClient you will have to provide the application context. Once an instance is created, you can call the .connect() method to connect to the socket. An error will appear as a socket response if there is no network available:
telnyxClient = TelnyxClient(context)
telnyxClient.connect()
Logging into Telnyx Client
To log into the Telnyx WebRTC client, you'll need to authenticate using a Telnyx SIP Connection. Follow our quickstart guide to create JWTs (JSON Web Tokens) to authenticate. To log in with a token we use the tokinLogin() method. You can also authenticate directly with the SIP Connection username
and password
with the credentialLogin() method:
telnyxClient.tokenLogin(tokenConfig)
//OR
telnyxClient.credentialLogin(credentialConfig)
Note: tokenConfig and credentialConfig are data classes that represent login settings for the client to use. They look like this:
sealed class TelnyxConfig
data class CredentialConfig(
val sipUser: String,
val sipPassword: String,
val sipCallerIDName: String?, // Your caller ID Name
val sipCallerIDNumber: String?, //Your caller ID Number
val ringtone: Int?, // Desired ringtone int resource ID
val ringBackTone: Int?, // Desired ringback tone int resource ID
val logLevel: LogLevel = LogLevel.NONE // SDK log level
) : TelnyxConfig()
data class TokenConfig(
val sipToken: String, // JWT login token
val sipCallerIDName: String?, // Your caller ID Name
val sipCallerIDNumber: String?, //Your caller ID Number
val ringtone: Int?, // Desired ringtone int resource ID
val ringBackTone: Int?, // Desired ringback tone int resource ID
val logLevel: LogLevel = LogLevel.NONE // SDK log level
) : TelnyxConfig()
Creating a call invitation
In order to make a call invitation, you need to provide your callerName, callerNumber, the destinationNumber (or SIP credential), and your clientState (any String value).
telnyxClient.call.newInvite(callerName, callerNumber, destinationNumber, clientState)
Accepting a call
In order to be able to accept a call, we first need to listen for invitations. We do this by getting the Telnyx Socket Response as LiveData:
fun getSocketResponse(): LiveData<SocketResponse<ReceivedMessageBody>>? =
telnyxClient.getSocketResponse()
We can then use this method to create a listener that listens for an invitation - in this example we assume getSocketResponse is a method within a ViewModel.
mainViewModel.getSocketResponse()
?.observe(this, object : SocketObserver<ReceivedMessageBody>() {
override fun onConnectionEstablished() {
// Handle a succesfully established connection
}
override fun onMessageReceived(data: ReceivedMessageBody?) {
when (data?.method) {
SocketMethod.LOGIN.methodName -> {
// Handle a successfull login - Update UI or Navigate to new screen, etc.
}
SocketMethod.INVITE.methodName -> {
// Handle an invitation Update UI or Navigate to new screen, etc.
// Then, through an answer button of some kind we can accept the call with:
val inviteResponse = data.result as InviteResponse
mainViewModel.acceptCall(inviteResponse.callId, inviteResponse.callerIdNumber)
}
SocketMethod.ANSWER.methodName -> {
//Handle a received call answer - Update UI or Navigate to new screen, etc.
}
SocketMethod.BYE.methodName -> {
// Handle a call rejection or ending - Update UI or Navigate to new screen, etc.
}
}
}
When we receive a call we will receive an InviteResponse data class that contains the details we need to accept the call. We can then call the acceptCall method in TelnyxClient from our ViewModel:
telnyxClient.call.acceptCall(callId, destinationNumber)
Methods:
.newInvite(callerName, callerNumber, destinationNumber, clientState)
Initiates a new call invitation, sending out an invitation to the destinationNumber via the Telnyx Socket Connection
Name | Type | Required | Description |
---|---|---|---|
callerName | String | required | Your caller name |
callerNumber | String | required | Your caller number |
destinationNumber | String | required | The person you are calling. Either their number or SIP username |
clientState | String | required | A state you would like to convey to the person you are calling. |
telnyxClient.call?.newInvite(callerName, callerNumber, destinationNumber, clientState)
.acceptCall(callId, destinationNumber)
Accepts an incoming call. Local user responds with both local and remote SDPs
Name | Type | Required | Description |
---|---|---|---|
callId | UUID | required | ID of Call to respond to, this will be in a JSON |
destinationNumber | String | required | Number or SIP username of the person calling, this will be in a JSON Object returned by the socket as an invitation |
telnyxClient.call.acceptCall(callId, destinationNumber)
.endCall(callID)
Ends an ongoing call with a provided callID, the unique UUID belonging to each call
Name | Type | Required | Description |
---|---|---|---|
callId | UUID | required | ID of Call to end. Each instance of a call has a callId parameter. |
telnyxClient.call.endCall(callId)
.getCallState()
Returns call state live data. This can be used to update UI. CallStates can be as follows: NEW
, CONNECTING
, RINGING
, ACTIVE
, HELD
or DONE
.
var calls = telnyxClient.getActiveCalls()
currentCall = calls[callID]
var currentCallState = currentCall.getCallState()
.onMuteUnmutePressed()
Either mutes or unmutes the AudioManager based on the current muteLiveData value
var calls = telnyxClient.getActiveCalls()
currentCall = calls[callID]
currentCall.onMuteUnmutePressed()
.getIsMuteStatus()
Returns mute state live data. This can either be true or false.
var calls = telnyxClient.getActiveCalls()
currentCall = calls[callID]
var isMute = currentCall.getIsMuteStatus()
.onHoldUnholdPressed(callID)
Either places a call on hold, or unholds a call based on the current holdLiveData value.
Name | Type | Required | Description |
---|---|---|---|
callId | UUID | required | ID of Call to hold or unhold. |
var calls = telnyxClient.getActiveCalls()
currentCall = calls[callID]
currentCall.onMuteUnmutePressed(callID)
.getIsOnHoldStatus()
Returns hold state live data. This can either be true or false.
var calls = telnyxClient.getActiveCalls()
currentCall = calls[callID]
var isOnHold = currentCall.getIsOnHoldStatus()
.onLoudSpeakerPressed()
Either enables or disables the AudioManager loudspeaker mode based on the current loudSpeakerLiveData value.
var calls = telnyxClient.getActiveCalls()
currentCall = calls[callID]
currentCall.onLoudSpeakerPressed()
.getIsOnLoudSpeakerStatus()
Returns loudspeaker state live data. This can either be true or false.
var calls = telnyxClient.getActiveCalls()
currentCall = calls[callID]
var isLoudSpeaker = currentCall.getIsOnLoudSpeakerStatus()
ProGuard changes
NOTE: In the case that you need to modify your application's proguard settings in order to obfuscate your code, such as we have done below:
app/build.gradle
buildTypes {
release {
minifyEnabled true
shrinkResources true
proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
jniDebuggable true
}
debug {
minifyEnabled true
shrinkResources true
proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
debuggable true
jniDebuggable true
}
}
Please keep in mind that you will need to add the following rules to the proguard-rules.pro file in your app in order for the SDK to continue functioning
app/proguard-rules.pro
-keep class org.webrtc.** { *; }
-keep class com.telnyx.webrtc.sdk.** { *; }
Questions? Comments? Building something rad? Join our Slack channel and share.
License
IOS Client SDK
Enable Telnyx real-time communication services on IOS.
The Telnyx iOS WebRTC Client SDK provides all the functionality you need to start making voice calls from an iPhone.
Project structure:
- SDK project: sdk module, containing all Telnyx SDK components as well as tests.
- Demo application: app module, containing a sample demo application utilizing the sdk module.
Project Setup:
- Clone the repository
- Open the cloned repository in Xcode and hit the build button to build both the sdk and sample app:
- Connect a device or start an emulated device and hit the run button
Usage
Adding Telnyx to your iOS Client Application:
Include the following line into your podfile and run pod install.
pod TelnyxRTC //Requires confirmation after the first release.
After updating your podfile you will need to run the following command:
pod install
Once the SDK is added to your pods, open your project workspace and import the SDK at the top of the class:
import TelnyxRTC
Telnyx Client
The TelnyxClient connects your application to the Telnyx backend, enabling you to make outgoing calls and handle incoming calls.
The main steps to get the SDK working are:
1 - Initialize the client.
2 - Set the delegate to listen to SDK events.
3 - Connect the client: Login to the backend in order to receive and start calls.
4 - Place outbound calls.
5 - Incoming calls.
1 - Initialize the client:
To begin you will need to instantiate the Telnyx Client:
// Initialize the client
let telnyxClient = TxClient()
2 - Listen SDK updates:
To begin you will need to instantiate the Telnyx Client:
Then you will need to set the client delegate in order to get SDK events and you should implement the protocol wherever you want to receive the events:
Example of the delegate usage on a ViewController:
// Set the delegate
telnyxClient.delegate = self
extension ViewController: TxClientDelegate {
func onRemoteCallEnded(callId: UUID) {
// Call has been removed internally.
}
func onSocketConnected() {
// When the client has successfully connected to the Telnyx Backend.
}
func onSocketDisconnected() {
// When the client from the Telnyx backend
}
func onClientError(error: Error) {
// Something went wrong.
}
func onClientReady() {
// You can start receiving incoming calls or
// start making calls once the client is fully initialized.
}
func onSessionUpdated(sessionId: String) {
// This function will be executed when a sessionId is received.
}
func onIncomingCall(call: Call) {
// Someone is calling you.
}
// You can update your UI from here based on the call states.
// Check that the callId is the same as your current call.
func onCallStateUpdated(callState: CallState, callId: UUID) {
// handle the new call state
switch (callState) {
case .CONNECTING:
break
case .RINGING:
break
case .NEW:
break
case .ACTIVE:
break
case .DONE:
break
case .HELD:
break
}
}
}
3 - Connect the client:
In this step you need to set the parameters to configure your connection. The main parameters are the login credentials used to register into the Telnyx backend.
You can connect using your SIP credentials (sip user and password) or by an access token. You can check how to create your credentials on the following link
Login with SIP credentials:
let txConfigUserAndPassword = TxConfig(sipUser: “SIP_USER”,
password: “SIP_PASSWORD”)
do {
// Connect and login
try telnyxClient.connect(txConfig: txConfigUserAndPassword)
} catch let error {
print("Error \(error)")
}
Login with Access Token:
// Use a JWT Telnyx Token to authenticate
let txConfigToken = TxConfig(token: "MY_JWT_TELNYX_TOKEN")
do {
// Connect and login
// Use `txConfigToken`
try telnyxClient.connect(txConfig: txConfigToken)
} catch let error {
print("Error \(error)")
}
The TxConfig Structure:
Through the TxConfig structure you can configure the following optional parameters:
- The Ringtone audio file.
- The Ringback tone audio file.
- The logging level.
4 - Outbound calls:
Once your client is fully connected and logged in you can place outbound calls from your iPhone. You can call to a phone number or to a SIP URI. To call a SIP URI pass the following as the destinationNumber parameter: [email protected]
Your client will be ready to place outbound calls only when is logged in. To determine whether your client is ready or not, you need to implement the TxClientDelegate and wait for the onClientReady() method to be called.
Example of usage:
// Create a client instance
self.telnyxClient = TxClient()
// Assign the delegate to get SDK events
self.telnyxClient?.delegate = self
// Connect the client (Check TxClient class for more info)
self.telnyxClient?.connect(....)
// Create the call and start calling
self.currentCall = try self.telnyxClient?.newCall(callerName: "Caller name",
callerNumber: "155531234567",
// Destination is required and can be a phone number or SIP URI
destinationNumber: "18004377950",
callId: UUID.init())
5 - Incoming calls:
In order to answer an incoming call you will need to be fully connected and logged in.
//Init your client
func initTelnyxClient() {
self.telnyxClient = TxClient()
// Assign the delegate to get SDK events
self.telnyxClient?.delegate = self
// Connect the client (Check TxClient class for more info)
self.telnyxClient?.connect(....)
}
extension ViewController: TxClientDelegate {
//....
func onIncomingCall(call: Call) {
//We are automatically answering any incoming call as an example, but
//maybe you want to store a reference of the call, and answer the call after a button press.
self.myCall = call.answer()
}
}
Before uploading your app to TestFlight:
The WebRTC SDK requires access to the device microphone in order to make audio calls. In order to avoid rejection from Apple when uploading a build to TestFlight, remember to add the following key into your info.plist:
- Privacy - Microphone Usage Description
Microphone permission will be requested when making the first outbound call or when receiving the first inbound call.
Questions? Comments? Building something rad? Join our Slack channel and share.