Free trial *Internet Service Required

How to use Twilio for voice and SMS capabilities from Windows Azure

This guide demonstrates how to perform common programming tasks with the Twilio API service on Windows Azure. The scenarios covered include making a phone call and sending a Short Message Service (SMS) message. For more information on Twilio and using voice and SMS in your applications, see the Next steps section.

Table of Contents

What is Twilio?What is Twilio?

Twilio is a telephony web-service API that lets you use your existing web languages and skills to build voice and SMS applications. Twilio is a third-party service (not a Windows Azure feature and not a Microsoft product).

Twilio Voice allows your applications to make and receive phone calls. Twilio SMS allows your applications to make and receive SMS messages. Twilio Client allows your applications to enable voice communication using existing Internet connections, including mobile connections.

Twilio pricing and offersTwilio pricing and special offers

Information about Twilio pricing is available at Twilio pricing. Windows Azure customers receive a special offer: a free credit of 1000 texts or 1000 inbound minutes. To sign up for this offer or get more information, please visit http://ahoy.twilio.com/azure.

ConceptsConcepts

The Twilio API is a RESTful API that provides voice and SMS functionality for applications. Client libraries are available in multiple languages; for a list, see Twilio API Libraries.

Key aspects of the Twilio API are Twilio verbs and Twilio Markup Language (TwiML).

Twilio verbs

The API makes use of Twilio verbs; for example, the <Say> verb instructs Twilio to audibly deliver a message on a call.

The following is a list of Twilio verbs.

  • <Dial>: Connects the caller to another phone.
  • <Gather>: Collects numeric digits entered on the telephone keypad.
  • <Hangup>: Ends a call.
  • <Play>: Plays an audio file.
  • <Pause>: Waits silently for a specified number of seconds.
  • <Record>: Records the caller’s voice and returns a URL of a file that contains the recording.
  • <Redirect>: Transfers control of a call or SMS to the TwiML at a different URL.
  • <Reject>: Rejects an incoming call to your Twilio number without billing you
  • <Say>: Converts text to speech that is made on a call.
  • <Sms>: Sends an SMS message.

TwiML

TwiML is a set of XML-based instructions based on the Twilio verbs that inform Twilio of how to process a call or SMS.

As an example, the following TwiML would convert the text Hello World to speech.

<?xml version="1.0" encoding="UTF-8" ?>
<Response>
   <Say>Hello World</Say>
</Response>

When your application calls the Twilio API, one of the API parameters is the URL that returns the TwiML response. For development purposes, you can use Twilio-provided URLs to provide the TwiML responses used by your applications. You could also host your own URLs to produce the TwiML responses, and another option is to use the TwiMLResponse object.

For more information about Twilio verbs, their attributes, and TwiML, see TwiML. For additional information about the Twilio API, see Twilio API.

Create an accountCreate a Twilio account

When you’re ready to get a Twilio account, sign up at Try Twilio. You can start with a free account, and upgrade your account later.

When you sign up for a Twilio account, you’ll receive an account ID and an authentication token. Both will be needed to make Twilio API calls. To prevent unauthorized access to your account, keep your authentication token secure. Your account ID and authentication token are viewable at the Twilio account page, in the fields labeled ACCOUNT SID and AUTH TOKEN, respectively.

Verify phone numbersVerify phone numbers

Various phone numbers need to be verified with Twilio for your account. For example, if you want to place outbound phone calls, the phone number must be verified as an outbound caller ID with Twilio. Similarly, if you want a phone number to receive SMS messages, the receiving phone number must be verified with Twilio. For information on how to verify a phone number, see Manage numbers. Some of the code below relies on phone numbers that you will need to verify with Twilio.

As an alternative to using an existing number for your applications, you can purchase a Twilio phone number. For information about purchasing a Twilio phone number, see Twilio Phone Numbers Help.

Create an applicationCreate a Windows Azure application

A Windows Azure application that hosts a Twilio enabled application is no different from any other Windows Azure application. You simply add the Twilio .NET library and configure the role to use the Twilio .NET libraries. For information on creating an initial Windows Azure project, see Creating a Windows Azure project with Visual Studio.

