Home » Wordpress » How to Set Up OTP Verification in WordPress Contact Form 7

How to Set Up OTP Verification in WordPress Contact Form 7

Home » Wordpress » How to Set Up OTP Verification in WordPress Contact Form 7

Are you looking to secure your WordPress forms and prevent spam? Adding OTP (One-Time Password) verification to Contact Form 7 is a simple yet powerful solution. In this guide, we’ll walk you through the steps to set up OTP verification and protect your forms effectively. Whether you’re new to WordPress or a seasoned developer, this tutorial will help you enhance your form’s security.


Why Add OTP Verification to Contact Form 7?

Adding OTP verification to your WordPress forms ensures:

  • Improved Security: Prevents spam and unauthorized submissions.
  • Verified Users: Ensures only genuine users can submit forms.
  • Better User Experience: Adds a layer of trust and reliability to your website.

What You Need

  1. Contact Form 7 plugin installed and activated.
  2. An OTP service provider such as:
  3. Basic knowledge of WordPress and how to edit your theme files.

Step 1: Add Fields for Phone Number and OTP

First, edit your Contact Form 7 form to include fields for the phone number and OTP input. Here’s an example:

<label> Phone Number

[tel* phone-number]

</label> <button id=”send-otp” type=”button”>Send OTP</button> <label> Enter OTP

[text* otp]

</label> [submit “Submit”]

Explanation:

  • *[tel phone-number]**: A required field for the user’s phone number.
  • *[text otp]**: A required field for the OTP input.
  • Send OTP Button: Used to trigger the OTP sending process.

Save the form after adding these fields.


Step 2: Add JavaScript for Sending OTP

You need JavaScript to handle the “Send OTP” button click and send the OTP to the user’s phone number. Add the following script to your theme:

document.getElementById('send-otp').addEventListener('click', function() {
    const phoneNumber = document.querySelector('[name="phone-number"]').value;

    if (!phoneNumber) {
        alert('Please enter a phone number.');
        return;
    }

    // AJAX request to send OTP
    fetch('/wp-json/send-otp/v1', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ phone: phoneNumber }),
    })
    .then(response => response.json())
    .then(data => {
        if (data.success) {
            alert('OTP sent successfully!');
        } else {
            alert('Failed to send OTP. Please try again.');
        }
    })
    .catch(error => console.error('Error:', error));
});

This script sends the phone number to a custom WordPress REST API endpoint (created in the next step) to generate and send the OTP.


Step 3: Create a Custom REST API Endpoint

To handle OTP generation and sending, add the following code to your theme’s functions.php file:

add_action('rest_api_init', function () {
    register_rest_route('send-otp/v1', '/', array(
        'methods' => 'POST',
        'callback' => 'send_otp_callback',
        'permission_callback' => '__return_true',
    ));
});

function send_otp_callback(WP_REST_Request $request) {
    $phone = $request->get_param('phone');
    if (!$phone) {
        return new WP_REST_Response(['success' => false, 'message' => 'Phone number is required.'], 400);
    }

    // Generate a random OTP
    $otp = rand(100000, 999999);
    
    // Save OTP in session or database for verification
    $_SESSION['otp'] = $otp;

    // Example: Sending OTP via Twilio
    $account_sid = 'your_account_sid';
    $auth_token = 'your_auth_token';
    $twilio_number = 'your_twilio_number';

    $client = new Twilio\Rest\Client($account_sid, $auth_token);
    try {
        $client->messages->create(
            $phone,
            ['from' => $twilio_number, 'body' => "Your OTP is: $otp"]
        );
        return new WP_REST_Response(['success' => true], 200);
    } catch (Exception $e) {
        return new WP_REST_Response(['success' => false, 'message' => $e->getMessage()], 500);
    }
}

This code creates a REST API endpoint /wp-json/send-otp/v1 that:

  • Accepts a phone number.
  • Generates a random OTP.
  • Sends the OTP via Twilio (or another service provider).

Replace the Twilio credentials with your own.


Step 4: Verify OTP Before Form Submission

To verify the OTP, hook into Contact Form 7’s wpcf7_before_send_mail action. Add this code to your functions.php file:

add_action('wpcf7_before_send_mail', function($contact_form) {
    $submission = WPCF7_Submission::get_instance();
    if ($submission) {
        $data = $submission->get_posted_data();
        $entered_otp = $data['otp'];

        if ($entered_otp != $_SESSION['otp']) {
            // Fail the submission
            $contact_form->skip_mail = true;
            $submission->set_status('validation_failed');
            $submission->add_error('otp', 'Invalid OTP. Please try again.');
        } else {
            // OTP verified, clear it
            unset($_SESSION['otp']);
        }
    }
});

This code validates the OTP entered by the user before the form submission is processed. If the OTP is incorrect, the form submission will fail.


Step 5: Test Your Setup

  1. Add the Contact Form 7 shortcode to a page.
  2. Open the page and enter a phone number.
  3. Click “Send OTP” and verify that the OTP is sent to the provided phone number.
  4. Enter the OTP and submit the form.
  5. Check if the form submission is successful only when the correct OTP is entered.

Conclusion

Adding OTP verification to Contact Form 7 enhances your form’s security and ensures that only verified users can submit data. By following this guide, you can integrate OTP verification seamlessly using WordPress REST API and an OTP service provider like Twilio.

If you found this guide helpful, share it with others and start securing your WordPress forms today! For any questions, feel free to leave a comment below.

1 thought on “How to Set Up OTP Verification in WordPress Contact Form 7”

  1. Pingback: How to Set Up WordPress - LinkInput

Leave a Comment

Your email address will not be published. Required fields are marked *