Using SMS and Voice Services via Twilio

Twilio is powering the future of business communications, enabling developers to embed voice, VoIP, and messaging into applications. They virtualize all infrastructure needed in a cloud-based, global environment, exposing it through the Twilio communications API platform. Applications are simple to build and scalable. Enjoy flexibility with pay-as-you go pricing, and benefit from cloud reliability.

Twilio Voice enables your application to make and receive phone calls. Twilio SMS enables your application to send and receive text messages. Twilio Client allows you to make VoIP calls from any phone, tablet, or browser and supports WebRTC.

Pricing

Google App Engine customers receive complimentary credit for SMS messages or inbound minutes when you upgrade.

Twilio is a pay-as-you-go service. There are no set-up fees and you can close your account at any time. You can find more details at Twilio Pricing.

Platform

The Twilio platform consists of the Twilio Markup Language (TwiML), a RESTful API and VoIP SDKs for web browsers, Android and iOS. Helper libraries are available in multiple languages. You can find the full list at Twilio Helper Libraries.

TwiML

TwiML is a set of instructions that you can use to tell Twilio what to do when you receive an incoming call or SMS. When someone makes a call or sends an SMS to one of your Twilio numbers, Twilio will look up the URL associated with that phone number and make a request to that URL. Twilio will read TwiML instructions at that URL to determine what to do:

  • <Say> - text to speech
  • <Record> - record the call
  • <Play> - play a message for the caller
  • <Gather> - prompt the caller to press digits on their keypad
  • <Message> - send a message

Learn about the other verbs and capabilities from the Twilio Markup Language documentation.

REST API

The Twilio REST API allows you to query metadata about your account, phone numbers, calls, text messages, and recordings. You can also do some fancy things like initiate outbound calls and send text messages.

Since the API is based on REST principles, it's very easy to write and test applications. You can use your browser to access URLs, and you can use pretty much any HTTP client in any programming language to interact with the API. For more information, see the Twilio REST API.

Copying the sample code

A complete code sample showing integration with Twilio is available at Github. If you want to use this sample code, copy it to your local machine:

git clone https://github.com/GoogleCloudPlatform/java-docs-samples
cd java-docs-samples/flexible/twilio

Setup

To use Twilio to receive an incoming call, send an SMS, or receive an SMS:

  1. Create a project. For further instructions, see "Hello, World!" for Java on App Engine.

  2. Create a Twilio account.

  3. In Twilio, create a number. Configure the URLs for your Twilio number as needed for your app. For example, for the sample code:

    • Configure the voice request URL to be https://[your-app-id].appspot.com/call/receive
    • Configure the SMS request URL to be https://[your-app-id].appspot.com/sms/receive
  4. Configure your Twilio settings in the environment variables section in app.yaml. For example, for the sample code:

    env_variables:
      TWILIO_ACCOUNT_SID: YOUR-TWILIO-ACCOUNT-SID
      TWILIO_AUTH_TOKEN: YOUR-TWILIO-AUTH-TOKEN
      TWILIO_NUMBER: YOUR-TWILIO-NUMBER

  5. Add Twilio's Java library to your application. If you use Maven, you can add the library to the project's pom.xml. For example, see this sample code:

    <dependency>
      <groupId>com.twilio.sdk</groupId>
      <artifactId>twilio-java-sdk</artifactId>
      <version>6.3.0</version>
    </dependency>

    App Engine will ensure all dependencies declared in pom.xml will be installed when you deploy your application.

  6. To prepare for local testing of your app, set the environment variables on your local machine using the command line. For example, for the sample code:

    export TWILIO_ACCOUNT_SID=[your-twilio-account-sid]
    export TWILIO_AUTH_TOKEN=[your-twilio-auth-token]
    export TWILIO_NUMBER=[your-twilio-number]
    
  7. You can run the application locally to test the callbacks and SMS sending. For example, using Maven:

    mvn clean jetty:run
    

Receiving an incoming call

After you complete Setting up, create your first application:

The ReceiveCallServlet.java shows how to respond to an incoming call and return TwiML instructions:

@SuppressWarnings("serial")
@WebServlet(name = "receivecall", value = "/call/receive")
public class ReceiveCallServlet extends HttpServlet {

