You are here

function sms_twilio_command in Twilio SMS Integration 7.2

Same name and namespace in other branches
  1. 6 sms_twilio.module \sms_twilio_command()
  2. 7 sms_twilio.module \sms_twilio_command()

Executes a command using the Twilio API

1 call to sms_twilio_command()
sms_twilio_send in ./sms_twilio.module
Callback for sending messages.

File

./sms_twilio.module, line 111
Adds support for sending SMS messages using the Twilio gateway.

Code

function sms_twilio_command($command = 'auth', $data = array(), $config = NULL, $account = '') {
  if (!isset($config)) {
    $gateway = sms_gateways('gateway', 'twilio');
    $config = $gateway['configuration'];
  }

  // Set our AccountSid and AuthToken
  $AccountSid = $config['sms_twilio_api_sid'];
  $AuthToken = $config['sms_twilio_api_auth_token'];

  // Include the PHP TwilioRest library
  require_once DRUPAL_ROOT . '/' . $config['sms_twilio_path'] . '/autoload.php';

  // Instantiate a new Twilio Rest Client
  $client = new Client($AccountSid, $AuthToken);
  switch ($command) {
    case 'sendmsg':
      $payload = array(
        'body' => $data['message'],
      );
      if (strlen($config['sms_twilio_number']) == 34 && substr($config['sms_twilio_number'], 0, 2) == 'MG') {
        $payload['messagingServiceSid'] = $config['sms_twilio_number'];
      }
      else {
        $payload['from'] = $config['sms_twilio_number'];
      }
      $response = $client->messages
        ->create($data['number'], $payload);
      break;
  }
  watchdog('sms_twilio', print_r($response, TRUE));

  // Check for HTTP errors
  if ($response->errorCode != '') {
    $result = array(
      'status' => FALSE,
      'message' => t('An error occurred during the HTTP request: @error_code: @error.  Please see <a href="@twilio_url">the Twilio docs</a> for more information', array(
        '@error_code' => $response->errorCode,
        '@error' => $response->errorMessage,
        '@twilio_url' => 'https://www.twilio.com/docs/api/rest/message#error-values',
      )),
    );
    watchdog('sms_twilio', $result['message']);
  }
  else {
    $result = array(
      'status' => TRUE,
      'data' => t('Message sent to @number', array(
        '@number' => $data['number'],
      )),
    );
  }
  return $result;
}