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

Google reCAPTCHA v3验证始终返回success:false问题求助

解决reCAPTCHA v3始终返回success:false的问题

我来帮你排查一下问题,结合你的代码来看,主要有几个关键原因,咱们一步步来解决:

1. Token生成时机错误,导致过期失效

你的代码在页面加载完成后就立即生成了reCAPTCHA token,但这个token的有效期只有2分钟。如果用户打开页面后过了很久才提交表单,token就会直接失效,这是验证失败的常见原因。

修复方法:

把token生成逻辑移到表单提交事件里,确保每次提交都生成新鲜的有效token:

<script>
$(document).ready(function() {
    $('#testform').submit(function(e) {
        // 先阻止表单默认提交行为
        e.preventDefault();
        const form = this;
        
        grecaptcha.ready(function() {
            grecaptcha.execute('my_site_key', {action: 'homepage'}).then(function(token) {
                // 将新生成的token赋值到隐藏字段
                document.getElementById('recaptchaResponse').value = token;
                // 提交表单
                form.submit();
            });
        });
    });
});
</script>

2. 使用GET请求验证token,不符合接口规范

Google的reCAPTCHA siteverify接口推荐且更兼容POST请求,你当前用file_get_contents拼接URL发送GET请求,可能遇到以下问题:

  • 部分服务器禁用了allow_url_fopen,导致file_get_contents无法发起请求
  • GET请求的URL长度存在限制(虽然token长度一般不会触发,但这不是标准用法)
  • 接口对GET请求的容错性不如POST

修复方法:

改用curl发起POST请求(比file_get_contents更稳定),修改你的contact.php代码:

<?php
// 先检查验证字段是否存在
if (!isset($_POST['recaptcha_response'])) {
    echo '请完成验证';
    exit;
}

$recaptcha_url = 'https://www.google.com/recaptcha/api/siteverify';
$recaptcha_secret = 'my_secret_key';
$recaptcha_response = $_POST['recaptcha_response'];

// 用curl发起POST请求
$ch = curl_init($recaptcha_url);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query([
    'secret' => $recaptcha_secret,
    'response' => $recaptcha_response,
    // 可选:添加用户IP,提升验证准确性
    'remoteip' => $_SERVER['REMOTE_ADDR']
]));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$recaptcha = curl_exec($ch);
curl_close($ch);

$recaptcha = json_decode($recaptcha);

// 先确保解码成功,避免报错
if ($recaptcha && $recaptcha->success) {
    if ($recaptcha->score >= 0.5) {
        echo 'Pass !';
    } else {
        echo 'Spammer';
    }
} else {
    // 开发阶段可以打印错误码排查,上线后记得移除
    if ($recaptcha) {
        print_r($recaptcha->{'error-codes'});
    }
    echo 'Connection failed';
}
?>

3. 额外排查点

  • 再次确认站点密钥和密钥完全匹配,且Google reCAPTCHA后台配置了正确的域名(本地测试填localhost,线上填实际域名)
  • 检查服务器是否能访问https://www.google.com/recaptcha/api/siteverify,可以在服务器终端执行curl https://www.google.com/recaptcha/api/siteverify测试连通性
  • 开启PHP错误提示,查看是否有file_get_contents或json_decode相关的报错(比如allow_url_fopen被禁用)

按照上面的方法修改后,应该就能解决验证失败的问题了。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.08 14:38:15