Register by 10/16 for $250 off the on-site price.

Outgoing Calls with Twilio Client

Outgoing Capability

In order for your client device to be allowed to connect to Twilio so it can make an outgoing call, you need to make sure that the Capability Token you've provided allows for it. To do this, you will need a TwiML App SID and have your server application provide this SID to the outgoing capability of the token generator.

Loading Code Samples...
Language
SDK Version:
  • 4.x
  • 5.x
SDK Version:
  • 6.x
  • 7.x
SDK Version:
  • 2.x
  • 3.x
SDK Version:
  • 4.x
  • 5.x
SDK Version:
  • 5.x
  • 6.x
SDK Version:
  • 4.x
  • 5.x
const http = require('http');
const express = require('express');
const twilio = require('twilio');

const app = express();

app.get('/token', (req, res) => {
  // put your Twilio API credentials here
  const accountSid = 'ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX';
  const authToken = 'your_auth_token';

  // put your Twilio Application Sid here
  const appSid = 'APXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX';

  const capability = new twilio.Capability(accountSid, authToken);
  capability.allowClientOutgoing(appSid);
  const token = capability.generate();

  res.set('Content-Type', 'application/jwt');
  res.send(token);
});

app.post('/voice', (req, res) => {
  // TODO: Create TwiML response
});

http.createServer(app).listen(1337, '127.0.0.1');
console.log('Twilio Client app server running at http://127.0.0.1:1337/');
const http = require('http');
const express = require('express');
const ClientCapability = require('twilio').jwt.ClientCapability;

const app = express();

app.get('/token', (req, res) => {
  // put your Twilio API credentials here
  const accountSid = 'ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX';
  const authToken = 'your_auth_token';

  // put your Twilio Application Sid here
  const appSid = 'APXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX';

  const capability = new ClientCapability({
    accountSid: accountSid,
    authToken: authToken,
  });
  capability.addScope(
    new ClientCapability.OutgoingClientScope({ applicationSid: appSid })
  );
  const token = capability.toJwt();

  res.set('Content-Type', 'application/jwt');
  res.send(token);
});

app.post('/voice', (req, res) => {
  // TODO: Create TwiML response
});

http.createServer(app).listen(1337, '127.0.0.1');
console.log('Twilio Client app server running at http://127.0.0.1:1337/token/');
// In Package Manager, run:
// Install-Package Twilio.Client -DependencyVersion HighestMinor

using System.Web.Mvc;
using Twilio;

public class TokenController : Controller
{
  // GET: Token
  public ActionResult Index()
  {
    // put your Twilio API credentials here
    string accountSid = "ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX";
    string authToken = "your_auth_token";

    // put your Twilio Application Sid here
    string appSid = "APXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX";

    var capability = new TwilioCapability(accountSid, authToken);
    capability.AllowClientOutgoing(appSid);
    string token = capability.GenerateToken();

    return Content(token, "application/jwt");
  }
}
<?php
include 'Services/Twilio/Capability.php';

// put your Twilio API credentials here
$accountSid = 'ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX';
$authToken  = 'your_auth_token';
$appSid = 'APXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX';

$capability = new Services_Twilio_Capability($accountSid, $authToken);
$capability->allowClientOutgoing($appSid);
$token = $capability->generateToken();

echo $token;
require 'twilio-ruby'
require 'sinatra'

get '/token' do
  account_sid = 'ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX'
  auth_token = 'your_auth_token'
  capability = Twilio::Util::Capability.new account_sid, auth_token
  # Create an application sid at
  # twilio.com/console/phone-numbers/dev-tools/twiml-apps and use it here
  capability.allow_client_outgoing 'APXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX'
  token = capability.generate

  content_type 'application/jwt'
  token
end

# TODO: post '/voice' do
// In Package Manager, run:
// Install-Package Twilio.Client -Pre

using System.Collections.Generic;
using System.Web.Mvc;
using Twilio.Jwt;
using Twilio.Jwt.Client;

public class TokenController : Controller
{
    // GET: Token
    public ActionResult Index()
    {
        // Put your Twilio API credentials here
        const string accountSid = "ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX";
        const string authToken = "your_auth_token";

        // Put your Twilio Application SID here
        const string appSid = "APXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX";

        var scopes = new HashSet<IScope>
        {
            new OutgoingClientScope(appSid)
        };
        var capability = new ClientCapability(accountSid, authToken, scopes: scopes);

        return Content(capability.ToJwt(), "application/jwt");
    }
}
<?php
include "vendor/autoload.php";

use Twilio\Jwt\ClientToken;

// put your Twilio API credentials here
$accountSid = 'ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX';
$authToken  = 'your_auth_token';
$appSid = 'APXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX';

$capability = new ClientToken($accountSid, $authToken);
$capability->allowClientOutgoing($appSid);
$token = $capability->generateToken();

