WordpressBảo Mật

[Woocommerce] Chống spam đơn hàng bằng  OTP gmail với WooCommerce

Bạn là đơn vị bán hàng sẽ gặp tình trạng đơn hàng ảo xuất hiện tràn lan trên WooCommerce. Bạn đau đầu vì những đơn hàng spam làm rối tung hệ thống quản lý của bạn? Đừng lo, hôm nay hnitmedia sẽ chia sẻ cho bạn một giải pháp cực kỳ bá đạo: cách code chống spam đơn hàng bằng  OTP gmail vào WooCommerce chống spam đơn hàng – chặn spam, xử lý nhanh, không delay!

Vì sao cần xác minh đơn hàng bằng OTP?

  • Ngăn chặn đơn hàng rác, tránh tình trạng bom hàng.
  • Tăng độ tin cậy, giúp bạn lọc khách thật, khách giả.
  • Giúp hệ thống WooCommerce chạy mượt mà hơn, không bị spam gây quá tải.
  • Giảm tỷ lệ đơn hàng thất bại, giúp tối ưu lợi nhuận.

Cách hoạt động của OTP Order Verification for WooCommerce

Hệ thống này hoạt động như sau:

  1. Khi khách đặt hàng, họ phải nhập một mã OTP 6 chữ số gửi qua email.
  2. Mã OTP này chỉ có hiệu lực trong 3 phút – hết thời gian là vô dụng!
  3. Khách hàng chỉ được yêu cầu 1 mã mỗi phút – hết spam nhé!
  4. Tất cả quá trình gửi email được xử lý nhanh như chớp!

Cách tích hợp code chống spam đơn hàng bằng  OTP gmail vào WooCommerce

Dưới đây là đoạn code giúp bạn chặn spam đơn hàng bằng OTP. Đơn giản nhưng cực kỳ hiệu quả! Các bạn copy nó bỏ vào function.php là được nhé.

 /*
 * Description: Thêm chức năng OTP vào trang thanh toán WooCommerce không liên quan đến Flatsome theme.
 * Version: 1.0
 * Author: muathemewpgiare.com
 * Author URI: https://muathemewpgiare.com
 */

// Thêm chức năng enqueue script
add_action('wp_enqueue_scripts', 'enqueue_sweetalert_script_custom_plugin');
function enqueue_sweetalert_script_custom_plugin() {
    if (is_checkout()) {
        // Đưa vào SweetAlert2 từ CDN
        wp_enqueue_script('sweetalert2', 'https://cdn.jsdelivr.net/npm/sweetalert2@11', array('jquery'), null, true);
        // Thêm CSS từ Google Fonts để làm đẹp
        wp_enqueue_style('google_fonts', 'https://fonts.googleapis.com/css2?family=Roboto:wght@400;700&display=swap', false);
        // Thêm CSS tùy chỉnh cho giao diện Checkout
        wp_enqueue_style('custom_checkout_css', plugin_dir_url(__FILE__) . 'css/custom_checkout.css', false);
    }
}

// Thêm 6 trường nhập OTP vào form Checkout
add_action('woocommerce_after_order_notes', 'add_otp_six_fields_to_checkout_custom_plugin');
function add_otp_six_fields_to_checkout_custom_plugin($checkout) {
    echo '<div id="otp_checkout_field" class="otp-verification muathemewpgiare">';
    echo '<h3>' . __('Xác minh đơn hàng') . '</h3>';
    echo '<p class="otp-instruction">Hãy bấm nút gửi mã ở phía dưới, sau đó nhập mã xác minh gồm 6 chữ số đã được gửi đến email của bạn để xác nhận đơn hàng.</p>';
    echo '<div class="otp-input-wrapper muathemewpgiare">';
    for ($i = 1; $i <= 6; $i++) {
        woocommerce_form_field('otp_code_' . $i, array(
            'type'          => 'text',
            'class'         => array('otp-code muathemewpgiare'),
            'maxlength'     => 1,
            'required'      => true,
            'input_class'   => array('otp-input muathemewpgiare'),
            'label'         => false,
            'placeholder'   => '',
        ), $checkout->get_value('otp_code_' . $i));
    }
    echo '</div>';
    echo '<input type="hidden" name="order_otp_code" id="order_otp_code" />';
    echo '<button type="button" class="button alt otp-button muathemewpgiare" id="send_otp_button">' . __('Gửi mã xác thực') . '</button>';
    echo '<button type="button" class="button alt otp-button resend-button muathemewpgiare" id="resend_otp_button" style="display:none;">' . __('Gửi lại mã OTP') . '</button>';
    echo '<p id="otp_timer" class="muathemewpgiare" style="display:none;">Thời gian chờ: <span id="countdown">60</span> giây</p>';
    echo '</div>';
}

