如何在WordPress全站部署reCAPTCHA Enterprise v3?
WordPress全站部署reCAPTCHA Enterprise v3完整方案
一、全局注入reCAPTCHA Enterprise脚本
不要用短代码单页加载,通过主题functions.php或自定义插件添加全局脚本,确保所有页面都加载验证资源:
function enqueue_recaptcha_enterprise() { wp_enqueue_script('recaptcha-enterprise', 'https://www.google.com/recaptcha/enterprise.js?render=你的站点密钥', array(), null, true); } add_action('wp_enqueue_scripts', 'enqueue_recaptcha_enterprise');
二、前端全局生成并携带令牌
编写全局JS,自动生成验证令牌并附加到所有表单、支付链接中,覆盖全站交互场景:
document.addEventListener('DOMContentLoaded', function() { grecaptcha.enterprise.ready(function() { // 生成全局令牌,action可根据场景自定义(如form_submit、payment_init) grecaptcha.enterprise.execute('你的站点密钥', {action: 'global_site_action'}).then(function(token) { window.recaptchaToken = token; // 给所有表单添加隐藏令牌字段 document.querySelectorAll('form').forEach(form => { let tokenInput = document.createElement('input'); tokenInput.type = 'hidden'; tokenInput.name = 'g-recaptcha-response'; tokenInput.value = token; form.appendChild(tokenInput); }); }); }); // 处理支付链接点击,将令牌附加到URL参数 document.querySelectorAll('a.payment-link').forEach(link => { link.addEventListener('click', function(e) { e.preventDefault(); let targetUrl = new URL(this.href); targetUrl.searchParams.append('g-recaptcha-response', window.recaptchaToken); window.location.href = targetUrl.toString(); }); }); });
将这段JS添加到主题的自定义JS区域,或通过wp_enqueue_script作为独立脚本加载。
三、后端全局验证令牌(核心步骤)
短代码的本质缺陷是缺少后端验证,必须在所有用户请求中校验令牌有效性,添加以下代码到functions.php或自定义插件:
function verify_recaptcha_enterprise_token() { $token = isset($_POST['g-recaptcha-response']) ? $_POST['g-recaptcha-response'] : ($_GET['g-recaptcha-response'] ?? ''); if (empty($token)) return; $secret_key = '你的密钥'; $project_id = '你的Google Cloud项目ID'; $site_key = '你的站点密钥'; // 调用reCAPTCHA Enterprise验证API $api_url = "https://recaptchaenterprise.googleapis.com/v1/projects/{$project_id}/assessments?key={$secret_key}"; $response = wp_remote_post($api_url, array( 'body' => json_encode(array( 'event' => array( 'token' => $token, 'siteKey' => $site_key, 'action' => 'global_site_action' // 需与前端action完全一致 ) )), 'headers' => array('Content-Type' => 'application/json'), 'timeout' => 10 )); if (is_wp_error($response)) { wp_die('验证失败,请刷新页面重试'); } $result = json_decode(wp_remote_retrieve_body($response), true); // 分数阈值可根据业务调整,建议生产环境设0.5以上 if (empty($result['riskAnalysis']['score']) || $result['riskAnalysis']['score'] < 0.5 || $result['event']['action'] !== 'global_site_action') { wp_die('疑似机器人行为,验证不通过'); } } // 针对前端所有请求验证 add_action('init', 'verify_recaptcha_enterprise_token'); // 针对后台表单提交验证 add_action('admin_init', 'verify_recaptcha_enterprise_token');
关键注意事项
- 替换代码中所有占位符(站点密钥、密钥、项目ID)为实际值
- 不同场景可设置不同action(如表单用
form_submit,支付用payment_init),后端需对应验证action一致性 - 测试阶段可降低分数阈值(如0.1),生产环境根据实际业务调整
- 不要依赖短代码,短代码仅加载前端脚本无后端验证,无法真正完成安全评估
内容的提问来源于stack exchange,提问作者Mark Lick
相关产品推荐
相关产品推荐