echo $token;
from flask import Flask, Response
from twilio.util import TwilioCapability

app = Flask(__name__)


@app.route('/token', methods=['GET'])
def get_capability_token():
    """Respond to incoming requests."""

    # Find these values at twilio.com/console
    account_sid = 'ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX'
    auth_token = 'your_auth_token'

    capability = TwilioCapability(account_sid, auth_token)

    # Twilio Application Sid
    application_sid = 'APXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX'
    capability.allow_client_outgoing(application_sid)
    token = capability.generate()

    return Response(token, mimetype='application/jwt')


if __name__ == "__main__":
    app.run(debug=True)
require 'twilio-ruby'
require 'sinatra'

get '/token' do
  account_sid = 'ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX'
  auth_token = 'your_auth_token'
  capability = Twilio::JWT::Capability.new(account_sid, auth_token)

  # Create an application sid at
  # twilio.com/console/phone-numbers/dev-tools/twiml-apps and use it here
  capability.allow_client_outgoing('APXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX')
  token = capability.generate

  content_type 'application/jwt'
  token
end

# TODO: post '/voice' do
package com.twilio;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

import com.twilio.sdk.client.TwilioCapability;

public class TwilioServlet extends HttpServlet {

    public static final String ACCOUNT_SID = "ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX";
    public static final String AUTH_TOKEN = "your_auth_token";

    public void service(HttpServletRequest request, HttpServletResponse response) throws IOException {

        // Find an application Sid from twilio.com/user/account/apps
        String applicationSid = "APXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX";
        TwilioCapability capability = new TwilioCapability(ACCOUNT_SID, AUTH_TOKEN);
        capability.allowClientOutgoing(applicationSid);

        String token = capability.generateToken();

        response.setContentType("application/jwt");
        response.getWriter().print(token);
    }
}
from flask import Flask, Response
from twilio.jwt.client import ClientCapabilityToken

app = Flask(__name__)


@app.route('/token', methods=['GET'])
def get_capability_token():
    """Respond to incoming requests."""

    # Find these values at twilio.com/console
    account_sid = 'ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX'
    auth_token = 'your_auth_token'

    capability = ClientCapabilityToken(account_sid, auth_token)

    # Twilio Application Sid
    application_sid = 'APXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX'
    capability.allow_client_outgoing(application_sid)
    token = capability.generate()

    return Response(token, mimetype='application/jwt')


if __name__ == "__main__":
    app.run(debug=True)
import java.io.IOException;
import java.util.List;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.google.common.collect.Lists;
import com.twilio.jwt.client.ClientCapability;
import com.twilio.jwt.client.OutgoingClientScope;
import com.twilio.jwt.client.Scope;

public class TwilioServlet extends HttpServlet {

  public static final String ACCOUNT_SID = "ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX";
  public static final String AUTH_TOKEN = "your_auth_token";

  public void service(HttpServletRequest request, HttpServletResponse response) throws IOException {
    // Find an application Sid from twilio.com/user/account/apps
    String applicationSid = "APXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX";

    List<Scope> scopes =
        Lists.newArrayList(new OutgoingClientScope.Builder(applicationSid).build());

    ClientCapability capability =
        new ClientCapability.Builder(ACCOUNT_SID, AUTH_TOKEN).scopes(scopes).build();

    String token = capability.toJwt();

    response.setContentType("application/jwt");
    response.getWriter().print(token);
  }
}
Allow Outgoing Calls for Twilio Client

TwiML App Configuration

Configure your TwiML App to connect to a URL that returns the following TwiML:

<?xml version="1.0" encoding="UTF-8"?>
<Response>
    <Say>Thanks for calling!</Say>
</Response>

See our server application guide for more details on how to set this up.

Connecting a Call

Once you've created a Device, you can call it's connect() method to connect to Twilio. Twilio will make a request to the voice URL configured on your TwiML App. Since this return the <Say> verb that simply thanks the caller, you should hear the thank you message in your browser or on your device.

Loading Code Samples...
Language
private void connect() {
    if (clientDevice != null) {
        // Create an outgoing connection
        connection = clientDevice.connect();
    } else {
        Toast.makeText(ClientActivity.this, "No existing device", Toast.LENGTH_SHORT).show();
    }
}
// Connect a call when button clicked
document.getElementById('button-call').onclick = function() {
  console.log('Calling...');
  Twilio.Device.connect();
};
- (IBAction)dialButtonPressed:(id)sender
{
    _connection = [_phone connect:nil delegate:nil];
}
Connecting a Call with Twilio Client

Passing Parameters for a Call

Just getting a message played to you in your browser isn't all that interesting. What we really want to do is have the client make a call to a real live phone number. In order to do this, our client needs to pass a parameter to our TwiML App. The parameter can be anything you like, but we'll create a parameter named "To" to indicate the number we want to make a call to.