// JavaScript để xử lý nhập OTP và gửi OTP qua email
add_action('wp_footer', 'enqueue_otp_six_fields_script_custom_plugin');
function enqueue_otp_six_fields_script_custom_plugin() {
    if (is_checkout()) {
        ?>
<script type="text/javascript">
    jQuery(document).ready(function($) {
        // Tự động chuyển con trỏ khi người dùng nhập vào các ô OTP
        $('.otp-input').on('input', function() {
            if ($(this).val().length == 1) {
                $(this).next('.otp-input').focus();
            }
            updateOtpCode();
        });

        // Chuyển con trỏ về ô trước nếu nhấn Backspace
        $('.otp-input').on('keydown', function(e) {
            if (e.key === "Backspace" && $(this).val() === "") {
                $(this).prev('.otp-input').focus();
            }
        });

        // Cập nhật giá trị mã OTP vào trường ẩn để gửi lên server
        function updateOtpCode() {
            let otpCode = '';
            $('.otp-input').each(function() {
                otpCode += $(this).val();
            });
            $('#order_otp_code').val(otpCode);
        }

        // Kiểm tra email hợp lệ
        function isValidEmail(email) {
            var emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
            return emailRegex.test(email);
        }

        // Đếm ngược thời gian gửi lại OTP
        function startOtpCountdown() {
            var countdown = 60;
            $('#otp_timer').show();
            $('#countdown').text(countdown);
            var timer = setInterval(function() {
                countdown--;
                $('#countdown').text(countdown);
                if (countdown <= 0) {
                    clearInterval(timer);
                    $('#resend_otp_button').prop('disabled', false);
                    $('#countdown').text(60);
                }
            }, 1000);
        }

        // Xử lý gửi OTP
        $('#send_otp_button').on('click', function() {
            var email = $('input#billing_email').val();
            if (email === '' || !isValidEmail(email)) {
                Swal.fire({
                    icon: 'warning',
                    title: 'Lỗi!',
                    text: 'Vui lòng nhập email hợp lệ để nhận mã OTP.',
                });
                return;
            }

            $.ajax({
                type: 'POST',
                url: '<?php echo admin_url('admin-ajax.php'); ?>',
                data: {
                    action: 'send_order_otp',
                    email: email,
                },
                success: function(response) {
                    Swal.fire({
                        icon: response.success ? 'success' : 'error',
                        title: response.success ? 'Thành Công!' : 'Lỗi!',
                        text: response.message,
                    });
                    if (response.success) {
                        $('#send_otp_button').hide();
                        $('#resend_otp_button').show().prop('disabled', true);
                        startOtpCountdown();
                        $('.otp-input').first().focus(); // Focus vào ô đầu tiên sau khi gửi thành công

                        // Hiển thị thông báo dưới nút gửi
                        $('#otp_checkout_field').append('<p id="otp_info_message" class="muathemewpgiare">Mã OTP đã được gửi đến email của bạn. Vui lòng kiểm tra và nhập mã OTP vào các ô trên để tiếp tục.</p>');

                        // Hiển thị thông báo yêu cầu nhập mã OTP
                        Swal.fire({
                            icon: 'info',
                            title: 'Nhập mã OTP',
                            text: 'Vui lòng nhập mã OTP vào các ô trên và bấm Đặt hàng để hoàn tất quá trình thanh toán.',
                            confirmButtonText: 'Đã hiểu',
                            confirmButtonColor: '#007bff'
                        });
                    }
                }
            });
        });

        // Xử lý gửi lại OTP
        $('#resend_otp_button').on('click', function() {
            $('#send_otp_button').click(); // Tái sử dụng hàm gửi mã OTP
        });
    });
</script>

        <?php
    }
}

