:::: MENU ::::
Posts tagged with: API

Getting started with Twilio Phone Services

Today I am going to talk about how to create a simple phone application using the popular Twilio API. If you don’t know what Twilio is all about then I recommend you go through their “What is Cloud Communications” section.

Twilio

Twilio

When I was working for Infofree I was given a task to come up with a basic SMS and Voice Authentication system using any available services out there. My two options back then was either Corvisa (now Shoretel) or Twilio. I tried to work with Corvisa and their API but, it lacked a lot of features that Twilio has. So ultimately, I decided to build the feature using Twilio. Sadly, because of economic reasons for my company my code was never live. But, in my free time I went further and used Twilio’s service to test different features.

In this tutorial I will show you how to setup basic twilio service using JAVA.

These are some of the things you will need in order for yor app to work.

  1. Twilio Account SID TWILIO_ACCOUNT_SID
  2. Twilio Authentication Token TWILIO_AUTH_TOKEN
  3. Twilio Number TWILIO_NUMBER
  4. Twilio Application SID (Optional)
  5. Twilio Agent Number (Optional)

Get API Key

Go to twilio and click on the “Get a Free API Key button”.

Get a Free API Key - Twilio

Get a Free API Key – Twilio

Go through the general registration process (should be easy). You need to verify using your phone number.

After you are done, go to Home-> Settings-> General

You should see your  TWILIO_ACCOUNT_SID and TWILIO_AUTH_TOKEN

Get Phone Number

If you plan to use your number then you do not need to get TWILIO_NUMBER else click here and get a phone number. For trial purposes you can only use verified phone numbers.

Get a new phone number

Get a new phone number

You should see this number in your Manage Numbers section.

 

Things you’ll need for JAVA

If you use maven, you need to add this dependency in your pom.xml file:

<dependency>
  <groupId>com.twilio.sdk</groupId>
  <artifactId>twilio</artifactId>
  <version>(7.0,7.9)</version>
</dependency>

If you don’t use maven, use this jar file instead: twilio-7.x.x-with-dependencies.jar

Here I will be using a properties file (db.properties) to store all my API credentials

#mysql DB properties
DB_DRIVER_CLASS=com.mysql.jdbc.Driver
DB_URL=jdbc:mysql://localhost:3306/test
DB_USERNAME=username
DB_PASSWORD=password

TWILIO_ACCOUNT_SID=ACed9da74780242eded3a2fb674a*****
TWILIO_AUTH_TOKEN=fac36407eb1bf66f207d2763671*****
TWILIO_NUMBER=+14023789330
TWILIO_APPLICATION_SID=

Once you have everything setup, we can use Twilio’s API library to do various tasks.

Go ahead and download this sample code to play around some of the features.

I also created a Phone Verification system where you could verify phone using either a SMS or a Voice Call. But because it was part of my company project, I cannot share the code with you. But here is the screenshot of how it looks like.

Phone Verification using Twilio

Phone Verification using Twilio

Following are some of the examples:

Send SMS

SendSMS

SendSMS

 

package com.twilioAPI;

import com.twilio.sdk.resource.instance.Account;
import com.twilioAPI.exceptions.UndefinedEnvironmentVariableException;
import com.twilioAPI.lib.AppSetup;
import com.twilio.sdk.TwilioRestClient;
import com.twilio.sdk.TwilioRestException;
import com.twilio.sdk.resource.factory.MessageFactory;
import com.twilio.sdk.resource.instance.Message;
import java.util.ArrayList;
import java.util.List;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Servlet implementation class sendSMS
 */
@WebServlet("/sendSMS")
public class SendSMS extends HttpServlet {
	private static final long serialVersionUID = 1L;
	private AppSetup appsetup;
    /**
     * @see HttpServlet#HttpServlet()
     */
    public SendSMS() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		response.getWriter().append("Served at: ").append(request.getContextPath());
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		doGet(request, response);
		this.appsetup = new AppSetup();
		try {
			String accountSid = this.appsetup.getAccountSid();
			String authToken = this.appsetup.getAuthToken();
			String fromNumber = this.appsetup.getTwilioNumber();
			TwilioRestClient client = new TwilioRestClient(accountSid, authToken);
			String pNumber = request.getParameter("phoneSMS");
			String pMessage = request.getParameter("testSMS");
			Account account = client.getAccount();
			MessageFactory messageFactory = account.getMessageFactory();
	        List<NameValuePair> params = new ArrayList<NameValuePair>();
	        params.add(new BasicNameValuePair("To", pNumber)); // Replace with a valid phone number for your account.
	        params.add(new BasicNameValuePair("From", fromNumber)); // Replace with a valid phone number for your account.
	        params.add(new BasicNameValuePair("Body", pMessage));
	        Message sms = messageFactory.create(params);
	        System.out.println("Sending SMS...: To:" + pNumber + "From:"+ fromNumber+ "and Message:" +pMessage);
		} catch (UndefinedEnvironmentVariableException | TwilioRestException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
        
		
		
		
		
	}

}

Click-to-Call

Click-to-Call

Click-to-Call

 

package com.twilioAPI;

import com.twilioAPI.exceptions.UndefinedEnvironmentVariableException;
import com.twilioAPI.lib.AppSetup;
import com.twilio.sdk.TwilioRestClient;
import com.twilio.sdk.TwilioRestException;
import org.json.simple.JSONObject;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;
/**
 * Servlet implementation class Call
 */
@WebServlet("/Call")
public class Call extends HttpServlet {
	private static final long serialVersionUID = 1L;
	 AppSetup appSetup;
	  TwilioRestClient client;

	  public Call() {}