Loading Code Samples...
Language
private void connect(String contact, boolean isPhoneNumber) {
    ...

    Map<String, String> params = new HashMap<String, String>();
    params.put("To", contact);

    if (clientDevice != null) {
        // Create an outgoing connection
        connection = clientDevice.connect(params, this);
        setCallUI();
    } else {
        Toast.makeText(ClientActivity.this, "No existing device", Toast.LENGTH_SHORT).show();
    }
}
// Connect a call when button clicked
document.getElementById('button-call').onclick = function() {
  // get the phone number to connect the call to
  const params = { To: '15558675310' };

  console.log('Calling ' + params.To + '...');
  Twilio.Device.connect(params);
};
- (IBAction)dialButtonPressed:(id)sender
{
    NSDictionary *params = @{@"To": self.numberField.text};
    _connection = [_phone connect:params delegate:nil];
}
Connecting a Call with Parameters

The "To" parameter (and anything else you specify in the params object) will be passed to your server application's TwiML handler. Your server code can check for those parameters and then generate and return the appropriate TwiML, for example a <Dial> verb to connect the call.

Loading Code Samples...
Language
SDK Version:
  • 4.x
  • 5.x
SDK Version:
  • 6.x
  • 7.x
SDK Version:
  • 2.x
  • 3.x
SDK Version:
  • 4.x
  • 5.x
SDK Version:
  • 5.x
  • 6.x
SDK Version:
  • 4.x
  • 5.x
Format:
  • XML
const http = require('http');
const express = require('express');
const bodyParser = require('body-parser');
const twilio = require('twilio');

const app = express();
app.use(bodyParser.urlencoded({ extended: false }));

app.post('/voice', (req, res) => {
  // Create TwiML response
  const twiml = new twilio.TwimlResponse();

  if (req.body.To) {
    twiml.dial({ callerId: '+15017122661' }, function() {
      this.number(req.body.To);
    });
  } else {
    twiml.say('Thanks for calling!');
  }

  res.set('Content-Type', 'text/xml');
  res.send(twiml.toString());
});

app.get('/token', (req, res) => {
  // TODO: generate token
});

http.createServer(app).listen(1337, '127.0.0.1');
console.log('Twilio Client app server running at http://127.0.0.1:1337/');
const http = require('http');
const express = require('express');
const bodyParser = require('body-parser');
const VoiceResponse = require('twilio').twiml.VoiceResponse;

const app = express();
app.use(bodyParser.urlencoded({ extended: false }));

app.post('/voice', (req, res) => {
  // Create TwiML response
  const twiml = new VoiceResponse();

  if (req.body.To) {
    const dial = twiml.dial({ callerId: '+15017122661' });
    dial.number(req.body.To);
  } else {
    twiml.say('Thanks for calling!');
  }

  res.set('Content-Type', 'text/xml');
  res.send(twiml.toString());
});

app.get('/token', (req, res) => {
  // TODO: generate token
});

http.createServer(app).listen(1337, '127.0.0.1');
console.log('Twilio Client app server running at http://127.0.0.1:1337/voice/');
// In Package Manager, run:
// Install-Package Twilio.Mvc -DependencyVersion HighestMinor

using Twilio.Mvc;
using Twilio.TwiML;
using Twilio.TwiML.Mvc;

public class VoiceController : TwilioController
{
  [HttpPost]
  public ActionResult Index(VoiceRequest request)
  {
      var response = new TwilioResponse();
      if (!string.IsNullOrEmpty(request.To))
      {
        response.Dial(new Number(request.To), 
          new {callerId = "+15017122661"});
      }
      else
      {
        response.Say("Thanks for calling!");
      }
      return TwiML(response);
  }
}
<?php
// Get the PHP helper library from https://twilio.com/docs/libraries/php

// this line loads the library 
require('/path/to/twilio-php/Services/Twilio.php'); 

$response = new Services_Twilio_Twiml;

// get the phone number from the page request parameters, if given
if (isset($_REQUEST['To'])) {
    $number = htmlspecialchars($_REQUEST['To']);
    $response->dial(array(
        'callerId' => '+15017122661'
    ))->number($number);
} else {
    $response->say("Thanks for calling!");
}

echo $response;
require 'twilio-ruby'
require 'sinatra'

post '/voice' do
  twiml = Twilio::TwiML::Response.new do |r|
    if params['To']
      r.Dial callerId: '+15017122661' do |d|
        d.Number params['To']
      end
    else
      r.Say 'Thanks for calling!'
    end
  end

  content_type 'text/xml'
  twiml.text
end

