Build Your Own Agent SMS Chat Using Twilio Toll-free Numbers

Screen Shot 2014-06-12 at 9.03.53 AMLearn more about Twilio Toll Free SMS here and get started with your new numbers here.

Most businesses own a Toll-free number to offer customer service and support. But, wouldn’t it be more engaging if contact centers had the  ability to interact with customers via a new channel – texting – to  allow calling and texting to the same Toll-free number?

In this tutorial I’ll show you how to add an SMS channel on your Toll-free number for a new way of interacting with your customers.

You’ll learn how to build an agent chat utility that connects your customer service department to mobile customers, via SMS on Toll-free numbers.

This application will have the following functions:

  • Customers using any mobile device with SMS capabilities can text to a Toll-free number to receive live support from agents.
  • A common agent chat room to handle incoming SMS with customer support inquiries.
  • One or more agents can respond to the queries by addressing the customer’s phone number.
  • Internal agent communication through the same chat window for escalations or collaboration.

Along the way you will not only use Twilio for it’s powerful Messaging API, but also get a good dose of AJAX, PHP and Javascript.

Previewing The Final Product

Screen Shot 2014-06-11 at 1.33.10 PM.png

Here Agent Alice and Agent Bob are logged into the support chat room. A customer with phone number (650)123-1234 sends a text message that is displayed in the browser window. The user asks about the release date for Twilio phone numbers in Ireland.

Unaware of the answer, Bob asks Alice. This exchange is internal to the chat room and the mobile phone user doesn’t see it. Once Bob gets his response from Alice, he texts back from within the chat room, to the mobile phone identified with an @ symbol followed by the phone number and the text. This message is received by the customer. Texting becomes a natural extension to an already available service channel. At this stage, to the agent, it doesn’t matter how they are connected, voice, instant messaging or SMS. It is a seamless experience for them as well as the customer.

Here is what this exchange looks like. Check out the Toll-free number we text to, and from where we get our reply.

Screen Shot 2014-06-11 at 1.56.28 PM.png

We’ll use existing code components for this exercise so you should have this working in no time.

Our Ingredients List

We use a few components which make building this project really easy. Best of all they are all free. For Twilio you need to signup on the Twilio portal. You get a free $30 credit on your account after you signup. Through the portal, you can purchase Toll-free, or mobile, SMS-enabled phone numbers, and access the REST API for messaging, and a helper library for PHP.

Here are our 4 basic ingredients

  • XAMPP or another webserver that can render php files
  • ngrok – forwards http request via an encrypted tunnel through your firewall to your local machine
  • Twilio Toll-free SMS for sending and receiving of text messages via a programmatic interface
  • A prebuild chat application that we will enhance to include SMS texting

Building The Basic Chat

If you look for code for instant chat systems you will find plenty of examples on the web. We are using the excellent work of Tutorialzine for the basic chat functionality. I used XAMPP as my appserver with an already configured MySQL database.  You can download and install XAMPP for your favorite OS here.

Checkpoint – Load http://localhost or

This is what you should see

If you don’t see this, check this site for help.

Next we’ll configure a MySQL database with the convenient phpMyAdmin tool. phpMyAdmin comes preinstalled with XAMPP. It provides a graphical interface to configure your MySQL database. You can load it from your XAMPP start page, on the left side, close to the bottom.

Here is a screenshot of how the phpMyAdmin site looks like on my system. I already have a couple databases. Ignore these for now.

Create a new database by selecting the SQL tab and specifying the following command: “CREATE DATABASE ajaxchat”, just like in this screenshot.

You should see your database “ajaxchat” appear in the left column now. We need to create a connection for this database. Go to the house-button and in the right frame select “Privileges”. Create a user and give this user full access like in the picture below. It works for this prototype, but if you have a better knowledge of security best practices, by all means use what’s considered best practice. Remember the username and password! We will need it later.

Next, check out “Making an AJAX Web Chat” written by Martin Angelov. Read about the best architectures for website development and download his code from their site into the htdocs folder under your XAMPP installation. Once you unzip the files, you will see a tables.sql file in the topmost folder, which issues all the right commands to build the tables in our newly created “ajaxchat” database. Let’s do it.

I selected my ajaxchat database and then on the right side the “Import” tab where I browsed for the tables.sql file. Essentially we are importing a file that has SQL instructions in it, which we are going run against our database.

