Sending a Message via Phone from your Web Application

Twilio makes sending audio messages from your application to a telephone easy. Let’s go through a simple example of how to initiate a call to a phone number and play a message when the call is answered

First, we will need a simple TwiML document to play the message.

<!– http://my.example.com/sayMsg.xml –>
<Response>
<Say>Hello! This was a message sent by Twilio</Say>
</Response>

Save the text of this doc to a file on a public web server. Test it by putting the URL for it into your browser and making sure it loads. This is the URL that will instruct Twilio what to say to the party you are calling when they answer.

Next, we will actually make the outgoing phone call. I will be using PHP for this example, but the process is much the same in other languages. You will need a couple things: your Twilio AccountSid and AuthToken, avalidated caller Id, and optionally the REST helper library for your language of choice.

We will be making a REST API call to Twilio, telling it to make an outgoing call to a phone number and to follow the instructions in a TwiML doc when the called party picks up. The call will show your validated caller Id.

Here is the php code to make the call. Replace the AccountSid, AuthToken, PhoneNumberToCall, and VerifiedCallerId variables with your own information.

makeCall.php

<?php
/* Include the PHP TwilioRest library */
require “twiliorest.php”;

/* Twilio REST API version */
$ApiVersion = “2008-08-01″;

/* Replace these values with your specific info */
$AccountSid = “ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX”;
$AuthToken = “YYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYY”;
$PhoneNumberToCall=”XXX-XXX-XXXX”;
$VerifiedCallerId=”YYY-YYY-YYYY”;

/* Instantiate a new Twilio Rest Client */
$client = new TwilioRestClient($AccountSid, $AuthToken);

/* Initiate a new outbound call by POST’ing to the Calls resource */
$response = $client->request(“/$ApiVersion/Accounts/$AccountSid/Calls”,
“POST”, array(
“Caller” => $VerifiedCallerId,
“Called” => $PhoneNumberToCall,
“Url” => “http://my.example.com/sayMsg.xml”
));
if($response->IsError)
echo “Error: {$response->ErrorMessage}”;
else
echo “Started call: {$response->ResponseXml->Call->Sid}”;
?>

php makeCall.php should initiate a call to the phone number you specified. When the called party answers, Twilio will play the message in sayMsg.xml. By replacing the sayMsg.xml URL with one that points to a dynamic page, you can easily customize the output of the message for your own purposes.

More detailed discussions of both TwiML and making outgoing calls can be found in our quickstart tutorials.