Creating a custom mobile OTP (One-Time Password) system in a WordPress contact form

Creating a custom mobile OTP (One-Time Password) system in a WordPress contact form requires the following steps:


Steps to Implement Mobile OTP in WordPress Contact Form

  1. Create a Contact Form
    • Add fields like name, mobile number, and OTP.
  2. Generate and Send OTP to Mobile
    • Use a third-party SMS gateway like Twilio, Nexmo (Vonage), or Textlocal to send OTPs to mobile numbers.
  3. Store the OTP Temporarily
    • Save the OTP in a session or database with a timestamp for validation.
  4. Verify OTP
    • Add a second step in the form where users enter the OTP for verification.
  5. Proceed After Verification
    • Submit the form only if the OTP is verified successfully.

Code Implementation

Step 1: Add Form HTML

Create a custom form with fields for mobile and OTP:

<form id="custom-mobile-otp-form" method="post" action="">
    <label for="name">Name:</label>
    <input type="text" id="name" name="name" required>
    
    <label for="mobile">Mobile Number:</label>
    <input type="text" id="mobile" name="mobile" required>
    <button type="button" id="send-otp">Send OTP</button>

    <div id="otp-section" style="display:none;">
        <label for="otp">Enter OTP:</label>
        <input type="text" id="otp" name="otp" required>
        <button type="submit" id="verify-otp">Submit</button>
    </div>
</form>
<div id="response-message"></div>

Step 2: Handle OTP via AJAX

Generate and Send OTP

Add this PHP code to your theme’s functions.php file:

add_action('wp_ajax_send_mobile_otp', 'handle_send_mobile_otp');
add_action('wp_ajax_nopriv_send_mobile_otp', 'handle_send_mobile_otp');

function handle_send_mobile_otp() {
    session_start();
    $mobile = sanitize_text_field($_POST['mobile']);
    $otp = rand(100000, 999999); // Generate a 6-digit OTP
    $_SESSION['mobile_otp'] = $otp;
    $_SESSION['mobile_otp_expiry'] = time() + 300; // OTP valid for 5 minutes

    // Integrate SMS Gateway API (e.g., Twilio, Nexmo, Textlocal)
    $api_key = 'YOUR_API_KEY'; // Replace with your SMS gateway API key
    $sender = 'TXTLCL';        // Replace with your SMS sender ID
    $message = "Your OTP is $otp. It is valid for 5 minutes.";

    // Example API Request for Textlocal
    $url = "https://api.textlocal.in/send/?apikey=$api_key&numbers=$mobile&message=" . urlencode($message) . "&sender=$sender";
    $response = wp_remote_get($url);

    if (is_wp_error($response)) {
        wp_send_json_error('Failed to send OTP. Please try again.');
    }

    wp_send_json_success('OTP sent successfully to ' . $mobile . '!');
}
Verify OTP

Add the following code to verify the OTP:

add_action('wp_ajax_verify_mobile_otp', 'handle_verify_mobile_otp');
add_action('wp_ajax_nopriv_verify_mobile_otp', 'handle_verify_mobile_otp');

function handle_verify_mobile_otp() {
    session_start();
    $user_otp = sanitize_text_field($_POST['otp']);

    if (isset($_SESSION['mobile_otp']) && isset($_SESSION['mobile_otp_expiry'])) {
        if (time() > $_SESSION['mobile_otp_expiry']) {
            wp_send_json_error('OTP expired!');
        } elseif ($user_otp == $_SESSION['mobile_otp']) {
            unset($_SESSION['mobile_otp']);
            unset($_SESSION['mobile_otp_expiry']);
            wp_send_json_success('OTP verified! Form submitted successfully.');
        } else {
            wp_send_json_error('Invalid OTP!');
        }
    } else {
        wp_send_json_error('No OTP found!');
    }
}

Step 3: Add JavaScript for AJAX

Create a custom JavaScript file and enqueue it in your theme:

jQuery(document).ready(function ($) {
    $('#send-otp').click(function () {
        const mobile = $('#mobile').val();

        if (mobile) {
            $.ajax({
                url: ajaxurl, // WordPress AJAX URL
                method: 'POST',
                data: {
                    action: 'send_mobile_otp',
                    mobile: mobile,
                },
                success: function (response) {
                    if (response.success) {
                        alert(response.data);
                        $('#otp-section').show();
                    } else {
                        alert(response.data);
                    }
                },
            });
        } else {
            alert('Please enter your mobile number.');
        }
    });

    $('#custom-mobile-otp-form').submit(function (e) {
        e.preventDefault();
        const otp = $('#otp').val();

        $.ajax({
            url: ajaxurl,
            method: 'POST',
            data: {
                action: 'verify_mobile_otp',
                otp: otp,
            },
            success: function (response) {
                if (response.success) {
                    $('#response-message').text(response.data);
                } else {
                    $('#response-message').text(response.data);
                }
            },
        });
    });
});

Enqueue this script in your theme’s functions.php file:

function custom_enqueue_mobile_otp_scripts() {
    wp_enqueue_script('custom-mobile-otp', get_template_directory_uri() . '/js/custom-mobile-otp.js', ['jquery'], null, true);
    wp_localize_script('custom-mobile-otp', 'ajaxurl', admin_url('admin-ajax.php'));
}
add_action('wp_enqueue_scripts', 'custom_enqueue_mobile_otp_scripts');

Step 4: Test the Implementation

  1. Add the form to a WordPress page or template.
  2. Test sending and verifying the OTP via the mobile number.

Notes

  • Replace the placeholder API details with those from your SMS gateway provider.
  • Use HTTPS and secure your SMS API key.
  • Optionally, save form submissions in the WordPress database after OTP verification for future reference.
0 0 votes
Article Rating
Subscribe
Notify of
guest
0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x