Press GO, and et voila, we have two tables in our database, “webchat_lines” and “webchat_users”. The user table is self-explanatory, these are the people logged into the webchat. The system accepts any new login, no need for explicit provisioning of users. The webchat_lines are the actual text messages ( and later SMS ). Martin built the system in the easiest way for us to modify. Any row in the webchat_lines table is displayed in the browser chat window via AJAX. Later when we insert our SMS messages as table rows, they will be similarly displayed.

Screen Shot 2014-06-10 at 5.09.09 PM.png

Below in this post you will find a Download to a file 3rdPartyDB.php, which we are going to use. Go back to the downloaded ajax-chat folder. In the ajax-chat folder, under php, add the file 3rdPartyDB.php, add the database connectivity information for the connection we configured above. This is how it looks like for me.

Screen Shot 2014-06-11 at 2.00.05 PM.png

Brave enough to try it?

Checkpoint – Load the http://localhost/ajax-chat/ajax-chat.html page and login with your name and email address.

If it doesn’t work, please go back to the tutorial, which puts all things into context. Now, open two different web browser programs ( I use one Firefox and one Chrome ), load the AJAX-chat in each, and sign into each under a different name and email address. The system accepts any name/email address right now. We load the chat via a localhost URL for now. We will get to ngrok and public URL’s in a second. As you are typing messages in one window, under one account, you can reply from the other window, under your other user account. Just chat with yourself for the moment, to see how it works. Everything you type in one browser will show up in your and your other identities window.

Introoducing nGrok

ngrok is a free tool you can download here. Twilio, which we are going to use in a second for texting, expects to interact with our application. The way it does this is by using public/internet-accessible URL’s, but my XAMPP server is running on my machine behind my firewall. To expose my webserver to the wider internet we use ngrok. It’s a standalone executable; I still have it in my Downloads folder after many months.

I am a registered user so I can use a domain name that is easier to memorize. I start ngrok with ./ngrok -subdomain ralf 80

This means that all requests to will be forwarded to my XAMPP server as long as ngrok is running. If you are not registered with ngrok, you will get some funky domain name. Just watch the output of the tool and it will tell you what it is.


Checkpoint – load our chat system via ngrok. Browse to, well whatever the domain name is you selected, or got assigned.

If it works: Bravo! If it doesn’t work, but ngrok is running, check out this help page.


Even we haven’t done anything with texting yet, we are three quarters through to the final product. The rest is all easy peasy lemon squeezy and only 15 minutes left of work.


Adding The Text Messaging Sauce

So now that we have basic chat functionality going, let’s integrate Twilio text messaging as a new feature. Again, the idea is to send and receive text messages from the browser.


The design is simple. Incoming text messages, which are sent to a Twilio toll-free number ,will be displayed in the chat window under their phone number as label. Outgoing text messages, i.e., the messages sent to the customer, will be triggered by typing the @ symbol followed by the phone number and message text. For example, typing “@4151231234 Hello World” into the chat window would send Hello World to the phone number +1 (415) 123-1234.

I have taken the approach to use the Twilio PHP helper library. Alternatively, you could use cURL, but the helper library has such a nice encapsulation of Twilio REST functionality.

Here are the two basic modifications we need to do to our working chat program. First an inbound message needs to be displayed in the chat window.  Second, when agents type the special marker @, we need to send the text message to the customer’s mobile device.

Configuring Your Toll Free Number

Go ahead and purchase a toll free number and let’s use that one for texting.

Twilio responds to an incoming text message with a callback, sometimes called a webhook. In other words, Twilio will POST the message as well as some meta-information to a URL which you specify in your account portal for your number. Basic information includes the parameters ‘From’ (sender), ‘To’ (Twilio number) and ‘Body’ of the message. We will point this Message Request URL to our webchat browser app, from where it is inserted into the database and ultimately shows up in the chat window.

Here is a screenshot how you configure the number in your account portal.

Screen Shot 2014-06-11 at 2.01.35 PM.png

Here, we point the Messaging Request URL to The file 3rdPartyDB.php, which you can find in your ajax-chat folder in the php folder on disk, is the one, where we will handle the inbound message.  We just have to write some code to display it in the chat window.

Handling Incoming Texts From Customers

