Using Twilio API to send SMS Messages

Tips submitted by PHPMaker users
Post Reply
sticcino
User
Posts: 1043

Using Twilio API to send SMS Messages

Post by sticcino »

Poor man's function to send messages via twilio.

replace _getPreferences() with variables or where ever you store this information..
put the SendSMS_Message() function and use Twilio\Rest\Client as twiSMS; in your userfn.php file, so you can call it from anywhere in your app

Sample:

$Mobile_No = "555-555-5555";
$msg = "This is the message to send...";

SendSMS_Message($Mobile_No, $msg);
use Twilio\Rest\Client as twiSMS;
/////////////////////////////////////////////////////////////////////////////////////////////           
// Send an SMS using Twilio's REST API and PHP
//
function SendSMS_Message($Mobile_No, $msg)
{
    $sid = _getPreferences("TWILIO_SMS_SID");
    $token = _getPreferences("TWILIO_SMS_TOKEN"); 

    if($Mobile_No == '') {
        WriteAuditTrail("log", CurrentDateTime(), ScriptName(), CurrentUserID(), 'SendSMS_Message', CurrentUserIP(), $Mobile_No, 'Invalid Mobile Number', '', 'Failed');
        return;
    }

    try {       
        $client = new twiSMS($sid, $token); // Twilio\Rest\Client($sid, $token);
        WriteAuditTrail("log", CurrentDateTime(), ScriptName(), CurrentUserID(), 'SendSMS_Message', 'client->create', $client, $sid, $token, 'Completed');
    }
    catch(Exception $e) {
        WriteAuditTrail("log", CurrentDateTime(), ScriptName(), CurrentUserID(), 'SendSMS_Message', 'client->create', $e, $sid, $token, 'Failed');
        exit();
    }
    
    try {
        $message = $client->messages->create(
            $Mobile_No, // Text this number
            array(
                'from' => _getPreferences("TWILIO_SMS_NUMBER"), // Your Twilio number
                'body' => $msg   // Msg to send
            )
        );
        WriteAuditTrail("log", CurrentDateTime(), ScriptName(), CurrentUserID(), 'SendSMS_Message', CurrentUserIP(), $Mobile_No, $msg, $message, 'Success');
    }
    catch(Exception $e) {
        WriteAuditTrail("log", CurrentDateTime(), ScriptName(), CurrentUserID(), 'SendSMS_Message', 'messages->create', $e, $Mobile_No, $msg, 'Failed');
        exit();
    }
}

Post Reply