Configure your app for TwilioConfigure your application to use Twilio libraries

Twilio provides a set of .NET helper libraries that wrap various aspects of Twilio to provide simple and easy ways to interact with the Twilio REST API and Twilio Client to generate TwiML responses.

Twilio provides five libraries for .NET developers:

LibraryDescription
Twilio.API The core Twilio library that wraps the Twilio REST API in a friendly .NET library. This library is available for .NET, Silverlight, and Windows Phone 7.
Twilio.TwiML Provides a .NET friendly way to generate TwiML markup.
Twilio.MVC For developers using ASP.NET MVC, this library includes a TwilioController and TwiML ActionResult and request validation attribute.
Twilio.WebMatrix For developers using Microsoft's free WebMatrix development tool, this library contains Razor syntax helpers for various Twilio actions.
Twilio.Client.Capability Contains the Capability token generator for use with the Twilio Client JavaScript SDK.

Note that all libraries require .NET 3.5, Silverlight 4, or Windows Phone 7 or later.

The samples provided in this guide use the Twilio.API library.

The libraries are provided in binary form on GithHub and can be installed using the NuGet package manager extension available for Visual Studio 2010. The GitHub repo site also includes a Wiki that contains complete documentation for using the libraries.

By default, Microsoft Visual Studio 2010 installs version 1.2 of NuGet. Installing the Twilio libraries requires version 1.6 of NuGet or higher. For information on installing or updating NuGet, see http://nuget.org/.

Note

To install the latest verison of NuGet, you must first uninstall the loaded version using the Visual Studio Extension Manager. To do so, you must run Visual Studio as administrator. Otherwise, the Uninstall button is disabled.

To add the Twilio libraries to your Visual Studio project:

  1. Open your solution in Visual Studio.
  2. Right-click References.
  3. Click Manage NuGet Packages...
  4. Click Online.
  5. In the search online box, type twilio.
  6. Click Install on the Twilio package.

Make a callHow to: Make an outgoing call

The following screenshot shows how to make an outgoing call using the TwilioRestClient class. This code also uses a Twilio-provided site to return the Twilio Markup Language (TwiML) response. Substitute your values for the From and To phone numbers, and ensure that you verify the From phone number for your Twilio account prior to running the code.

// Use your account SID and authentication token instead
// of the placeholders shown here.
string accountSID = "your_twilio_account";
string authToken = "your_twilio_authentication_token";

// Create an instance of the Twilio client.
TwilioRestClient client;
client = new TwilioRestClient(accountSID, authToken);

// Use the Twilio-provided site for the TwiML response.
String Url="http://twimlets.com/message";
Url = Url + "?Message%5B0%5D=Hello%20World";

// Instantiate the call options that are passed
// to the outbound call
CallOptions options = new CallOptions();


// Set the call From, To, and URL values to use for the call.
// This sample uses the sandbox number provided by
// Twilio to make the call.
options.From = "+NNNNNNNNNN";
options.To = "NNNNNNNNNN";
options.Url = Url;

// Make the call.
var call = client.InitiateOutboundCall(options);

For more information about the parameters passed in to the client.InitiateOutboundCall method, see http://www.twilio.com/docs/api/rest/making-calls.

As mentioned, this code uses a Twilio-provided site to return the TwiML response. You could instead use your own site to provide the TwiML response. For more information, see How to: Provide TwiML responses from your own web site.

Send an SMS messageHow to: Send an SMS message

The following screenshot shows how to send an SMS message using the TwilioRestClient class. The From number, 4155992671, is provided by Twilio for trial accounts to send SMS messages. The To number must be verified for your Twilio account before you run the code.

// Use your account SID and authentication token instead
    // of the placeholders shown here.
    string accountSID = "your_twilio_account";
    string authToken = "your_twilio_authentication_token";

    // Create an instance of the Twilio client.
    TwilioRestClient client;
    client = new TwilioRestClient(accountSID, authToken);

    // Retrieve the account, used later to create an instance
    // of the client.
    Twilio.Account account = client.GetAccount();

    // Send an SMS message.
    SMSMessage result = client.SendSmsMessage(
        "+14155992671", "+12069419717", "This is my SMS message.");

    if (result.RestException != null)
    {
        //an exception occurred making the REST call
        string message = result.RestException.Message;
    }

