How to Customize a Joomla Extension for SMS Chat

December 19, 2018
Written by
Anibal Sanchez
Contributor
Opinions expressed by Twilio contributors are their own

4faPRmrbKnErltpOz4So0MHraRAT8mAqxBFw3UiTc892Ao4R0RRMF58hMNDtFL-moK4_sJrTFyX9WBFs0fhq15RB7rErDt9zGc-jviHc9WF0fl9BHifVleDH3CLSjBWYIeFr7sDt

In the article Add a Click To Call Button & SMS Chat to Your Joomla Site, I presented a ready-to-use extension, XT Twilio for Joomla to implement a simple communication channel on a website. The basic extension sends SMS messages (or supports a Click2Call workflow) between users and the sales area.

In this tutorial, I’m going to introduce how to solve a practical requirement of a real-world project; the need to add a first name field (and other fields) to the Contact by SMS module.

You will need a basic website configuration:

  • Local installation of Joomla (preferably version 3.8 or superior). The full detail of CMS requirements can be found here.
  • PHP 5.5 or superior. PHP 7.2 is highly recommended.
  • MySQL 5.1 or superior. MySQL 5.5.3 + is recommended.
  • A PHP development environment (only if you plan to develop your own extension).
  • Optional: NodeJS is only required if you plan to pack your own extension with Webpack.

The source code of the extension we’ll be modifying can be found in this repository: https://github.com/anibalsanchez/XT-Twilio-for-Joomla/releases/tag/1.0.0

Add the Field to the Contact by SMS Module

To add the first name field in the form, we’ll modify the files that implement the Contact by SMS module. The XT Twilio for Joomla extension should be installed inside of your modules folder at modules/mod_xttwilio_sms. If you don’t have it installed, please follow the installation instructions here.

In the module template located at modules/mod_xttwilio_sms/tmpl/default.php, add the first name field by adding the following code inside of the <form> tag:

<div class="controls">
    <label for="xttwiliosms-firstname">
        <?php echo JText::_('MOD_XTTWILIO_SMS_FIRSTNAME_LABEL'); ?>
    </label>
    <div class="controls">
        <input type="tel" id="xttwiliosms-firstname" name="firstname" placeholder="<?php echo JText::_('MOD_XTTWILIO_SMS_FIRSTNAME_PLACEHOLDER'); ?>" required />
    </div>
</div>

The input has two translation keys: MOD_XTTWILIO_SMS_FIRSTNAME_LABEL and MOD_XTTWILIO_SMS_FIRSTNAME_PLACEHOLDER. To translate them into English, I have added them in the file language/en-GB/en-GB.mod_xttwilio_sms.ini. Add the following setting to that file:

MOD_XTTWILIO_SMS_FIRSTNAME_LABEL="Your Name"
MOD_XTTWILIO_SMS_FIRSTNAME_PLACEHOLDER="Enter your name"

The Ajax Communication

The front-end functionality must be supported by a backend element to manage the communication with Twilio. This is a schema of the implemented organization between the front-end modules and Twilio:

To communicate the first name to the backend, the field is added to the ajax communication located in media/mod_xttwilio_sms/js/mod_xttwilio_sms.js.

/*
 * @package     XT Twilio for Joomla
 *
 * @author      Extly, CB. <team@extly.com>
 * @copyright   Copyright (c)2007-2018 Extly, CB. All rights reserved.
 * @license     https://www.gnu.org/licenses/gpl-3.0.html GNU/GPL
 *
 * @see         https://www.extly.com
 */

/* global URLSearchParams, alert */

document.addEventListener('DOMContentLoaded', function() {
  const postData = (firstname, phone, message) => {
    const data = new URLSearchParams();
    data.append('message', message);
    data.append('first-name', firstname);
    data.append('phone-number-from', phone);

    return fetch('index.php?option=com_ajax&plugin=xttwilio&task=sendsms&format=json', {
      body: data,
      method: 'POST',
    });
  };

  const eventHandler = (e, message, firstname, phone) => {
    e.preventDefault();

    if (!message.value.length) {
      return;
    }

    if (!firstname.value.length) {
      return;
    }

    if (!phone.value.length) {
      return;
    }

    postData(firstname.value, phone.value, message.value)
      .then(response => response.json())
      .then((response) => {
        if (response.success) {
          alert('Message sent.');

          return;
        }

        // An exception
        alert(response.message);
        console.log(response);
      });
  };

  const message = document.getElementById('xttwiliosms-message');
  const firstname = document.getElementById('xttwiliosms-firstname');
  const phone = document.getElementById('xttwiliosms-phone');
  const button = document.getElementById('xttwiliosms-button');

  button.addEventListener('click', e => eventHandler(e, message, firstname, phone));
});

