top of page
Writer's pictureFaysal Jaali

Send SMS Codes Using Twilio and Wix Velo: A Step-by-Step Guide


illustration sms code codemasters

Sending SMS codes using Twilio and Wix Velo is a straightforward way to enhance your website’s functionality and security. By leveraging Twilio's API and Wix Velo, you can seamlessly integrate SMS verification into your site, offering users a secure and smooth experience. Here's how to set it up step-by-step.


Prerequisites

  1. Twilio Account: Sign up for a Twilio account and obtain your Account SID and Auth Token.

  2. Wix Premium Plan: Required to use NPM packages in Wix Velo.

  3. Basic Velo Knowledge: Familiarity with backend and frontend coding in Wix.


Step 1: Enable Wix Velo and Install Twilio NPM

  1. Open your Wix Editor and enable Dev Mode.

  2. Navigate to the Code Files section and open Backend.

  3. Install the Twilio NPM package:

    • Click on Packages in the left sidebar.

    • Search for twilio and install it.


Step 2: Create a Backend Function to Send Codes

  1. In the Backend section, create a new file called twilio.web.js.

  2. Add the following code to integrate Twilio:


screenshot adding twilio.web.js In the Backend  of WIx

Step 3: Set Up Backend for Twilio API in Wix

  1. In the Wix Velo editor, go to the Backend section and create a new file, e.g., twilio.web.js.

  2. Add the following code to integrate Twilio's API:


import { Permissions, webMethod } from 'wix-web-module';
const accountSid = "your_account_sid"; // Replace with your Twilio Account SID
const authToken = "your_auth_token"; // Replace with your Twilio Auth Token
const client = require("twilio")(accountSid, authToken);

export const sendVerificationCode = webMethod(Permissions.Anyone, async (phoneNumber, code) => {

    try {
        const message = await client.messages.create({
            body: `This is your 6-digit code: ${code}`,
            from: "+your_twilio_phone", // Replace with your Twilio phone number
            to: phoneNumber,
        });
        console.log(`Message sent: ${message.sid}`);
        return { success: true, sid: message.sid };
    } catch (error) {
        console.error("Error sending verification code:", error);
        return { success: false, error: error.message };
    }
});

Step 3: Create the Frontend Interface

  1. Add the following elements to your page:

    • Input Field for the phone number (#phoneInput).

    • Button to send the verification code (#sendCodeButton).

    • Input Field for entering the code (#codeInput).

    • Button to verify the code (#verifyCodeButton).

    • Text Element for error/success messages (#statusMessage).


  2. Add the following code in the Page Code section:


import { sendVerificationCode } from "backend/twilio.web";

$w.onReady(() => {
    $w("#sendCodeButton").onClick(async () => {
        const phoneNumber = $w("#phoneInput").value;
        const code = Math.floor(100000 + Math.random() * 900000); // Generate a random 6-digit code

        if (!phoneNumber) {
            $w("#statusMessage").text = "Please enter a valid phone number.";
            return;
        }

        const response = await sendVerificationCode(phoneNumber, code);

        if (response.success) {
            $w("#statusMessage").text = "Verification code sent successfully!";
            console.log(`Verification Code: ${code}`); // Remove in production
        } else {
            $w("#statusMessage").text = "Failed to send verification code. Try again.";
            console.error(response.error);
        }
    });

    $w("#verifyCodeButton").onClick(() => {
        const enteredCode = $w("#codeInput").value;

        // Example: Match against the generated code (extend with a database for real applications)
        if (enteredCode === code.toString()) {
            $w("#statusMessage").text = "Verification successful!";
        } else {
            $w("#statusMessage").text = "Invalid verification code.";
        }
    });
});

Step 4: Test the Integration

  1. Preview your site.

  2. Enter a phone number and click "Send Code."

  3. Enter the received code and click "Verify Code."


Best Practices

  1. Secure Your Credentials: Store sensitive Twilio credentials in the Wix Secrets Manager for better security.

  2. Code Storage: Save generated codes in a secure database for comparison during verification.

  3. Rate Limiting: Prevent abuse by limiting how often codes can be sent to the same number.

  4. Remove Logs: Do not log sensitive data like verification codes in production.


Conclusion: SMS Codes Using Twilio and Wix Velo

Integrating SMS functionality using Twilio’s NPM package on Wix Velo is a simple yet powerful way to enhance your website's security and user experience. With minimal coding and Wix Velo’s flexibility, you can efficiently implement this feature to safeguard user accounts.


Looking for professional help to integrate advanced functionalities like 2FA on your website? Contact CodeMasters Agency today for expert web development and SEO solutions tailored to your needs.


Explore more tips and resources in our Web Development Blog and learn how we can take your online presence to the next level.

bottom of page