You are here

class Twilio in Twilio SMS Integration 8

Plugin annotation


@SmsGateway(
  id = "twilio",
  label = @Translation("Twilio"),
  outgoing_message_max_recipients = 1,
  reports_push = TRUE,
  incoming = TRUE,
  incoming_route = TRUE
)

Hierarchy

Expanded class hierarchy of Twilio

2 string references to 'Twilio'
sms_twilio_requirements in ./sms_twilio.install
Implements hook_requirements().
Twilio::buildConfigurationForm in src/Plugin/SmsGateway/Twilio.php
Form constructor.

File

src/Plugin/SmsGateway/Twilio.php, line 33

Namespace

Drupal\sms_twilio\Plugin\SmsGateway
View source
class Twilio extends SmsGatewayPluginBase {

  /**
   * {@inheritdoc}
   */
  public function defaultConfiguration() {
    return [
      'account_sid' => '',
      'auth_token' => '',
      'from' => '',
    ];
  }

  /**
   * {@inheritdoc}
   */
  public function buildConfigurationForm(array $form, FormStateInterface $form_state) {
    $form = parent::buildConfigurationForm($form, $form_state);
    $config = $this
      ->getConfiguration();
    $form['twilio'] = [
      '#type' => 'details',
      '#title' => $this
        ->t('Twilio'),
      '#open' => TRUE,
    ];
    $form['twilio']['help'] = [
      '#type' => 'html_tag',
      '#tag' => 'p',
      '#value' => $this
        ->t('API keys can be found at <a href="https://www.twilio.com/console">https://www.twilio.com/console</a>.'),
    ];
    $form['twilio']['account_sid'] = [
      '#type' => 'textfield',
      '#title' => $this
        ->t('Account SID'),
      '#default_value' => $config['account_sid'],
      '#placeholder' => 'XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX',
      '#required' => TRUE,
    ];
    $form['twilio']['auth_token'] = [
      '#type' => 'textfield',
      '#title' => $this
        ->t('Auth token'),
      '#default_value' => $config['auth_token'],
      '#placeholder' => 'XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX',
      '#required' => TRUE,
    ];
    $form['twilio']['from'] = [
      '#type' => 'textfield',
      '#title' => $this
        ->t('From number'),
      '#default_value' => $config['from'],
      '#required' => TRUE,
    ];
    return $form;
  }

  /**
   * {@inheritdoc}
   */
  public function submitConfigurationForm(array &$form, FormStateInterface $form_state) {
    $this->configuration['account_sid'] = trim($form_state
      ->getValue('account_sid'));
    $this->configuration['auth_token'] = trim($form_state
      ->getValue('auth_token'));
    $this->configuration['from'] = $form_state
      ->getValue('from');
  }

  /**
   * {@inheritdoc}
   */
  public function send(SmsMessageInterface $sms_message) {

    // Messages: https://www.twilio.com/docs/api/rest/message
    // Testing API: https://www.twilio.com/docs/api/rest/test-credentials
    $recipient = $sms_message
      ->getRecipients()[0];
    $result = new SmsMessageResult();
    $account_sid = $this->configuration['account_sid'];
    $auth_token = $this->configuration['auth_token'];
    $client = new Client($account_sid, $auth_token);
    $options = [
      'from' => $this->configuration['from'],
      'body' => $sms_message
        ->getMessage(),
    ];
    $report = new SmsDeliveryReport();
    $report
      ->setRecipient($recipient);
    try {
      $message = $client->messages
        ->create($recipient, $options);
      $report
        ->setStatus(SmsMessageReportStatus::QUEUED);
      $report
        ->setMessageId($message->uri);
    } catch (RestException $e) {
      $code = $e
        ->getCode();
      $message = $e
        ->getMessage();
      if (in_array($code, [
        21211,
        21612,
        21610,
        21614,
      ])) {

        // 21211: Recipient is invalid. (Test recipient: +15005550001)
        // 21612: Cannot route to this recipient. (Test recipient: +15005550002)
        // 21610: Recipient is blacklisted. (Test recipient: +15005550004)
        // 21614: Recipient is incapable of receiving SMS.
        //       (Test recipient: +15005550009)
        $report
          ->setStatus(SmsMessageReportStatus::INVALID_RECIPIENT);
        $report
          ->setStatusMessage($message);
      }
      elseif ($code == 21408) {

        // 21408: Account doesn't have the international permission.
        //       (Test recipient: +15005550003)
        $result
          ->setError(SmsMessageResultStatus::ACCOUNT_ERROR);
        $report
          ->setStatus(SmsMessageReportStatus::ERROR);
        $report
          ->setStatusMessage($message);
      }
      else {
        $report
          ->setStatus(SmsMessageReportStatus::ERROR);
        $report
          ->setStatusMessage($message);
      }
    }
    if ($report
      ->getStatus()) {
      $result
        ->addReport($report);
    }
    return $result;
  }