To receive the new field in the form and complete the Ajax communication, the new parameter is added to the plugin file onAjaxSendSMS() located in pugins/ajax/plg_ajax_xttwilio/xttwilio.php.

NOTE: To be recognized by the module, you’ll need to minify mod_xttwilio_sms.js.

Next we’ll add the class variable $firstname and modify the initialize() and onAjaxSendSMS() method as shown below. This will allow the first_name parameter to be discoverable by the class.

<?php

/**
 * onAjaxSendSMS.
 */
protected function onAjaxSendSMS()
{
    $input = new CMSInput();
    $message = $input->getString(SMSHelper::PARAM_MESSAGE);
    $firstName = $input->getCmd(SMSHelper::PARAM_FIRST_NAME);
    $phoneNumberFrom = $input->getCmd(SMSHelper::PARAM_PHONE_NUMBER_FROM);
    if (empty($message)) {
        throw new Exception('Error: Invalid Phone Number Message');
    }
    if (empty($firstName)) {
        throw new Exception('Error: Invalid First Name');
    }
    if (empty($phoneNumberFrom)) {
        throw new Exception('Error: Invalid Phone Number From');
    }
    $result = SMSHelper::create($this->accountSid, $this->authToken, $this->phoneNumber)
        ->sendSms($message, $firstName, $phoneNumberFrom);
    return $result->sid;
}

Finally, the new parameter is added to the SMS message in the sendSms() function of the helper file libraries/src/Infrastructure/Service/Twilio/SMSHelper.php. Add the updated code below to your file. Be sure to include the PARAM_FIRST_NAME in the class properties.

<?php

const PARAM_FIRST_NAME = 'first-name';

public function sendSms($message, $firstName, $phoneNumberTo)
{
    if (empty($message)) {
        return false;
    }
    if (empty($firstName)) {
        return false;
    }
    if (empty($phoneNumberTo)) {
        return false;
    }

    $client   = new TwilioRest($this->accountSid, $this->authToken);
    $response = $client->messages->create(
        $phoneNumberTo,
        [
            'from' => $this->phoneNumber,
            'body' => $message.' - '.$firstName.' ( '.$phoneNumberTo.' )',
        ]
    );

    return $response;
}

Test the First Name Field

Similarly to the steps of the previous article, you must install the modified version of the extension, and complete the steps to send an SMS.

  • Step 1 - Install the extension: I have already created the new version with the modification. You can download it for testing from here: https://github.com/anibalsanchez/XT-Twilio-for-Joomla/releases/tag/1.1.0
  • Step 2 - The Twilio Account Configuration: After you complete the configuration to send SMS messages, you are going to have the following information:
    • Account SID
    • Auth Token
    • Twilio Phone Number
  • Step 3 - Configure the account in the Ajax plugin: In the plugin, you must configure the previous credentials, Twilio’s phone and the Salesman Phone Number (who is going to receive the SMS messages).
  • Step 4 - Configure the module to contact customers by SMS: To configure the module from the Joomla admin menu, navigate to Extensions > Module > Twilio for Joomla - Contact by SMS module.
  • Finally, visit the page, where you have published the module, and send an SMS.

Next Steps

Based on this initial version of a Twilio implementation for Joomla, a world of possibilities is open. In this tutorial, I have explained in detail how a field can be added to the extension.

Now, we are ready to build on top of the current code base. We can continue adding more enhancements to the current modules, or we can add more Twilio channels and management features to improve the customer contact experience to support the full business case.

To the moon!

References

 

About Anibal

Anibal Sanchez is a technology geek, with a pinch of an entrepreneur. Aníbal is the team leader of Extly Tech. He helps businesses in rapid web development, implementing DevOps processes, quality assurance practices and project management methodologies. Anibal contributes to the Joomla! community as a member of the Leadership Team, JED’s Assistant Manager and Joomla! Magazine author.