  @Override
  public void service(HttpServletRequest req, HttpServletResponse resp) throws IOException,
      ServletException {
    TwiMLResponse twiml = new TwiMLResponse();
    Say say = new Say("Hello from Twilio!");
    try {
      twiml.append(say);
    } catch (TwiMLException e) {
      throw new ServletException("Twilio error", e);
    }

    resp.setContentType("application/xml");
    resp.getWriter().print(twiml.toXML());
  }
}
  1. Deploy your project to App Engine. After you deploy your project, you can send a POST request to http://your-app-id.appspot.com/call/receive, which returns the following text:

    <?xml version="1.0" encoding="UTF-8"?>
      <Response>
        <Say>Hello from Twilio!</Say>
      </Response>
    
  2. Copy and paste the http://your-app-id.appspot.com/call/receive URL into the Voice URL box on the Numbers page of your Twilio Account.

  3. Now call your Twilio number! You should hear a voice say "Hello from Twilio!" in response. When you call, Twilio will fetch your URL, and execute the XML instructions listed above. Then Twilio will hang up, because there are no more instructions.

Sending an SMS

To send an outgoing SMS using Twilio, you can use the Twilio Java helper library and Java classes included in the JAR file.

The SendSmsServlet.java shows how to send an SMS:

@SuppressWarnings("serial")
@WebServlet(name = "sendsms", value = "/sms/send")
public class SendSmsServlet extends HttpServlet {

  @Override
  public void service(HttpServletRequest req, HttpServletResponse resp) throws IOException,
      ServletException {
    final String twilioAccountSid = System.getenv("TWILIO_ACCOUNT_SID");
    final String twilioAuthToken = System.getenv("TWILIO_AUTH_TOKEN");
    final String twilioNumber = System.getenv("TWILIO_NUMBER");
    final String toNumber = (String) req.getParameter("to");
    if (toNumber == null) {
      resp.getWriter()
          .print("Please provide the number to message in the \"to\" query string parameter.");
      return;
    }
    TwilioRestClient client = new TwilioRestClient(twilioAccountSid, twilioAuthToken);
    Account account = client.getAccount();
    MessageFactory messageFactory = account.getMessageFactory();
    List<NameValuePair> params = new ArrayList<NameValuePair>();
    params.add(new BasicNameValuePair("To", toNumber));
    params.add(new BasicNameValuePair("From", twilioNumber));
    params.add(new BasicNameValuePair("Body", "Hello from Twilio!"));
    try {
      Message sms = messageFactory.create(params);
      resp.getWriter().print(sms.getBody());
    } catch (TwilioRestException e) {
      throw new ServletException("Twilio error", e);
    }
  }
}
  1. Change the to parameter to use a real phone number. The to number can be any outgoing number, such as your mobile phone number.

  2. Deploy the updated code, and then send the SMS by putting this URL into a web browser: http://your-app-id.appspot.com/sms/send

Receiving an SMS

To receive an incoming SMS using Twilio, you can use the Twilio Java helper library.

The ReceiveSmsServlet.java shows how to respond to an incoming SMS and return TwiML instructions:

@SuppressWarnings("serial")
@WebServlet(name = "receivesms", value = "/sms/receive")
public class ReceiveSmsServlet extends HttpServlet {

  @Override
  public void service(HttpServletRequest request, HttpServletResponse response) throws IOException,
      ServletException {
    String fromNumber = request.getParameter("From");
    String body = request.getParameter("Body");
    String message = String.format("Hello, %s, you said %s", fromNumber, body);

    TwiMLResponse twiml = new TwiMLResponse();
    Message sms = new Message(message);
    try {
      twiml.append(sms);
    } catch (TwiMLException e) {
      throw new ServletException("Twilio error", e);
    }

    response.setContentType("application/xml");
    response.getWriter().print(twiml.toXML());
  }
}

Deploy your updated code to App Engine, and then send an SMS to your Twilio number. You should receive a greeting in response.

Learning More about Twilio

Now that you've used some basic features, learn about more features and some best practices for building secure and scalable applications:

Send feedback about...

App Engine flexible environment for Java docs