Trang chủCode functionBài viết
Code function

Hướng dẫn thêm xác nhận mã OTP khi gửi CF7

22/03/2025 921 lượt xem admin Cập nhật: 04/12/2025
5/5 - (519 bình chọn)

Mở file functions.php trong child theme của bạn (nếu chưa có child theme, bạn nên tạo child theme để tránh mất thay đổi khi update theme). Thêm đoạn code sau:

 

// OTP cf7
add_action('wp_footer', function() {
    ?>
    <script type="text/javascript">
        document.addEventListener('DOMContentLoaded', function() {
            // Gắn sự kiện click cho nút Lấy OTP
            const otpButton = document.querySelector('#get-otp-btn');
            if (otpButton) {
                otpButton.addEventListener('click', function() {
                    // Truy cập trường email qua name
                    const emailField = document.querySelector('[name="email-441"]');
                    const email = emailField ? emailField.value.trim() : '';
                    const messageBox = document.querySelector('#otp_message');


                    // Kiểm tra email
                    if (!email || !/^\S+@\S+\.\S+$/.test(email)) {
                        if (messageBox) {
                            messageBox.style.display = 'block';
                            messageBox.textContent = 'Vui lòng nhập email đúng định dạng trước khi lấy OTP.';
                        }
                        return;
                    }


                    // Ẩn thông báo lỗi
                    if (messageBox) {
                        messageBox.style.display = 'none';
                        messageBox.textContent = '';
                    }


                    // Gửi yêu cầu AJAX
                    jQuery.ajax({
                        url: '<?php echo admin_url('admin-ajax.php'); ?>',
                        type: 'POST',
                        data: {
                            action: 'send_cf7_otp',
                            email: email
                        },
                        success: function(response) {
                            if (response.success) {
                                alert(response.data.message);
                            } else {
                                alert(response.data.message);
                            }
                        },
                        error: function() {
                            alert('Lỗi khi gửi yêu cầu. Vui lòng thử lại.');
                        }
                    });
                });
            }
        });
    </script>
    <?php
});


// Xử lý AJAX: Gửi OTP qua email
function send_cf7_otp() {
    if (empty($_POST['email'])) {
        wp_send_json_error(['message' => 'Email không được để trống.']);
    }


    $email = sanitize_email($_POST['email']);
    if (!is_email($email)) {
        wp_send_json_error(['message' => 'Định dạng email không hợp lệ.']);
    }


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


    // URL mẫu (thay thế bằng URL thực tế của bạn)
    $otp_url = "https://thetindung.com.vn";


    // Tiêu đề email
    $subject = "Xác nhận mã OTP của bạn";


    // Nội dung email với HTML đầy đủ
  $message = "
<!DOCTYPE html>
<html lang='en'>
<head>
    <meta charset='UTF-8'>
    <meta name='viewport' content='width=device-width, initial-scale=1.0'>
    <style>
        body {
            font-family: Arial, sans-serif;
            margin: 0;
            padding: 0;
            background-color: #f4f4f4;
            color: #333;
            line-height: 1.6;
        }
        .email-container {
            max-width: 600px;
            margin: 20px auto;
            background: #ffffff;
            border-radius: 10px;
            box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
            overflow: hidden;
        }
        .email-header {
            background-color: #4CAF50;
            color: #ffffff;
            padding: 20px;
            text-align: center;
        }
        .email-header img {
            max-width: 120px;
            margin-bottom: 10px;
        }
        .email-body {
            padding: 20px;
        }
        .email-body h1 {
            color: #4CAF50;
            font-size: 24px;
            margin-bottom: 20px;
        }
        .email-body p {
            font-size: 16px;
            margin-bottom: 20px;
        }
        .otp-code {
            font-size: 32px;
            color: #ff5722;
            font-weight: bold;
            text-align: center;
            display: block;
            margin: 20px 0;
        }
        .email-footer {
            background-color: #f4f4f4;
            text-align: center;
            padding: 20px;
            border-top: 1px solid #dddddd;
        }
        .email-footer p {
            font-size: 14px;
            color: #888888;
            margin: 5px 0;
        }
        .social-links {
            margin: 10px 0;
        }
        .social-links a {
            margin: 0 5px;
            display: inline-block;
            text-decoration: none;
        }
        .social-links img {
            width: 40px;
            height: 40px;
            border-radius: 50%;
            box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
        }
    </style>
</head>
<body>
    <div class='email-container'>
        <div class='email-header'>
            <img src='https://webdy.vn/files/uploads/2023/10/logo-webdy-white2.png' alt='webdy.vn'>
            <h2>Webdy.vn</h2>
        </div>
        <div class='email-body'>
            <h1>Xác nhận mã OTP</h1>
            <p>Xin chào,</p>
            <p>Chúng tôi nhận được yêu cầu xác nhận email của bạn. Đây là mã OTP của bạn:</p>
            <span class='otp-code'>$otp_code</span>
            <p>Hãy nhập mã này để hoàn tất xác nhận. Mã có hiệu lực trong vòng <strong>5 phút</strong>.</p>
            <p>Nếu bạn không yêu cầu, vui lòng bỏ qua email này.</p>
        </div>
        <div class='email-footer'>
            <p>Theo dõi chúng tôi:</p>
            <div class='social-links'>
                <a href='https://facebook.com/' target='_blank'>
                    <img src='https://example.com/icons/facebook.png' alt='Facebook'>
                </a>
                <a href='https://twitter.com/' target='_blank'>
                    <img src='https://example.com/icons/twitter.png' alt='Twitter'>
                </a>
                <a href='https://instagram.com/' target='_blank'>
                    <img src='https://example.com/icons/instagram.png' alt='Instagram'>
                </a>
                <a href='https://linkedin.com/' target='_blank'>
                    <img src='https://example.com/icons/linkedin.png' alt='LinkedIn'>
                </a>
            </div>
            <p>© 2024 Webdy.vn. Tất cả các quyền được bảo lưu.</p>
        </div>
    </div>
</body>
</html>
";




    // Header email, đảm bảo định dạng HTML
    $headers = "MIME-Version: 1.0" . "\r\n";
    $headers .= "Content-Type: text/html; charset=UTF-8" . "\r\n";
    $headers .= "From: [email protected]" . "\r\n"; // Thay email này thành email của bạn


    // Gửi email
    if (wp_mail($email, $subject, $message, $headers)) {
        // Lưu OTP bằng Transient API
        $transient_key = 'cf7_otp_' . md5($email);
        set_transient($transient_key, $otp_code, 300); // Lưu OTP trong 5 phút
        wp_send_json_success(['message' => 'OTP đã được gửi đến email của bạn.']);
    } else {
        wp_send_json_error(['message' => 'Lỗi khi gửi OTP. Vui lòng thử lại.']);
    }
}
add_action('wp_ajax_send_cf7_otp', 'send_cf7_otp');
add_action('wp_ajax_nopriv_send_cf7_otp', 'send_cf7_otp');