# TODO: get '/token' do
// In Package Manager, run:
// Install-Package Twilio.Mvc -DependencyVersion HighestMinor

using System.Web.Mvc;
using Twilio.TwiML;

public class VoiceController : Controller
{
    [HttpPost]
    public ActionResult Index(VoiceRequest request)
    {
        var response = new VoiceResponse();
        if (!string.IsNullOrEmpty(request.To))
        {
            var number = new Dial(callerId: "+15017122661");
            number.Number(Request.To);

            response.Dial(number);
        }
        else
        {
            response.Say("Thanks for calling!");
        }

        return Content(response.ToString(), "text/xml");
    }
}
<?php
// Get the PHP helper library from https://twilio.com/docs/libraries/php

// this line loads the library 
require('vendor/autoload.php'); 
use Twilio\TwiML;

$response = new TwiML;

// get the phone number from the page request parameters, if given
if (isset($_REQUEST['To'])) {
    $number = htmlspecialchars($_REQUEST['To']);
    $response->dial(array(
        'callerId' => '+15017122661'
    ))->number($number);
} else {
    $response->say("Thanks for calling!");
}

echo $response;
from flask import Flask, Response, request
import twilio.twiml

app = Flask(__name__)


@app.route("/voice", methods=['POST'])
def get_voice_twiml():
    """Respond to incoming calls with a simple text message."""

    resp = twilio.twiml.Response()
    if "To" in request.form:
        resp.dial(callerId="+15017122661").number(request.form["To"])
    else:
        resp.say("Thanks for calling!")

    return Response(str(resp), mimetype='text/xml')


if __name__ == "__main__":
    app.run(debug=True)
require 'twilio-ruby'
require 'sinatra'

post '/voice' do
  twiml = Twilio::TwiML::Response.new do |r|
    if params['To']
      r.Dial callerId: '+15017122661' do |d|
        d.Number params['To']
      end
    else
      r.Say 'Thanks for calling!'
    end
  end

  content_type 'text/xml'
  twiml.text
end

# TODO: get '/token' do
package com.twilio;

import java.io.IOException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.twilio.sdk.verbs.TwiMLResponse;
import com.twilio.sdk.verbs.TwiMLException;
import com.twilio.sdk.verbs.Say;
import com.twilio.sdk.verbs.Dial;
import com.twilio.sdk.verbs.Number;

@WebServlet(name = "TwilioServlet", urlPatterns = {"/voice"})
public class TwilioServlet extends HttpServlet {

    // service() responds to both GET and POST requests.
    // You can also use doGet() or doPost()
    public void service(HttpServletRequest request, HttpServletResponse response) throws IOException {
        TwiMLResponse twiml = new TwiMLResponse();
        try {
            String to = request.getParameter("To");
            if (to != null) {
                Dial dial = new Dial();
                dial.setCallerId("+15017122661");
                dial.append(new Number(to));
                twiml.append(dial);
            } else {
                twiml.append(new Say("Thanks for calling!"));
            }
        } catch (TwiMLException e) {
            e.printStackTrace();
        }

        response.setContentType("application/xml");
        response.getWriter().print(twiml.toXML());
    }
}
from flask import Flask, Response, request
from twilio.twiml.voice_response import VoiceResponse

app = Flask(__name__)


@app.route("/voice", methods=['POST'])
def get_voice_twiml():
    """Respond to incoming calls with a simple text message."""

    resp = VoiceResponse()
    if "To" in request.form:
        resp.dial(request.form["To"], caller_id="+15017122661")
    else:
        resp.say("Thanks for calling!")

    return Response(str(resp), mimetype='text/xml')


if __name__ == "__main__":
    app.run(debug=True)
import java.io.IOException;

import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.twilio.twiml.*;
import com.twilio.twiml.voice.Number;

@WebServlet(name = "TwilioServlet", urlPatterns = {"/voice"})
public class TwilioServlet extends HttpServlet {
  // service() responds to both GET and POST requests.
  // You can also use doGet() or doPost()
  public void service(HttpServletRequest request, HttpServletResponse response) throws IOException {
    String to = request.getParameter("To");

    VoiceResponse.Builder responseBuilder = new VoiceResponse.Builder();

    if (to != null) {
      Number number = new Number.Builder(to).build();
      Dial dial = new Dial.Builder()
          .number(number)
          .callerId("+15017122661")
          .build();

      responseBuilder = responseBuilder.dial(dial);
    } else {
      Say say = new Say.Builder("Thanks for calling!").build();
      responseBuilder = responseBuilder.say(say);
    }

    VoiceResponse twiml = responseBuilder.build();

    response.setContentType("application/xml");

    try {
      response.getWriter().print(twiml.toXml());
    } catch (TwiMLException e) {
      e.printStackTrace();
    }
  }
}
<?xml version="1.0" encoding="utf-8"?>
<Response>
  <Dial callerId="+15017122661">
    <Number>+15558675310</Number>
  </Dial>