  /**
   * Validates the webhook request and creates an SMS message object.
   *
   * @param \Symfony\Component\HttpFoundation\Request $request The current request.
   *
   * @return \Drupal\sms\Message\SmsMessage The parsed message.
   */
  protected function buildIncomingFromRequest(Request $request) {
    $result = new SmsMessageResult();
    $params = $request->request
      ->all();
    $report = (new SmsDeliveryReport())
      ->setRecipient($params['To'])
      ->setStatus(SmsMessageReportStatus::DELIVERED);
    $sms = (new SmsMessage())
      ->setMessage(trim($params['Body']))
      ->setDirection(Direction::INCOMING)
      ->setOption('data', $params)
      ->setSenderNumber($params['From'])
      ->addRecipients([
      $params['To'],
    ]);
    if ($files = TwilioMedia::processMedia($params)) {
      $sms
        ->setOption('media', $files);
    }
    if (!TwilioValidation::validateIncoming($request, $this)) {
      $report
        ->setStatus(SmsMessageReportStatus::REJECTED);
      $report
        ->setStatusMessage($e
        ->getMessage());
      $result
        ->setError($e
        ->getCode());
      $result
        ->setErrorMessage($e
        ->getMessage());
    }
    $result
      ->addReport($report);
    $sms
      ->setResult($result);
    return $sms;
  }

  /**
   * Callback for processing incoming messages.
   *
   * @param \Symfony\Component\HttpFoundation\Request $request The active request.
   * @param \Drupal\sms\Entity\SmsGatewayInterface $gateway The SMS gateway.
   *
   * @return \Drupal\sms\SmsProcessingResponse The processing response.
   */
  public function processIncoming(Request $request, SmsGatewayInterface $sms_gateway) {
    $task = new SmsProcessingResponse();
    $sms = $this
      ->buildIncomingFromRequest($request);
    $sms
      ->setGateway($sms_gateway);

    // Replies should be handled in implementing code.
    $response = new Response();
    if ($sms
      ->getResult()
      ->getError()) {
      $response = new Response($sms
        ->getResult()
        ->getErrorMessage(), $sms
        ->getResult()
        ->getError());
    }
    $task
      ->setMessages([
      $sms,
    ]);
    $task
      ->setResponse($response);
    return $task;
  }

}

Members

Namesort descending Modifiers Type Description Overrides
DependencySerializationTrait::$_entityStorages protected property An array of entity type IDs keyed by the property name of their storages.
DependencySerializationTrait::$_serviceIds protected property An array of service IDs keyed by property name used for serialization.
DependencySerializationTrait::__sleep public function 1
DependencySerializationTrait::__wakeup public function 2
MessengerTrait::$messenger protected property The messenger. 29
MessengerTrait::messenger public function Gets the messenger. 29
MessengerTrait::setMessenger public function Sets the messenger.
PluginBase::$configuration protected property Configuration information passed into the plugin. 1
PluginBase::$pluginDefinition protected property The plugin implementation definition. 1
PluginBase::$pluginId protected property The plugin_id.
PluginBase::DERIVATIVE_SEPARATOR constant A string which is used to separate base plugin IDs from the derivative ID.
PluginBase::getBaseId public function Gets the base_plugin_id of the plugin instance. Overrides DerivativeInspectionInterface::getBaseId
PluginBase::getDerivativeId public function Gets the derivative_id of the plugin instance. Overrides DerivativeInspectionInterface::getDerivativeId
PluginBase::getPluginDefinition public function Gets the definition of the plugin implementation. Overrides PluginInspectionInterface::getPluginDefinition 3
PluginBase::getPluginId public function Gets the plugin_id of the plugin instance. Overrides PluginInspectionInterface::getPluginId
PluginBase::isConfigurable public function Determines if the plugin is configurable.
SmsGatewayPluginBase::calculateDependencies public function Calculates dependencies for the configured plugin. Overrides DependentPluginInterface::calculateDependencies
SmsGatewayPluginBase::getConfiguration public function Gets this plugin's configuration. Overrides ConfigurablePluginInterface::getConfiguration
SmsGatewayPluginBase::getCreditsBalance public function Returns the credit balance available on this gateway. Overrides SmsGatewayPluginInterface::getCreditsBalance 1
SmsGatewayPluginBase::getDeliveryReports public function Gets delivery reports from the gateway. Overrides SmsGatewayPluginInterface::getDeliveryReports 1
SmsGatewayPluginBase::parseDeliveryReports public function Parses incoming delivery reports and returns the created delivery reports. Overrides SmsGatewayPluginInterface::parseDeliveryReports 1
SmsGatewayPluginBase::setConfiguration public function Sets the configuration for this plugin instance. Overrides ConfigurablePluginInterface::setConfiguration
SmsGatewayPluginBase::validateConfigurationForm public function Form validation handler. Overrides PluginFormInterface::validateConfigurationForm
SmsGatewayPluginBase::__construct public function Constructs a new SmsGateway plugin. Overrides PluginBase::__construct 1
StringTranslationTrait::$stringTranslation protected property The string translation service. 1
StringTranslationTrait::formatPlural protected function Formats a string containing a count of items.
StringTranslationTrait::getNumberOfPlurals protected function Returns the number of plurals supported by a given language.
StringTranslationTrait::getStringTranslation protected function Gets the string translation service.
StringTranslationTrait::setStringTranslation public function Sets the string translation service to use. 2
StringTranslationTrait::t protected function Translates a string to the current language or to a given language.
Twilio::buildConfigurationForm public function Form constructor. Overrides SmsGatewayPluginBase::buildConfigurationForm
Twilio::buildIncomingFromRequest protected function Validates the webhook request and creates an SMS message object.
Twilio::defaultConfiguration public function Gets default configuration for this plugin. Overrides SmsGatewayPluginBase::defaultConfiguration
Twilio::processIncoming public function Callback for processing incoming messages.
Twilio::send public function Sends an SMS. Overrides SmsGatewayPluginInterface::send
Twilio::submitConfigurationForm public function Form submission handler. Overrides SmsGatewayPluginBase::submitConfigurationForm