Provide TwiML responses from your own siteHow to: Provide TwiML responses from your own web site

When your application initiates a call to the Twilio API - for example, via the client.InitiateOutboundCall method - Twilio sends your request to a URL that is expected to return a TwiML response. The example in How to: Make an outgoing call uses the Twilio-provided URL http://twimlets.com/message to return the response.

Note

While TwiML is designed for use by web services, you can view the TwiML in your browser. For example, click [http://twimlets.com/message][twimlet_message_url] to see an empty <Response> element; as another example, click [http://twimlets.com/message?Message%5B0%5D=Hello%20World][twimlet_message_url_hello_world] to see a <Response> element that contains a <Say> element.

Instead of relying on the Twilio-provided URL, you can create your own URL site that returns HTTP responses. You can create the site in any language that returns HTTP responses. This topic assumes you’ll be hosting the URL from an ASP.NET generic handler.

The following ashx page results in a TwiML response that says Hello World on the call.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace WebRole1
{
    /// <summary>
    /// Summary description for Handler1
    /// </summary>
    public class Handler1 : IHttpHandler
    {

        public void ProcessRequest(HttpContext context)
        {
            context.Response.Clear();
            context.Response.ContentType = "text/xml";
            context.Response.ContentEncoding = System.Text.Encoding.UTF8;
            string twiMLResponse = "<Response><Say>Hello World</Say></Response>";
            context.Response.Write(twiMLResponse);
            context.Response.End();
        }

        public bool IsReusable
        {
            get
            {
                return false;
            }
        }
    }
}

The following ashx page results in a TwiML response that says some text, has several pauses, and reports the Twilio API version.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace WebRole1
{
    /// <summary>
    /// Summary description for Handler1
    /// </summary>
    public class Handler1 : IHttpHandler
    {

        public void ProcessRequest(HttpContext context)
        {
            // Instantiate an instance of the Twilio client.
            string accountSID = "ACNNNNNNNNNNNNNNNNNNNNNNNNNNNNNN";
            string authToken =  "NNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNN";
            var client = new Twilio.TwilioRestClient(accountSID, authToken);

            var twiml = new Twilio.TwiML.TwilioResponse();
            twiml.BeginGather()
                .Say("Hello from Windows Azure")
                .Pause()
                .Say("The Twilio API version is " + client.ApiVersion + ".")
                .Pause()
                .Say("Good bye.");
            twiml.EndGather();

            context.Response.Clear();
            context.Response.ContentType = "text/xml";
            context.Response.Write(twiml.ToString());
            context.Response.End();
        }

        public bool IsReusable
        {
            get
            {
                return false;
            }
        }
    }
}

To see the available request parameters for Twilio voice and SMS requests, see https://www.twilio.com/docs/api/twiml/twilio_request and https://www.twilio.com/docs/api/twiml/sms/twilio_request, respectively.

Once you have set up your handler to provide TwiML responses, use the URL of the page as the URL passed into the client.InitiateOutboundCall method. For example, if you have a web application named MyTwiML deployed to a Windows Azure cloud service, and the name of the cshtml page is mytwiml.ashx, the URL can be passed to client.InitiateOutboundCall as shown in the following code sample:

// Place the call From, To, and URL values into a hash map.
// This sample uses the sandbox number provided by Twilio to make the call.
options.From = "NNNNNNNNNN";
options.To = "NNNNNNNNNN";
options.Url = "http://<your_hosted_service>.cloudapp.net/MyTwiML/mytwiml.ashx";

// Place the call.
var call = client.InitiateOutboundCall(options);

For additional information about using Twilio on Windows Azure with ASP.NET, see How to make a phone call using Twilio in a web role on Windows Azure.

How to: Use Additional Twilio Services

In addition to the examples shown here, Twilio offers web-based APIs that you can use to leverage additional Twilio functionality from your Windows Azure application. For full details, see the Twilio API documentation.

Next Steps

Now that you’ve learned the basics of the Twilio service, follow these links to learn more:

Rss Newsletter