</Response>
Generate TwiML from Client Parameters

Hanging Up a Call

Once you're on a call, you will probably want a way to hang up. This can be accomplished (albeit with less satisfaction than slamming a real phone handset into the receiver) using the disconnect() method.

Loading Code Samples...
Language
private void disconnect() {
    if (activeConnection != null) {
        activeConnection.disconnect();
        activeConnection = null;
    }
}
// Connect a call when button clicked
document.getElementById('button-hangup').onclick = function() {
  console.log('Hanging up...');
  Twilio.Device.disconnectAll();
};
- (IBAction)hangupButtonPressed:(id)sender
{
    [_connection disconnect];
}
Disconnecting a Call with Twilio Client
David Prothero
Devin Rader

Need some help?

We all do sometimes; code is hard. Get help now from our support team, or lean on the wisdom of the crowd browsing the Twilio tag on Stack Overflow.

Loading Code Samples...
SDK Version:
  • 4.x
  • 5.x
SDK Version:
  • 6.x
  • 7.x
SDK Version:
  • 2.x
  • 3.x
SDK Version:
  • 4.x
  • 5.x
SDK Version:
  • 5.x
  • 6.x
SDK Version:
  • 4.x
  • 5.x
const http = require('http');
const express = require('express');
const twilio = require('twilio');

const app = express();

app.get('/token', (req, res) => {
  // put your Twilio API credentials here
  const accountSid = 'ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX';
  const authToken = 'your_auth_token';

  // put your Twilio Application Sid here
  const appSid = 'APXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX';

  const capability = new twilio.Capability(accountSid, authToken);
  capability.allowClientOutgoing(appSid);
  const token = capability.generate();

  res.set('Content-Type', 'application/jwt');
  res.send(token);
});

app.post('/voice', (req, res) => {
  // TODO: Create TwiML response
});

http.createServer(app).listen(1337, '127.0.0.1');
console.log('Twilio Client app server running at http://127.0.0.1:1337/');
const http = require('http');
const express = require('express');
const ClientCapability = require('twilio').jwt.ClientCapability;

const app = express();

app.get('/token', (req, res) => {
  // put your Twilio API credentials here
  const accountSid = 'ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX';
  const authToken = 'your_auth_token';

  // put your Twilio Application Sid here
  const appSid = 'APXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX';

  const capability = new ClientCapability({
    accountSid: accountSid,
    authToken: authToken,
  });
  capability.addScope(
    new ClientCapability.OutgoingClientScope({ applicationSid: appSid })
  );
  const token = capability.toJwt();

  res.set('Content-Type', 'application/jwt');
  res.send(token);
});

app.post('/voice', (req, res) => {
  // TODO: Create TwiML response
});

http.createServer(app).listen(1337, '127.0.0.1');
console.log('Twilio Client app server running at http://127.0.0.1:1337/token/');
// In Package Manager, run:
// Install-Package Twilio.Client -DependencyVersion HighestMinor

using System.Web.Mvc;
using Twilio;

public class TokenController : Controller
{
  // GET: Token
  public ActionResult Index()
  {
    // put your Twilio API credentials here
    string accountSid = "ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX";
    string authToken = "your_auth_token";

    // put your Twilio Application Sid here
    string appSid = "APXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX";

    var capability = new TwilioCapability(accountSid, authToken);
    capability.AllowClientOutgoing(appSid);
    string token = capability.GenerateToken();

    return Content(token, "application/jwt");
  }
}
<?php
include 'Services/Twilio/Capability.php';

// put your Twilio API credentials here
$accountSid = 'ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX';
$authToken  = 'your_auth_token';
$appSid = 'APXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX';

$capability = new Services_Twilio_Capability($accountSid, $authToken);
$capability->allowClientOutgoing($appSid);
$token = $capability->generateToken();

echo $token;
require 'twilio-ruby'
require 'sinatra'

get '/token' do
  account_sid = 'ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX'
  auth_token = 'your_auth_token'
  capability = Twilio::Util::Capability.new account_sid, auth_token
  # Create an application sid at
  # twilio.com/console/phone-numbers/dev-tools/twiml-apps and use it here
  capability.allow_client_outgoing 'APXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX'
  token = capability.generate

  content_type 'application/jwt'
  token
end

# TODO: post '/voice' do
// In Package Manager, run:
// Install-Package Twilio.Client -Pre

using System.Collections.Generic;
using System.Web.Mvc;
using Twilio.Jwt;
using Twilio.Jwt.Client;