We need to write the code that receives the Twilio callback and displays the text message on screen. Check this out! As mentioned earlier when Twilio receives a message it will POST the parameters ‘From’, ‘To’ and ‘Body’ to your Message Request URL, which we just configured to be http://…../3rdPartyDB.php. So in this file we first extract where the message comes ‘From’. ‘From’ is the senders phone number. We will display this number in the chat window. Next we also extract the message itself from the request, which Twilio sends to us in the same request under the ‘Body’ parameter.

As I mentioned earlier, anything that is inserted as a row into our webchat_lines database table will be displayed in the chat window. That’s what we have to do. We insert the user, here the user is the mobile phone number that sent the text message and the message itself into the database.  We escape the the strings to avoid attacks on our database.

Believe it or not, but this is all the modification we need to display the incoming text message in the chat window. These are 11 additional lines of easy code. Kudos to Martin and Kudos to Twilio.  The user identifier here is the sending phone number. The incoming message is displayed after the user identifier.

Checkpoint – let’s do some basic testing first. We mimic Twilio here. In your browser load the page

You should see a line in your chat window, that shows the message “test” from the user 14151231234. [%2B is the urlencoded form of “+” – we’ll talk about this later]. If this doesn’t work, go back in the tutorial to recheck all steps.

If it works, proceed by sending the Twilio number you configured in the account portal a text message from your mobile phone, and wait until it arrives in the chat window, which should be within seconds.

Sending Text Messages Back To Customers

Now, where we can receive inbound text messages in our chat window, we need to be able to reply. The same method  is also applied for reaching completely new recipients.  We’ll distinguish internal chat messages from external texting by using a special address format. As mentioned earlier we will use the @sign followed by the phone number and the text to send, like @4151231234 Hello

Let’s check the code that parses this chat line and uses Twilio to send the text out to the mobile phone. We are working with the file ajax.php here.

In ajax.php add your Twilio account credentials as variables to the page. Your account credentials can be found in the dashboard section of your Twilio account.  We also instantiate a Twilio client object which provides all the methods to talk to Twilio intelligently. Yeah, and don’t worry about trying my credentials. I changed them since then.

Screen Shot 2014-06-11 at 2.09.25 PM.png

The remaining task is to inspect a text that was submitted as a chat line and see if it has the special marker @phonenumber. If it does, we will make a Twilio helper library call to send the text messages. You can see this in the following section.

Screen Shot 2014-06-11 at 2.15.39 PM.png

The first line of code submits what I typed to the chat window itself. Again the idea is that other agents can see all the incoming and outgoing texts in one common window. This is done to ensure customers are responded to inquiries in a timely manner and so agents can collaborate.

The next code block is used to identify if this is a text message with the special marker @ and to make an encapsulated Twilio REST request to the Twilio Messages resource to send the message.

First we strip out the @symbol and identify the phone number and text of the message. This is done with some PHP parsing functions. Essentially we look for number groups in the text string and use the first number string as phone number.

One remark about the $to=”+1” . $to. Twilio expects numbers in E.164 format. This means a phone number should be formatted with the “+” sign, followed by the country code, followed by the number. It’s also how Twilio sends you numbers. In North America the country code is 1, so a full number in E.164 would look like +16501231234. I don’t expect the agent to know this and assume they just input @6501231234 which is how we do it all day long. That’s why I am adding the +1. We could apply more logic but this seems natural.

Next we make a request to the Twilio /Messages REST resource to send the message. This is done with the helper library and this line of code:

$sms = $client->account->sms_messages->create($from, $to, $chatFilteredText, array());

Behind the scenes, the messages resource is addressed via’ . $twilioAccountSid . ‘/SMS/Messages.xml’,

The POST to this resource expects ‘From’, ‘To’ and ‘Body’ which we supply. The helper library takes all this RESTful thinking away from us in a chaining of objects and methods. Sweet.

Checkpoint: Go into your web chat browser window and send yourself a text message. You could type @4151231234 I can text and chat now via my computer.

It’s All Done!

couple lines of code. There are many more enhancements possible. You could map the phone number into a username transparently in the database. You could use Twilio Message Delivery Information to display if the message was delivered on the customer’s device. Or you could add Twilio client to enable voice calling within the same browser window as the chat system.


Contact and Comments

We want to see what you are building with Twilio SMS on toll-free numbers, so give us a shout and show us what you got. I am or @guglhupf on Twitter.

