How-To: Sending an SMS using WebAPI

September 10th, 2010 by John Dyer

Sending an SMS with WebAPI is quite simple, especially since we added the {message:} object to the API. To get started we’ll need you to first create a WebAPI application in your Tropo account. Once you have set this up you will need to assign an SMS enabled phone number to the application, this part is required to send messages from the application. The next step is to make sure you have a messaging token associated with the application, since you will need this to start the session via our API (more on this in a few). Please note there are two Tokens associate with Tropo applications, one for voice calls, and one for messaging, we will want to use the Messaging token for our purposes here, but if you are interested in Voice calls please check out our guides for Scripting and WebAPI.

I will be using the Ruby WebAPI helper class for most of this example,  however I will post also include the raw JSON in-case you are using other libraries to render it (C#, Python, PHP, ect).

To start please take a look at the finished product, this is an example in Sinatra, using the Ruby helper class ( Tip: Additional WebAPI Power tips can be found in a previous blog posting here).

require 'rubygems'
require 'sinatra'
require 'tropo-webapi-ruby'

post '/' do
  sessions_object = Tropo::Generator.parse request.env['rack.input'].read
msg = sessions_object[:session][:parameters][:msg]
number_to_dial = sessions_object[:session][:parameters][:to]

tropo = Tropo::Generator.new do
            message({
                          :to => 'tel:+1'+number_to_dial,
                          :channel => 'TEXT',
                          :network => 'SMS'}) do
                             say     :value => "#{msg}"
                          end
            end

  tropo.response

end

If you have the WebAPI class installed then you can start Sinatra by just running sinatra my_app.rb from the command line.  This will start the server, and as long as you have the URL to this machine in the messaging portion of your application then we are all set!  If you are doing development, and are perhaps behind a firewall, you can get setup quickly by using something like tunnlr ( more info here ).

So lets review…  we have our server running, Tropo application created and pointed to our running server.  We have a messaging number associated with the application, and a messaging token.  I thin we are ready to rock and roll!!

So to send the message we need to send an HTTP request to Tropo’s sessions API.  So I’ll go ahead and use CURL, which is a command line tool which will among other things send HTTP requests.  If you dont have CURL you can just as easily place the URL in your browser, since this will accomplish the same end result ( Tip: make sure to substitute your number in the to parameter, and use your own messaging token in place of ‘my_messaging_token_id’ )

curl "http://api.tropo.com/1.0/sessions?action=create&token=my_messaging_token_id&msg=my+message+to+send&to=4075551212"

Now the magic begins! What will happen is this HTTP request will hit our API servers, and using the messaging tokenID we’ll route that to your applications startURL. This will in turn send a JSON payload to your messaging startURL similar to what you see below. Please pay close attention to the parameters located in this JSON body, this contains the message, the number we are sending a msg to, as well as various other parameters:

{
    "session": {
        "id": "76b05a0b25127dbf59a4627f6dcd38a7",
        "accountId": "12345",
        "timestamp": "2010-05-05T01:59:19.402Z",
        "userType": "NONE",
        "initialText": null,
        "callId":"092f931c4dddf0124ef426c56d26f98c",
        "parameters": {
            "token": "my_messaging_token_id",
            "action": "create",
	     "msg":"my message to send",
	     "to":"4075551212"
        }
    }
}

This JSON payload will hit out application and using the parse method of Tropo’s WebAPI helper class we can grab the associated values needed to send out message. This way we can use the same application to send multiple messages, to multiple recipients, with out having to change our code:

  sessions_object = Tropo::Generator.parse request.env['rack.input'].read
    msg = sessions_object[:session][:parameters][:msg]
    number_to_dial = sessions_object[:session][:parameters][:to]

Now we just use the generator method to build the return JSON payload, which we’ll send back to the Tropo session, which will then send the message. You can see the final JSON that our script sends back to Tropo below for your reference:

{
     "tropo":   [
         {
          "message": {
           "channel": "TEXT",
           "to": "tel:+14075551212",
            "say": [
                 {
                "value":"my message to send"
                 }
             ],
              "network": "SMS"
         }
    }
  ]
}
This payload instructs Tropo to send the message to your user, and all of this was started with a simple HTTP request, how cool is that! Now to wrap things up I wanted to touch on a few frequently asked questions we see related to messaging:

  • When you send a message you can set the from callerID, however the number must be associated with the application sending the message.
  • SMS Messages are carrier limited to 10 messages per number a minute, and currently the developer is responsible the throttling their messaging campaigns.
  • Tropo does not block international SMS messages at this time, but delivery to international carriers is not officially supported at this time.
  • I really hope this information is helpful, and if there are any other questions please let us know, as our team is most certainly always standing by to offer any help our developers may require. You can always find us on Freenode irc.freenode.net in #tropo.

    John Dyer

    Tropo Support

    Related posts:

    1. Sending outbound SMS with Java
    2. Command Line SMS
    3. WebAPI Tips & Tricks
    4. New tropo-webapi-ruby Gem Released
    5. WebAPI: Now with outbound and transcription

    Tags: , , ,

    6 Responses to “How-To: Sending an SMS using WebAPI”

    1. James says:

      Not even one decent example for PHP how to initiate SMS. Moving to twillo :)

    2. John Dyer says:

      Hey James,

      I am sorry you feel there is some lack in support for PHP on our platform, but I assure you this couldn’t be further from the truth. We have dozens of examples on our blog under the tag ‘php‘ that you may want to check out. We also have an active WebAPI PHP library on our GitHub page, as well as libraries in C#, Ruby, Java, Redis, Node.js,Grails, and even a Drupal plugin. If you are having any issues finding, or using, any of these plugins please let us know, as our team is most certainly always standing by to be of service!

      -John

    3. Juan Pablo says:

      I agree with James… I spent 20 minutes looking for a simple example for PHP (to send SMS), with no luck. The I found the comment from James and tried Twilio, and 5 minutes later I was sending a SMS from my Linux command line.

      Don’t get me wrong, Tropo looks great! But I can’t find the examples for PHP and SMS! Could you please point me to the right direction? I don’t need audio, I don’t need to receive any response… just send a SMS to a cell phone. From PHP or command line using Curl or Wget.

      Thanks!

      jp

      PD: I already saw the blog (tag PHP) and the web API.

    4. Kevin Bond says:

      Hello Juan and James,

      I apologize for any confusion. I will show you a quick example on how to send an SMS dynamically using a browser request and also through the terminal.

      The way that Tropo works is you will setup an app in Tropo(webAPI or scripting), then whenever you send a request to send an SMS, your app that you made will be hit and will send the actual SMS. Below is an example of a SMS app in the php webAPI platform:

      <?php
      
      //Require to use the Tropo php library
      require 'tropo.class.php';
      
      //Create the Tropo object to call the methods 
      $tropo = new Tropo();
      
      //Extract the parameter sent in
      $session = new Session(); 
      $to = "+".$session->getParameters("numbertodial"); 
      $msg = $session->getParameters("msg");
      
      //send the SMS
      $tropo->message($msg, array("to"=> $to, "network"=>"SMS")); 
      
      //Send Tropo the JSON payload
      $tropo->RenderJson();
      ?>
      

      Once you have this code on your servers, you will use the URL which can reach that app as your Tropo (“What URL powers your app?”) link.

      Once that is done, you are ready to start sending in your requests to send the SMSs. The way that the app is set up, you will be sending 2 variables – num (the number that you will be send thing SMS to) and msg ( the text of the SMS).

      The basic request URL will look something like this:

      https://api.tropo.com/1.0/sessions?action=create&token=TOKEN&num=14075551212&msg=This+is+a+sample+SMS

      The token in the URL above will be the token that is attached to your app (“Outbound Tokens” – you can use either one).

      You can send a GET request using the php cURL to initiate your Tropo app using the URL above. You can view an example of that below:

      $curl_handle=curl_init(); 
      
      curl_setopt($curl_handle,CURLOPT_URL, $Above_URL); 
      
      curl_setopt($curl_handle,CURLOPT_CONNECTTIMEOUT,2); 
      curl_exec($curl_handle); 
      curl_close($curl_handle);
      

      You can also send this request in the terminal as follows:

      $curl https://api.tropo.com/1.0/sessions?action=create -i -X POST -d “token=Your_Token&num=14071234321&msg=Hello+from+Tropo”

      *Note – to be able to send an SMS, you will need either a US or Canadian phone number attached to your Tropo application. If you are sending the SMS to a non-US destination, a Canadian number is recommended.

      Does that help? If you have any other questions or concerns, please don’t hesitate to ask!

      Regards,

      Kevin Bond Voxeo Labs

    5. Trav says:

      So am I right in saying that you call the Tropo URL with your token which then calls the url of your website that you specify in the application which is called by Tropo to get a JSON response that is used by Tropo to populate the message?

      If this is the case then how do you do development in a local environment?

      Process flow is very hard to work out and isn’t clear in the documentation.

      Thanks Trav

    6. John Dyer says:

      Trav,

      Sorry to hear your having some trouble here, but we actually have a good blog post that might be just what your looking for. Please check out the post, and if you ‘re still having issues please drop us a line in a support ticket or stop by our IRC channel ( #tropo on FreeNode).

      Regards,

      John Dyer

    Leave a Reply

    Please note: By submitting a comment you agree to comply with our Comment Policy. We welcome all comments, positive or negative, but do reserve the right to remove all or part of blog comments that do not comply with our policy.

    Additionally, the first time you leave a comment on this blog, it will be held for moderation. After that first comment has been approved, future comments will be posted without delay.

    Additional comments powered by BackType