public class TokenController : Controller
{
    // GET: Token
    public ActionResult Index()
    {
        // Put your Twilio API credentials here
        const string accountSid = "ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX";
        const string authToken = "your_auth_token";

        // Put your Twilio Application SID here
        const string appSid = "APXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX";

        var scopes = new HashSet<IScope>
        {
            new OutgoingClientScope(appSid)
        };
        var capability = new ClientCapability(accountSid, authToken, scopes: scopes);

        return Content(capability.ToJwt(), "application/jwt");
    }
}
<?php
include "vendor/autoload.php";

use Twilio\Jwt\ClientToken;

// put your Twilio API credentials here
$accountSid = 'ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX';
$authToken  = 'your_auth_token';
$appSid = 'APXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX';

$capability = new ClientToken($accountSid, $authToken);
$capability->allowClientOutgoing($appSid);
$token = $capability->generateToken();

echo $token;
from flask import Flask, Response
from twilio.util import TwilioCapability

app = Flask(__name__)


@app.route('/token', methods=['GET'])
def get_capability_token():
    """Respond to incoming requests."""

    # Find these values at twilio.com/console
    account_sid = 'ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX'
    auth_token = 'your_auth_token'

    capability = TwilioCapability(account_sid, auth_token)

    # Twilio Application Sid
    application_sid = 'APXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX'
    capability.allow_client_outgoing(application_sid)
    token = capability.generate()

    return Response(token, mimetype='application/jwt')


if __name__ == "__main__":
    app.run(debug=True)
require 'twilio-ruby'
require 'sinatra'

get '/token' do
  account_sid = 'ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX'
  auth_token = 'your_auth_token'
  capability = Twilio::JWT::Capability.new(account_sid, auth_token)

  # Create an application sid at
  # twilio.com/console/phone-numbers/dev-tools/twiml-apps and use it here
  capability.allow_client_outgoing('APXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX')
  token = capability.generate

  content_type 'application/jwt'
  token
end

# TODO: post '/voice' do
package com.twilio;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

import com.twilio.sdk.client.TwilioCapability;

public class TwilioServlet extends HttpServlet {

    public static final String ACCOUNT_SID = "ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX";
    public static final String AUTH_TOKEN = "your_auth_token";

    public void service(HttpServletRequest request, HttpServletResponse response) throws IOException {

        // Find an application Sid from twilio.com/user/account/apps
        String applicationSid = "APXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX";
        TwilioCapability capability = new TwilioCapability(ACCOUNT_SID, AUTH_TOKEN);
        capability.allowClientOutgoing(applicationSid);

        String token = capability.generateToken();

        response.setContentType("application/jwt");
        response.getWriter().print(token);
    }
}
from flask import Flask, Response
from twilio.jwt.client import ClientCapabilityToken

app = Flask(__name__)


@app.route('/token', methods=['GET'])
def get_capability_token():
    """Respond to incoming requests."""

    # Find these values at twilio.com/console
    account_sid = 'ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX'
    auth_token = 'your_auth_token'

    capability = ClientCapabilityToken(account_sid, auth_token)

    # Twilio Application Sid
    application_sid = 'APXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX'
    capability.allow_client_outgoing(application_sid)
    token = capability.generate()

    return Response(token, mimetype='application/jwt')


if __name__ == "__main__":
    app.run(debug=True)
import java.io.IOException;
import java.util.List;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.google.common.collect.Lists;
import com.twilio.jwt.client.ClientCapability;
import com.twilio.jwt.client.OutgoingClientScope;
import com.twilio.jwt.client.Scope;

public class TwilioServlet extends HttpServlet {

  public static final String ACCOUNT_SID = "ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX";
  public static final String AUTH_TOKEN = "your_auth_token";

  public void service(HttpServletRequest request, HttpServletResponse response) throws IOException {
    // Find an application Sid from twilio.com/user/account/apps
    String applicationSid = "APXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX";

    List<Scope> scopes =
        Lists.newArrayList(new OutgoingClientScope.Builder(applicationSid).build());

    ClientCapability capability =
        new ClientCapability.Builder(ACCOUNT_SID, AUTH_TOKEN).scopes(scopes).build();

    String token = capability.toJwt();

    response.setContentType("application/jwt");
    response.getWriter().print(token);
  }
}
private void connect() {
    if (clientDevice != null) {
        // Create an outgoing connection
        connection = clientDevice.connect();
    } else {
        Toast.makeText(ClientActivity.this, "No existing device", Toast.LENGTH_SHORT).show();
    }
}
// Connect a call when button clicked
document.getElementById('button-call').onclick = function() {
  console.log('Calling...');
  Twilio.Device.connect();
};
- (IBAction)dialButtonPressed:(id)sender
{
    _connection = [_phone connect:nil delegate:nil];
}
private void connect(String contact, boolean isPhoneNumber) {
    ...

    Map<String, String> params = new HashMap<String, String>();
    params.put("To", contact);

    if (clientDevice != null) {
        // Create an outgoing connection
        connection = clientDevice.connect(params, this);
        setCallUI();
    } else {
        Toast.makeText(ClientActivity.this, "No existing device", Toast.LENGTH_SHORT).show();
    }
}
// Connect a call when button clicked
document.getElementById('button-call').onclick = function() {
  // get the phone number to connect the call to
  const params = { To: '15558675310' };

  console.log('Calling ' + params.To + '...');
  Twilio.Device.connect(params);
};
- (IBAction)dialButtonPressed:(id)sender
{
    NSDictionary *params = @{@"To": self.numberField.text};
    _connection = [_phone connect:params delegate:nil];
}
SDK Version:
  • 4.x
  • 5.x