Thanks for reading!

  • EpicBusiness

    Thanks, Ralf! I do have one question. When downloading the files from, I cannot find 3rdPartyDB.php in the php folder (or, anywhere for that matter). Should we point the Messaging Request URL to the /php/ajax.php file?

    • Ralf

      I just added a Download section with the link to the file. Thank you for pointing this out.

      • EpicBusiness

        Thanks for the update, Ralf. Nice app.

    • Twilio

      @EpicBusiness:disqus We just added a GitHub link as well for a download section.

      • EpicBusiness

        Thanks for the update. Works great!

  • kam

    Hi, I did not understand how toll free number helps here. Is it because voice and text are same number?

    • Ralf

      Hi, this is exactly it. If you think as toll-free numbers having a dual purpose. First of all calling them is free for the enduser. Then they are typically also very strongly branded like 1800CITI1234 (just an example). So now with this new Twilio feature you can text to that number and receive voice calls at the same number. For the enduser it means convenience in how they want to interact with the business. For the business it means, reuse of existing marketing materials, and reuse of an established and well memorized number, while still offering a completely new channel of communication. That said, the tutorial has no dependency on toll-free numbers, you can pick a regular long code Twilio number as well.

  • vanplus

    Could you post a completed version to download?

  • Jsdallas

    Something that I have noticed playing with this. You can’t reply with a number in your sms message out bound. It will get added to the database right, but it is not sent out as a sms. But guess is it has something to do with you looking to digits in the message for the number. So when I sent message “@NPANXXZZZZ Test!” the message went threw just fine. But when I send “@NPANXXZZZZ Test2!” The message showes up on the screen but is never sent to the phone. On top of that it does not even show in my Twilio logs as trying to be sent. Is there any way this can be looked at?

    • Ralf

      Looks like a bug to me and I wrote it. I will double check and fix it appropriately. As to the logic. Below I have copied the code snippet. It first looks for the @ sign and strip it. I then use preg_match_all(‘!d+!’, $chatFilteredText, $matches); to find all numbers in the string. Your Test->20) {
      // if there was a phone number supplied sent the text out
      // find the phone number in the string
      preg_match_all(‘!d+!’, $chatFilteredText, $matches);
      $to = implode(‘ ‘, $matches[0]); // the phone number is the first number in the string
      $chatFilteredText = str_replace($to,”,$chatFilteredText);
      $to = “+1” . $to;
      $sms = $client->account->sms_messages->create($from, $to, $chatFilteredText, array());

      • Ralf

        O.K. I fundamentally took the wrong approach. Here is a better solution which I am going to post to the github repo.
        Here I am looking for the @ sign and replace it with a +1. In the US the E.164 formatted numbers start with +1 followed by a ten digit number.
        I next extract the whole phone number via the preg_match_all regular expression. The ^ indicated the start of the line. Now we have our phone number which we should send to, no matter what other numbers show up in the body of the message.

        $chatFilteredText = str_replace(‘@’,’+1′,$_POST[‘chatText’],$count);
        if ($count>0) {
        // if there was a phone number supplied sent the text out
        // find the phone number in the string
        preg_match_all(‘/^+1[0-9]{10}/’, $chatFilteredText, $matches);
        $to = implode(‘ ‘, $matches[0]); // the phone number is the first number in the string
        $chatFilteredText = str_replace($to,”,$chatFilteredText);
        $sms = $client->account->sms_messages->create($from, $to, $chatFilteredText, array());

  • Merv Rutt

    Is there an ASP.NET version of this app? That would be very helpful.

  • Jim Martin

    This is great, but I can’t get the Twilio SMSportion to work. Is there a completed ajax.php file for downlaod where we can simply fill in our Twilio account details, and a from phone number?

  • WCTG1

    I can receive texts, but can’t reply back out. When I add my twilio account information to the ajax.php file the chat function does not load properly.

    • matt

      same problem

  • Robert Anthonie Soriano

    Hello I have a question,

    Does toll free numbers let clients send sms to you for free?

  • nick

    Great tutorial! I am having an issue with the chat not sending messages via text message to the user. I’ve checked the twilio log, and they haven’t appeared there which means that for some reason the ajax.php file isn’t doing its job. I’ve checked and it’s the same as yours; do you have any ideas on what could be wrong?

  • Niv Caner

    cool tutorial! How do you handle long incoming SMSs? can your program re-construct the SMS fragments in the correct order?