top of page
Twilio SMS Integration

Twilio SMS Integration

Integrate with Twilio to send SMS messages

Intermediate.png

Intermediate

6K

Published:

November 26, 2020

Girl Enjoying her Drink

by

Anchor 1
Hire a Developer

Example Description

In this example, we integrate with the Twilio 3rd-party service using their npm package, allowing us to send SMS messages directly from the browser.

 

Note: To implement this example, you must first create an account on Twilio as described here.

Example Code

Tab 1

.

Tab 2

.

Tab 3

.

This code solution can be complicated.

How We Built It

This example is built from several parts:


  • Secrets Manager

  • External Packages

  • Backend Code

  • Page Design

  • Page Code



Secrets Manager


This example uses Twilio's Messaging API. Before using the example, you need to create an account with Twilio and locate the account's SID and auth token, which you will use when calling the API. The most secure way of storing this sensitive information on your site is to use the Secrets Manager.



To add the necessary data to the Secrets Manager:


  1. In the Editor, select Settings from the top menu and then select My Dashboard to open your site's dashboard.

  2. In the dashboard, select Settings and then Secrets Manager to open the Secrets Manager.

  3. Click Store New Secret to start storing secrets.

  4. Add a secret named accountSID and give it the value of your Twilio account SID.

  5. Add a secret named authToken and give it the value of your Twilio auth token.

  6. Add a secret named fromPhone and give it the value of the phone number you received from Twilio.



External Packages


Twilio provides an npm package to make it easier to work with their APIs. In order to use an npm package in a site, you first need to install the package on the site.

 


To install the twilio npm package:


  1. Go to the Code Files tab in the Velo Sidebar.

  2. In the Packages (npm) section, click Install a new package to open the Package Manager.

  3. In the Packages tab of the Package Manager, search for the twilio package.

  4. Click Install to install the twilio package.

 


Backend Code


Because you need to use sensitive information when calling the Twilio API, it's best to make the API calls from the backend. However, the calls to the Twilio API will be triggered from the frontend. So, you need to place the code in a backend web module, which resides in the backend but can be called from the frontend.

 


To create a backend web module:


  1. Go to the Code Files tab in the Velo Sidebar.

  2. In the Backend section, click Add a new Web Module to create a web module.

  3. Name the web module twilioService.jsw. Web modules must end with the .jsw extension.

 


Add the following code to the web module:


  • Start by importing the getSecret() function so you can retrieve the secrets stored in the Secrets Manager. You also need to import the twilio npm module.


   import { getSecret } from 'wix-secrets-backend';

   import twilio from 'twilio';


  • Next, create a function to send a message. The function needs to take in the phone number the message will be sent to and the contents of the message.


   export async function sendMessage(toPhone, message) {}
 

  • Inside the function, retrieve the sender's phone number, account SID, and auth token from the Secrets Manager.


   const fromPhone = await getSecret('fromPhone');

   const accountSID = await getSecret('accountSID');

   const authToken = await getSecret('authToken');


  • After retrieving the secrets, use them to create a Twilio client.


   const client = twilio(accountSID, authToken);


  • Finally, use the client to create a message. If the message wasn't sent successfully, throw an error.


         try {

    await client.messages.create({

      body: `${message}\n${messageSuffix}`,

      from: fromPhone,

      to: toPhone

    });

    } catch(error) {

    throw 'Failed to send sms';

    }



Page Design


The page design in this example is pretty straightforward. It's a simple form that's used to specify the receiver's phone number and the message to send. It's a good idea to use descriptive IDs for all the elements that you add to the page. This will make your code a lot cleaner.

 

Note: When implementing a form such as this one, we recommend you add the reCAPTCHA tool to your form to prevent spam and other types of automated abuse.

 


To create the form:


  1. Add a text input element to the page, set its type to Phone Number, and change its ID to toPhoneInput.

  2. Add a text box element to the page and change its ID to messageInput.

  3. Add a button to the page, change its label to Send, and change its ID to sendButton.

  4. Add two text elements to the page, set their IDs to successMessage and errorMessage, and change their text accordingly.



Page Code


The page code handles the functionality of the page elements and uses the backend web module to send the message using Twilio.

 


Add the following code to the page:


  • Start by importing the sendMessage() function from the twilioService backend web module.


   import { sendMessage } from 'backend/twilioService';
 

  • Next, create an event handler that runs when the sendButton is clicked. Since the event handler is added to a page element, it needs to wait for the page elements to be ready. That means it needs to be added inside the $w.onReady event handler.


         $w.onReady(function () {

     $w('#sendButton').onClick(() => {

       // handle a sendButton click

     })

   });

 

  • Inside the onClick event handler, check if the form is filled out properly using the validateForm() function, which checks if the values entered in the form are valid.

 

   if (validateForm()) {

     // send the message

   } else {

     // update the validity indications

   }


  • If the form is valid, retrieve the information from the form.


   const toPhoneNumber = $w('#toPhoneInput').value;

   const message = $w('#messageInput').value;


  • Then, hide the success and error messages in case this is not the first message being sent.


   $w('#successMessage').hide();

   $w('#errorMessage').hide();

 

  • Then, call the backend function to send the message using the values retrieved from the form. If the message is sent successfully, show the success message. If not, show the error message.


   sendMessage(phoneNumber, message).then(() => {

     $w('#successMessage').show();

   }).catch(() => {

     $w('#errorMessage').show();

   });

 

  • If the form is not valid, call the updateFormValidation() function to update the input validity indicators in the form.


   else {

    updateFormValidation();

   }

Hire a Developer

Velo solutions are powerful tools, but building them on your own can be challenging. Let an experienced Velo development shop build it for you, so you can keep working on your site or business.

Related Examples

Did this help?

Yes

|

No

Thanks for your feedback!

Twilio Integration

Twilio Integration

Integrate with Twilio to make voice calls and send SMS messages

Intermediate.png

Advanced

Secrets Manager

Secrets Manager

Store API keys in a secure manner using Secrets Manager.

Intermediate.png

Intermediate

SendGrid npm Integration

SendGrid npm Integration

Use SendGrid’s npm module to send emails from your site

Intermediate.png

Intermediate

Anchor 2
bottom of page