SDK Version:
  • 6.x
  • 7.x
SDK Version:
  • 2.x
  • 3.x
SDK Version:
  • 4.x
  • 5.x
SDK Version:
  • 5.x
  • 6.x
SDK Version:
  • 4.x
  • 5.x
Format:
  • XML
const http = require('http');
const express = require('express');
const bodyParser = require('body-parser');
const twilio = require('twilio');

const app = express();
app.use(bodyParser.urlencoded({ extended: false }));

app.post('/voice', (req, res) => {
  // Create TwiML response
  const twiml = new twilio.TwimlResponse();

  if (req.body.To) {
    twiml.dial({ callerId: '+15017122661' }, function() {
      this.number(req.body.To);
    });
  } else {
    twiml.say('Thanks for calling!');
  }

  res.set('Content-Type', 'text/xml');
  res.send(twiml.toString());
});

app.get('/token', (req, res) => {
  // TODO: generate token
});

http.createServer(app).listen(1337, '127.0.0.1');
console.log('Twilio Client app server running at http://127.0.0.1:1337/');
const http = require('http');
const express = require('express');
const bodyParser = require('body-parser');
const VoiceResponse = require('twilio').twiml.VoiceResponse;

const app = express();
app.use(bodyParser.urlencoded({ extended: false }));

app.post('/voice', (req, res) => {
  // Create TwiML response
  const twiml = new VoiceResponse();

  if (req.body.To) {
    const dial = twiml.dial({ callerId: '+15017122661' });
    dial.number(req.body.To);
  } else {
    twiml.say('Thanks for calling!');
  }

  res.set('Content-Type', 'text/xml');
  res.send(twiml.toString());
});

app.get('/token', (req, res) => {
  // TODO: generate token
});

http.createServer(app).listen(1337, '127.0.0.1');
console.log('Twilio Client app server running at http://127.0.0.1:1337/voice/');
// In Package Manager, run:
// Install-Package Twilio.Mvc -DependencyVersion HighestMinor

using Twilio.Mvc;
using Twilio.TwiML;
using Twilio.TwiML.Mvc;

public class VoiceController : TwilioController
{
  [HttpPost]
  public ActionResult Index(VoiceRequest request)
  {
      var response = new TwilioResponse();
      if (!string.IsNullOrEmpty(request.To))
      {
        response.Dial(new Number(request.To), 
          new {callerId = "+15017122661"});
      }
      else
      {
        response.Say("Thanks for calling!");
      }
      return TwiML(response);
  }
}
<?php
// Get the PHP helper library from https://twilio.com/docs/libraries/php

// this line loads the library 
require('/path/to/twilio-php/Services/Twilio.php'); 

$response = new Services_Twilio_Twiml;

// get the phone number from the page request parameters, if given
if (isset($_REQUEST['To'])) {
    $number = htmlspecialchars($_REQUEST['To']);
    $response->dial(array(
        'callerId' => '+15017122661'
    ))->number($number);
} else {
    $response->say("Thanks for calling!");
}

echo $response;
require 'twilio-ruby'
require 'sinatra'

post '/voice' do
  twiml = Twilio::TwiML::Response.new do |r|
    if params['To']
      r.Dial callerId: '+15017122661' do |d|
        d.Number params['To']
      end
    else
      r.Say 'Thanks for calling!'
    end
  end

  content_type 'text/xml'
  twiml.text
end

# TODO: get '/token' do
// In Package Manager, run:
// Install-Package Twilio.Mvc -DependencyVersion HighestMinor

using System.Web.Mvc;
using Twilio.TwiML;

public class VoiceController : Controller
{
    [HttpPost]
    public ActionResult Index(VoiceRequest request)
    {
        var response = new VoiceResponse();
        if (!string.IsNullOrEmpty(request.To))
        {
            var number = new Dial(callerId: "+15017122661");
            number.Number(Request.To);

            response.Dial(number);
        }
        else
        {
            response.Say("Thanks for calling!");
        }

        return Content(response.ToString(), "text/xml");
    }
}
<?php
// Get the PHP helper library from https://twilio.com/docs/libraries/php