	  public Call(AppSetup appSetup, TwilioRestClient client) {
	    this.appSetup = appSetup;
	    this.client = client;
	  }
	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		response.getWriter().append("Served at: ").append(request.getContextPath());
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
	    String phoneNumber = request.getParameter("phone");
	    if(phoneNumber==null||phoneNumber==""){
	    	phoneNumber = request.getParameter("phoneNumber");
	    }
	    boolean record = request.getParameter( "record" ) != null;
	    String CallRecord = "false";
	    if (record == true){
	    	CallRecord = "true";
	    }
	    request.getServletContext().setAttribute("record", CallRecord);
	    
	    if (phoneNumber != null) {
	      if (this.appSetup == null || this.client == null) {
	        appSetup = new AppSetup();
	        client = null;
	        try {
	          client = new TwilioRestClient(appSetup.getAccountSid(), appSetup.getAuthToken());
	        } catch (UndefinedEnvironmentVariableException e) {
	          response.getOutputStream().write(getJSONResponse(e.getMessage()).getBytes());
	          return;
	        }
	      }

	      Map<String, String> params = new HashMap<>();
	      String twilioNumber;
	      try {
	        twilioNumber = appSetup.getTwilioNumber();
	      } catch (UndefinedEnvironmentVariableException e) {
	        response.getOutputStream().write(getJSONResponse(e.getMessage()).getBytes());
	        return;
	      }

	      // Full path to the end point that will respond with the call TwiML
	      //String path = request.getRequestURL().toString().replace(request.getRequestURI(), "") + "/CorvisaAPI/connect?record="+CallRecord;
	      String path = request.getRequestURL().toString().replace(request.getRequestURI(), "") + "/CorvisaAPI/connect";
	      params.put("From", twilioNumber);
	      params.put("To", phoneNumber);
	      params.put("Url", path);
	      try {
	        client.getAccount().getCallFactory().create(params);
	      } catch (TwilioRestException e) {
	        String message = "Twilio rest client error: " + e.getErrorMessage() +
	            "\nRemember not to use localhost to access this app, use your ngrok URL";
	        response.getOutputStream().write(getJSONResponse(message).getBytes());
	        return;
	      }
	      response.getOutputStream().write(getJSONResponse("Phone call incoming!").getBytes());
	    } else {
	      response.getOutputStream()
	          .write(getJSONResponse("The phone number field can't be empty").getBytes());
	    }
	}
	private String getJSONResponse(String message) {
	    JSONObject obj = new JSONObject();
	    obj.put("message", message);
	    obj.put("status", "ok");

	    return obj.toJSONString();
	  }

}

Web Phone

WebPhone

WebPhone

package com.twilioAPI;

import com.twilioAPI.exceptions.UndefinedEnvironmentVariableException;
import com.twilioAPI.lib.AppSetup;
import com.twilio.sdk.TwilioRestClient;
import com.twilio.sdk.TwilioRestException;
import org.json.simple.JSONObject;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;
/**
 * Servlet implementation class Call
 */
@WebServlet("/Call")
public class Call extends HttpServlet {
	private static final long serialVersionUID = 1L;
	 AppSetup appSetup;
	  TwilioRestClient client;

	  public Call() {}

	  public Call(AppSetup appSetup, TwilioRestClient client) {
	    this.appSetup = appSetup;
	    this.client = client;
	  }
	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		response.getWriter().append("Served at: ").append(request.getContextPath());
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
	    String phoneNumber = request.getParameter("phone");
	    if(phoneNumber==null||phoneNumber==""){
	    	phoneNumber = request.getParameter("phoneNumber");
	    }
	    boolean record = request.getParameter( "record" ) != null;
	    String CallRecord = "false";
	    if (record == true){
	    	CallRecord = "true";
	    }
	    request.getServletContext().setAttribute("record", CallRecord);
	    
	    if (phoneNumber != null) {
	      if (this.appSetup == null || this.client == null) {
	        appSetup = new AppSetup();
	        client = null;
	        try {
	          client = new TwilioRestClient(appSetup.getAccountSid(), appSetup.getAuthToken());
	        } catch (UndefinedEnvironmentVariableException e) {
	          response.getOutputStream().write(getJSONResponse(e.getMessage()).getBytes());
	          return;
	        }
	      }

	      Map<String, String> params = new HashMap<>();
	      String twilioNumber;
	      try {
	        twilioNumber = appSetup.getTwilioNumber();
	      } catch (UndefinedEnvironmentVariableException e) {
	        response.getOutputStream().write(getJSONResponse(e.getMessage()).getBytes());
	        return;
	      }

	      // Full path to the end point that will respond with the call TwiML
	      //String path = request.getRequestURL().toString().replace(request.getRequestURI(), "") + "/CorvisaAPI/connect?record="+CallRecord;
	      String path = request.getRequestURL().toString().replace(request.getRequestURI(), "") + "/CorvisaAPI/connect";
	      params.put("From", twilioNumber);
	      params.put("To", phoneNumber);
	      params.put("Url", path);
	      try {
	        client.getAccount().getCallFactory().create(params);
	      } catch (TwilioRestException e) {
	        String message = "Twilio rest client error: " + e.getErrorMessage() +
	            "\nRemember not to use localhost to access this app, use your ngrok URL";
	        response.getOutputStream().write(getJSONResponse(message).getBytes());
	        return;
	      }
	      response.getOutputStream().write(getJSONResponse("Phone call incoming!").getBytes());
	    } else {
	      response.getOutputStream()
	          .write(getJSONResponse("The phone number field can't be empty").getBytes());
	    }
	}
	private String getJSONResponse(String message) {
	    JSONObject obj = new JSONObject();
	    obj.put("message", message);
	    obj.put("status", "ok");

	    return obj.toJSONString();
	  }

}

 

Other uses are Phone Verification system, Conference Call, etc.