// Xác thực OTP khi gửi form
add_filter('wpcf7_validate_text*', 'validate_cf7_otp', 20, 2);
function validate_cf7_otp($result, $tag) {
    $tag_name = $tag['name'];


    if ($tag_name === 'your-otp') {
        $email = isset($_POST['email-441']) ? sanitize_email($_POST['email-441']) : '';
        $submitted_otp = isset($_POST['your-otp']) ? sanitize_text_field($_POST['your-otp']) : '';


        // Lấy mã OTP từ Transient
        $transient_key = 'cf7_otp_' . md5($email);
        $saved_otp = get_transient($transient_key);


        if (!$saved_otp || $submitted_otp !== $saved_otp) {
            $result->invalidate($tag, 'Mã OTP không đúng. Vui lòng kiểm tra lại.');
        } else {
            delete_transient($transient_key); // Xóa OTP sau khi xác thực thành công
        }
    }


    return $result;
}


// Xóa OTP sau khi gửi form thành công (đề phòng lỗi lưu trữ)
add_action('wpcf7_mail_sent', function($contact_form) {
    $email = isset($_POST['email-441']) ? sanitize_email($_POST['email-441']) : '';
    $transient_key = 'cf7_otp_' . md5($email);
    delete_transient($transient_key);
});

Nội dung Form

<div class="custom-contact-form">
    <label for="name">Tên của bạn</label>
    [text* your-name id:name placeholder "Nhập tên của bạn"]

    <label for="tel-696">Số điện thoại</label>
    [tel* tel-696 minlength:10 maxlength:10 placeholder "0912345678"]

    <label for="email-441">Email của bạn</label>
    [email* email-441 autocomplete:email placeholder "[email protected]"]

    <label for="message">Nội dung gửi</label>
    [textarea* your-message id:message placeholder "Tôi muốn mua tên miền abc.com với giá:"]

    <label for="your-otp">Mã OTP:</label>
    <button type="button" id="get-otp-btn">Lấy OTP</button>
    [text* your-otp id:your-otp placeholder "Nhập mã OTP được gửi qua email của bạn"]

    <div id="otp_message">Vui lòng nhập email trước khi lấy OTP.</div>

    <button class="submit-button" type="submit">Gửi</button>
</div>

Thay đổi your-name, email-441, tel-696,… cho phù hợp

Nội dung đã bị khóa.

Nhập mật khẩu để xem thêm:

Chào ! Bạn thấy nội dung này thế nào?
webdy.vn
webdy.vn

Tạo web nhanh dùng thử miễn phí.

Chia sẻ ↗

Bài liên quan

×