// this line loads the library 
require('vendor/autoload.php'); 
use Twilio\TwiML;

$response = new TwiML;

// get the phone number from the page request parameters, if given
if (isset($_REQUEST['To'])) {
    $number = htmlspecialchars($_REQUEST['To']);
    $response->dial(array(
        'callerId' => '+15017122661'
    ))->number($number);
} else {
    $response->say("Thanks for calling!");
}

echo $response;
from flask import Flask, Response, request
import twilio.twiml

app = Flask(__name__)


@app.route("/voice", methods=['POST'])
def get_voice_twiml():
    """Respond to incoming calls with a simple text message."""

    resp = twilio.twiml.Response()
    if "To" in request.form:
        resp.dial(callerId="+15017122661").number(request.form["To"])
    else:
        resp.say("Thanks for calling!")

    return Response(str(resp), mimetype='text/xml')


if __name__ == "__main__":
    app.run(debug=True)
require 'twilio-ruby'
require 'sinatra'

post '/voice' do
  twiml = Twilio::TwiML::Response.new do |r|
    if params['To']
      r.Dial callerId: '+15017122661' do |d|
        d.Number params['To']
      end
    else
      r.Say 'Thanks for calling!'
    end
  end

  content_type 'text/xml'
  twiml.text
end

# TODO: get '/token' do
package com.twilio;

import java.io.IOException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.twilio.sdk.verbs.TwiMLResponse;
import com.twilio.sdk.verbs.TwiMLException;
import com.twilio.sdk.verbs.Say;
import com.twilio.sdk.verbs.Dial;
import com.twilio.sdk.verbs.Number;

@WebServlet(name = "TwilioServlet", urlPatterns = {"/voice"})
public class TwilioServlet extends HttpServlet {

    // service() responds to both GET and POST requests.
    // You can also use doGet() or doPost()
    public void service(HttpServletRequest request, HttpServletResponse response) throws IOException {
        TwiMLResponse twiml = new TwiMLResponse();
        try {
            String to = request.getParameter("To");
            if (to != null) {
                Dial dial = new Dial();
                dial.setCallerId("+15017122661");
                dial.append(new Number(to));
                twiml.append(dial);
            } else {
                twiml.append(new Say("Thanks for calling!"));
            }
        } catch (TwiMLException e) {
            e.printStackTrace();
        }

        response.setContentType("application/xml");
        response.getWriter().print(twiml.toXML());
    }
}
from flask import Flask, Response, request
from twilio.twiml.voice_response import VoiceResponse

app = Flask(__name__)


@app.route("/voice", methods=['POST'])
def get_voice_twiml():
    """Respond to incoming calls with a simple text message."""

    resp = VoiceResponse()
    if "To" in request.form:
        resp.dial(request.form["To"], caller_id="+15017122661")
    else:
        resp.say("Thanks for calling!")

    return Response(str(resp), mimetype='text/xml')


if __name__ == "__main__":
    app.run(debug=True)
import java.io.IOException;

import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.twilio.twiml.*;
import com.twilio.twiml.voice.Number;

@WebServlet(name = "TwilioServlet", urlPatterns = {"/voice"})
public class TwilioServlet extends HttpServlet {
  // service() responds to both GET and POST requests.
  // You can also use doGet() or doPost()
  public void service(HttpServletRequest request, HttpServletResponse response) throws IOException {
    String to = request.getParameter("To");

    VoiceResponse.Builder responseBuilder = new VoiceResponse.Builder();

    if (to != null) {
      Number number = new Number.Builder(to).build();
      Dial dial = new Dial.Builder()
          .number(number)
          .callerId("+15017122661")
          .build();

      responseBuilder = responseBuilder.dial(dial);
    } else {
      Say say = new Say.Builder("Thanks for calling!").build();
      responseBuilder = responseBuilder.say(say);
    }

    VoiceResponse twiml = responseBuilder.build();

    response.setContentType("application/xml");

    try {
      response.getWriter().print(twiml.toXml());
    } catch (TwiMLException e) {
      e.printStackTrace();
    }
  }
}
<?xml version="1.0" encoding="utf-8"?>
<Response>
  <Dial callerId="+15017122661">
    <Number>+15558675310</Number>
  </Dial>
</Response>
private void disconnect() {
    if (activeConnection != null) {
        activeConnection.disconnect();
        activeConnection = null;
    }
}
// Connect a call when button clicked
document.getElementById('button-hangup').onclick = function() {
  console.log('Hanging up...');
  Twilio.Device.disconnectAll();
};
- (IBAction)hangupButtonPressed:(id)sender
{
    [_connection disconnect];
}