WooCommerce给账户注册模块添加谷歌验证码【纯代码】

tencent promotion
原创作者: Fengjiajun

WooCommerce给账户注册模块添加谷歌验证码【纯代码】

在 WooCommerce 中,如果你的网站被骚扰机器人盯上了,机器人可能会每天不停的在你的“My Account”注册页面自动注册各种乱七八糟的账户,属实可恨。解决办法也很简单,就是添加一个验证码!接下来给大家介绍一种通过【纯代码、非插件】的方式在“My Account”注册页面添加 Google reCAPTCHA 验证码,可以按照以下步骤操作:

1. 获取 Google reCAPTCHA API 密钥
首先,你需要在 Google reCAPTCHA 官网 注册并获取 API 密钥(Site Key 和 Secret Key),注意,这里的版本请选择V2,不要选择V3。

2. 在主题的 functions.php 文件中添加代码
将以下代码添加到当前主题的 functions.php 文件中:

// 添加 reCAPTCHA 脚本
function add_google_recaptcha_script() {
    if (is_account_page()) {
        wp_enqueue_script('google-recaptcha', 'https://www.google.com/recaptcha/api.js', array(), null, true);
    }
}
add_action('wp_enqueue_scripts', 'add_google_recaptcha_script');

// 在注册表单中添加 reCAPTCHA
function add_recaptcha_to_registration_form() {
    if (is_account_page()) {
        echo '<div class="g-recaptcha" data-sitekey="YOUR_SITE_KEY"></div>';
    }
}
add_action('woocommerce_register_form', 'add_recaptcha_to_registration_form');

// 验证 reCAPTCHA
function validate_recaptcha_on_registration($errors, $username, $email) {
    if (isset($_POST['g-recaptcha-response'])) {
        $recaptcha_response = sanitize_text_field($_POST['g-recaptcha-response']);
        $secret_key = 'YOUR_SECRET_KEY';
        $response = wp_remote_get("https://www.google.com/recaptcha/api/siteverify?secret={$secret_key}&response={$recaptcha_response}");
        $response_data = json_decode(wp_remote_retrieve_body($response));

        if (!$response_data->success) {
            $errors->add('recaptcha_error', __('Please verify that you are not a robot.', 'woocommerce'));
        }
    } else {
        $errors->add('recaptcha_error', __('reCAPTCHA verification failed. Please try again.', 'woocommerce'));
    }
    return $errors;
}
add_filter('woocommerce_registration_errors', 'validate_recaptcha_on_registration', 10, 3);

3. 替换 YOUR_SITE_KEY 和 YOUR_SECRET_KEY
将代码中的 YOUR_SITE_KEY 和 YOUR_SECRET_KEY 替换为你在 Google reCAPTCHA 获取的实际密钥。

4. 测试
保存更改后,访问 WooCommerce 的“My Account”页面,查看注册表单中是否显示 reCAPTCHA 验证码,并测试验证功能是否正常工作。

5. 测试效果展示: