You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在WordPress自定义HTML表单中用reCaptcha V3验证用户响应?

解决方案:给Eloqua表单添加reCaptcha V3的安全实现

核心问题分析

你当前的实现存在明显漏洞:恶意攻击者可以直接构造POST请求发送到Eloqua的表单地址,完全绕过前端的reCaptcha验证逻辑,垃圾信息依然能进入系统。必须把reCaptcha验证和表单提交的控制权转移到服务器端,再由服务器转发请求到Eloqua,才能彻底解决问题。

具体实现步骤

1. 修改前端表单结构

  • 移除表单原有的action和method属性,避免用户直接提交
  • 添加隐藏字段存储reCaptcha token:<input type="hidden" name="recaptcha_token" id="recaptcha_token">
  • 保留Eloqua生成的所有原生字段(如elqFormName、elqSiteId等隐藏项)
  • 给表单提交按钮绑定JS事件,先获取reCaptcha token,再通过AJAX把完整表单数据发送到WordPress自定义端点

示例前端JS代码:

document.getElementById('your-form-id').addEventListener('submit', function(e) {
    e.preventDefault();
    
    grecaptcha.ready(function() {
        // 获取reCaptcha V3验证token
        grecaptcha.execute('你的reCaptcha站点密钥', {action: 'form_submit'}).then(function(token) {
            document.getElementById('recaptcha_token').value = token;
            
            // 收集所有表单数据
            const formData = new FormData(this);
            // 手动指定AJAX动作(对应后端函数)
            formData.append('action', 'submit_eloqua_form');
            
            // 发送请求到WordPress后端
            fetch('/wp-admin/admin-ajax.php', {
                method: 'POST',
                body: formData,
                headers: {
                    'X-Requested-With': 'XMLHttpRequest'
                }
            })
            .then(res => res.json())
            .then(data => {
                data.success 
                    ? alert('表单提交成功!') 
                    : alert('提交失败:' + data.message);
            })
            .catch(err => {
                console.error('请求异常:', err);
                alert('提交失败,请稍后重试');
            });
        });
    });
});

2. 配置WordPress后端AJAX处理

在主题的functions.php中添加以下代码:

// 注册AJAX处理函数(支持登录/未登录用户)
add_action('wp_ajax_submit_eloqua_form', 'submit_eloqua_form_handler');
add_action('wp_ajax_nopriv_submit_eloqua_form', 'submit_eloqua_form_handler');

function submit_eloqua_form_handler() {
    // CSRF验证
    check_ajax_referer('eloqua_form_nonce', 'nonce');
    
    // 获取并验证reCaptcha token
    $recaptcha_token = isset($_POST['recaptcha_token']) ? sanitize_text_field($_POST['recaptcha_token']) : '';
    if (empty($recaptcha_token)) {
        wp_send_json_error(['message' => '缺少验证信息']);
    }

    // 调用Google验证API
    $secret_key = '你的reCaptcha密钥';
    $verify_res = wp_remote_post('https://www.google.com/recaptcha/api/siteverify', [
        'body' => [
            'secret' => $secret_key,
            'response' => $recaptcha_token,
            'remoteip' => $_SERVER['REMOTE_ADDR']
        ]
    ]);

    if (is_wp_error($verify_res)) {
        wp_send_json_error(['message' => '验证服务异常']);
    }

    $verify_data = json_decode(wp_remote_retrieve_body($verify_res), true);
    // 验证分数(V3返回0-1的分数,建议阈值设0.5,可按需调整)
    if (!$verify_data['success'] || $verify_data['score'] < 0.5) {
        wp_send_json_error(['message' => '验证未通过,请重试']);
    }

    // 整理要发送给Eloqua的表单数据
    $eloqua_data = [];
    foreach ($_POST as $key => $val) {
        // 排除reCaptcha、nonce和AJAX动作字段
        if (!in_array($key, ['recaptcha_token', 'nonce', 'action'])) {
            $eloqua_data[$key] = sanitize_text_field($val);
        }
    }

    // 转发请求到Eloqua表单地址
    $eloqua_res = wp_remote_post('https://s########.t.eloqua.com/e/f2', [
        'body' => $eloqua_data,
        'headers' => ['Content-Type' => 'application/x-www-form-urlencoded']
    ]);

    if (is_wp_error($eloqua_res)) {
        wp_send_json_error(['message' => '提交失败,请稍后重试']);
    }

    // 根据Eloqua响应状态判断结果(通常200为成功)
    $status_code = wp_remote_retrieve_response_code($eloqua_res);
    $status_code === 200 
        ? wp_send_json_success(['message' => '提交成功']) 
        : wp_send_json_error(['message' => '提交失败,请稍后重试']);

    wp_die(); // 必须调用以结束AJAX请求
}

3. 添加CSRF保护

在前端表单内部添加WordPress的nonce字段,防止跨站请求伪造:

<?php wp_nonce_field('eloqua_form_nonce', 'nonce'); ?>

4. 加载reCaptcha脚本

在主题functions.php中添加加载reCaptcha脚本的代码:

add_action('wp_enqueue_scripts', 'enqueue_recaptcha_script');
function enqueue_recaptcha_script() {
    wp_enqueue_script(
        'recaptcha',
        'https://www.google.com/recaptcha/api.js?render=你的reCaptcha站点密钥',
        [],
        null,
        true // 放在页面底部加载
    );
}

关键注意事项

  • 测试阶段可以使用Google提供的测试密钥:站点密钥6LeIxAcTAAAAAJcZVRqyHh71UMIEGNQ_MXjiZKhI,密钥6LeIxAcTAAAAAGG-vFI1TnRWxMZNFuojJ4WifJWe,测试时会固定返回0.9的分数
  • reCaptcha分数阈值可根据实际情况调整:垃圾信息多就提高到0.7,误判多就降到0.3
  • 确保在Google reCaptcha控制台中将你的域名加入允许列表

内容的提问来源于stack exchange,提问作者callum21

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.01 17:22:38