// Gửi mã OTP qua Email với giao diện đẹp hơn và thông tin chi tiết hơn
add_action('wp_ajax_nopriv_send_order_otp', 'send_order_otp_custom_plugin');
add_action('wp_ajax_send_order_otp', 'send_order_otp_custom_plugin');
function send_order_otp_custom_plugin() {
    // Kiểm tra thời gian lần gửi gần nhất (chặn spam gửi OTP)
    $last_sent_time = WC()->session->get('last_otp_sent_time');
    if ($last_sent_time && (time() - $last_sent_time) < 60) {
        wp_send_json(array('success' => false, 'message' => 'Vui lòng đợi 1 phút trước khi gửi lại mã OTP.'));
        return;
    }

    $email = sanitize_email($_POST['email']);
    if (empty($email)) {
        wp_send_json(array('success' => false, 'message' => 'Email không hợp lệ.'));
        return;
    }

    // Tạo mã OTP
    $otp_code = rand(100000, 999999);

    // Lưu mã OTP và thời gian hết hạn vào session
    WC()->session->set('order_otp_code', $otp_code);
    WC()->session->set('order_otp_expiry', time() + 3 * 60); // Thời hạn là 3 phút.
    WC()->session->set('last_otp_sent_time', time()); // Cập nhật thời gian gửi.

    // Nội dung email gửi mã OTP
    $subject = 'Mã OTP xác minh đơn hàng của bạn';
    $message = "<html><body>";
    $message .= "<h2 style='color: #333;'>Mã OTP Xác Minh Đơn Hàng</h2>";
    $message .= "<p style='font-size: 16px;'>Xin chào,</p>";
    $message .= "<p style='font-size: 16px;'>Cảm ơn bạn đã đặt hàng tại cửa hàng của chúng tôi. Để xác nhận đơn hàng của bạn, vui lòng nhập mã OTP sau đây:</p>";
    $message .= "<h3 style='font-size: 28px; color: #ff4081; text-align: center;'>$otp_code</h3>";
    $message .= "<p style='font-size: 16px;'>Mã này sẽ hết hạn sau <strong>3 phút</strong>. Nếu bạn không yêu cầu mã OTP này, vui lòng bỏ qua email này.</p>";
    $message .= "<p style='font-size: 16px; color: #666;'>Trân trọng,<br>Đội ngũ hỗ trợ - muathemewpgiare.com</p>";
    $message .= "</body></html>";

    // Đặt header cho email là HTML
    $headers = array('Content-Type: text/html; charset=UTF-8');

    // Gửi email OTP
    if (wp_mail($email, $subject, $message, $headers)) {
        wp_send_json(array('success' => true, 'message' => 'Mã OTP đã được gửi đến email của bạn. Vui lòng kiểm tra và xác minh đơn hàng.'));
    } else {
        wp_send_json(array('success' => false, 'message' => 'Có lỗi xảy ra khi gửi email. Vui lòng thử lại.'));
    }
}

// Xác minh mã OTP trước khi đặt hàng với thông báo đẹp hơn
add_action('woocommerce_checkout_process', 'validate_order_otp_custom_plugin');
function validate_order_otp_custom_plugin() {
    $otp_code_input = isset($_POST['order_otp_code']) ? sanitize_text_field($_POST['order_otp_code']) : '';
    $otp_code_saved = WC()->session->get('order_otp_code');
    $otp_expiry = WC()->session->get('order_otp_expiry');

    if (empty($otp_code_input)) {
        wc_add_notice('<script>Swal.fire({ icon: "warning", title: "Lỗi!", text: "Vui lòng nhập mã OTP để xác nhận đơn hàng.", confirmButtonColor: "#007bff" });</script>', 'error');
    } elseif (time() > $otp_expiry) {
        wc_add_notice('<script>Swal.fire({ icon: "warning", title: "Lỗi!", text: "Mã OTP đã hết hạn. Vui lòng gửi lại mã OTP.", confirmButtonColor: "#007bff" });</script>', 'error');
    } elseif ($otp_code_input != $otp_code_saved) {
        wc_add_notice('<script>Swal.fire({ icon: "error", title: "Lỗi!", text: "Mã OTP không chính xác. Vui lòng kiểm tra lại.", confirmButtonColor: "#007bff" });</script>', 'error');
    }
}

// Lưu mã OTP vào thông tin đơn hàng (tùy chọn)
add_action('woocommerce_checkout_update_order_meta', 'save_otp_to_order_meta_custom_plugin');
function save_otp_to_order_meta_custom_plugin($order_id) {
    if (!empty($_POST['order_otp_code'])) {
        update_post_meta($order_id, '_order_otp_code', sanitize_text_field($_POST['order_otp_code']));
    }
}

Lưu ý: Bạn cần có plugin hỗ trợ gửi email như WP Mail SMTP để đảm bảo email không bị vào spam

CSS cho đẹp chức năng chống spam đơn hàng bằng  OTP gmail vào WooCommerce

/* CSS cải tiến cho giao diện OTP */
.otp-verification.muathemewpgiare {
    text-align: center;
    margin: 30px auto;
    font-family: 'Roboto', sans-serif;
    border: 1px solid #ccc;
    border-radius: 25px;
    padding: 40px;
    background: linear-gradient(135deg, #e0f7fa, #ffffff);
    box-shadow: 0 8px 30px rgba(0, 0, 0, 0.15);
    transition: transform 0.4s ease, box-shadow 0.4s ease;
}

.otp-verification.muathemewpgiare:hover {
    transform: scale(1.02);
    box-shadow: 0 12px 40px rgba(0, 0, 0, 0.2);
}

.otp-instruction.muathemewpgiare {
    font-size: 20px;
    color: #333;
    margin-bottom: 30px;
    font-weight: 700;
    line-height: 1.6;
}

.otp-input-wrapper.muathemewpgiare {
    display: flex;
    gap: 25px;
    justify-content: center;
    margin-bottom: 30px;
}

.otp-input.muathemewpgiare {
    width: 60px;
    height: 75px;
    text-align: center;
    font-size: 28px;
    font-weight: bold;
    border: 2px solid #ddd;
    border-radius: 15px;
    outline: none;
    transition: border-color 0.4s ease, box-shadow 0.4s ease, transform 0.4s ease;
    background-color: #ffffff;
}

.otp-input.muathemewpgiare:focus {
    border-color: #42a5f5;
    box-shadow: 0 0 15px rgba(66, 165, 245, 0.5);
    transform: scale(1.1);
}

.otp-button.muathemewpgiare {
    background: linear-gradient(135deg, #42a5f5, #1e88e5);
    color: white;
    border: none;
    padding: 20px 40px;
    font-size: 22px;
    font-weight: bold;
    border-radius: 12px;
    cursor: pointer;
    transition: background 0.3s ease, transform 0.4s ease, box-shadow 0.4s ease;
    margin-top: 25px;
    box-shadow: 0 6px 15px rgba(66, 165, 245, 0.4);
}

.otp-button.muathemewpgiare:hover {
    background: linear-gradient(135deg, #1e88e5, #1565c0);
    transform: translateY(-4px);
    box-shadow: 0 10px 25px rgba(66, 165, 245, 0.6);
}

.resend-button.muathemewpgiare {
    margin-top: 20px;
    font-size: 18px;
    font-weight: 600;
    background-color: transparent;
    color: #42a5f5;
    text-decoration: underline;
    border: none;
    cursor: pointer;
    transition: color 0.4s ease, text-decoration 0.4s ease;
}

.resend-button.muathemewpgiare:disabled {
    color: #bbb;
    cursor: not-allowed;
}

.resend-button.muathemewpgiare:hover {
    color: #1e88e5;
    text-decoration: none;
}

#otp_timer.muathemewpgiare {
    font-size: 18px;
    color: #666;
    margin-top: 20px;
    font-weight: 600;
}

/* Hiệu ứng đặc biệt */
.otp-verification.muathemewpgiare::before {
    content: '';
    position: absolute;
    top: -10px;
    left: -10px;
    right: -10px;
    bottom: -10px;
    border-radius: 25px;
    background: linear-gradient(135deg, rgba(255, 64, 129, 0.2), rgba(66, 165, 245, 0.2));
    z-index: -1;
    filter: blur(20px);
    opacity: 0.7;
}

Những lợi ích khi dùng chức năng OTP chống spam tạo đơn hàng

  • Ngăn chặn spam đơn hàng hiệu quả, không còn tình trạng đơn hàng ảo tràn lan.
  • Bảo vệ website WooCommerce khỏi những kẻ xấu chuyên phá hoại.
  • Tăng trải nghiệm khách hàng bằng cách xác minh email nhanh chóng.
  • Giảm tải hệ thống, tránh bị spam email hàng loạt.

Để lại một bình luận

Email của bạn sẽ không được hiển thị công khai. Các trường bắt buộc được đánh dấu *

Back to top button