Saturday, October 6, 2012

Using Twilio for SMS with PHP


Twilio provides a relatively painless SMS interface.  But the PHP documentation is fragmented and takes some effort to aggregate.  So, to make it easier for others, I threw together a quick outline of how you go about implementing a Twilio interface in PHP. The send interface is very simple:

   const SMS_PREFIX =     '+1';
   const MAX_SEND_CHARS = 160;
   const TWILIO_SMS_APP_ID = '15 digit appId';
   const TWILIO_SMS_APP_SECRET = '32 character app Secret';

    /**
     *send an SMS message
     *
     * @param string $smsNum
     * @param string $smsBody
     *
     * @return string
     */   
   public function sendSms($smsNum, $smsBody) {
     
      $cliTwilio = new Services_Twilio(self::TWILIO_SMS_APP_ID,       
                                       self::TWILIO_SMS_APP_SECRET);
      $smsNum = self::SMS_PREFIX . $smsNum;
      $smsFrom = self::SMS_PREFIX . $this->twilioNumber;
      if (strlen($smsBody) > self::MAX_SEND_CHARS) {
         throw new Exception ('Error: attempting to send message of length (' .    
                            strlen($smsBody) . ') but max allowed chars is (' .
                            self::MAX_SEND_CHARS . ') for SMS number: ' . $smsNum);
      } else {
         $smsResponse = $cliTwilio->account->sms_messages->create($smsFrom, $smsNum,     
                               $smsBody);
         if ($smsResponse->sid != null) {
            return $smsResponse->sid;
         } else {
            throw new Exception ('Error: SMS send returned invalid (NULL) sid for ' .
                                 'sms number: ' . $smsNum);
         }
      }
   }


The “Services_Twilio” class referenced here is in the Twilio library provided by Twilio.  You need to download it from Twilio.

To be able to receive SMS messages, you need to go the Twilio website, login, select “Numbers”, and click into the number you have setup for your Twilio account.  Go to the SMS section, and set the “SMS Request URL” to point to your receiving web page (https is recommended but not required to make it work which is handy for testing).  The receiving web page on your site needs something similar to the following in it:

class SMSMessageParser {
  
   /**
    * Parse the incoming SMS message
    */
   public function parse() {
     
      if(!isset($_SERVER['HTTPS']) && $this->config->twilio->useSSL !="NO") {             
         header("HTTP/1.1 301 Moved Permanently");
         header("Location: https://" . $_SERVER["SERVER_NAME"] .  
                                       $_SERVER["REQUEST_URI"]);
         exit();
      }

      if (empty($_REQUEST)) {
         die();
      } else {
         $smsNum = substr($_REQUEST['From'],-10);
         $smsMsg = $_REQUEST['Body'];
         try {
            $smsService = new SmsService();
            $response = $smsService->parseSms($smsNum, $smsMsg);
         } catch (Exception $e) {
            $response = "We are sorry, but we experienced an unexpected error " .
  "processing your request.";
         }
         header("content-type: text/xml");
         echo "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n";
         echo "<Response>";
         echo "<Sms>" . $response . "</Sms>";
         echo "</Response>";
         exit;
      }
   }
}


$parser = new SMSMessageParser();
$parser->parse();

And finally, you need a class to process the incoming text:

class SmsService {

   private $smsReservedVerbs = array('stop','unsubscribe','cancel','quit',
                                     'start','yes','help');
  
   /**
    * parse incoming SMS message
    *
    * @param string $smsNum
    * @param string $smsMsg
    *
    * @return string
    */  
   public function parseSms($smsNum, $smsMsg) {
      $smsNum = trim($smsNum);
      $smsMsg = trim($smsMsg);
     
      if(strlen($smsNum) != 10) {
         return false;
      }
      if ($smsMsg == "Whatever you are looking for") {
         // Do something with message

      } else if (in_array(strtolower($smsMsg), $this->smsReservedVerbs)) {
         switch(strtolower($smsMsg)) {
            case "unsubscribe":
            case "stop":
            case "cancel":
            case "quit":
               // User unsubscribed so take appropriate action
               break;
            case "start":
            case "yes":
               // User resubscribed.  Act appropriately.
               break;
            case "help":  
               // send some sort of appropriate information.
               break;
            default:
               throw new Exception ('Error: We should not be able to reach ' .
                        'this statement.  Message was: ' . $smsMsg);
         }
      } else {
         $responseString = 'We are sorry.  Your message "' . $smsMsg . '" ' .
                           'was not understood.' ;
      }
      return $responseString;
   }
}

And that’s all there is to it. 

1 comment:

  1. Everytime I see some pieces of php-code, my heart goes bleeding! No doubt, this language was quite popular for a long time, but we need to get this very clear, that now it's the time to choose more simplified solutions! I found for myself the best way to bulk business sms with the with this program to send mass text messages https://www.intistele.com/group-sms-texting/ You see, it has pretty simple interface and no limits on characters and number of messages! Moreover, it put all the replies in one place, so you can navigate them in pretty easy fashion

    ReplyDelete