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

Google隐形reCAPTCHA出现invalid-input-response错误求助

Google隐形reCAPTCHA报错invalid-input-response的原因及修复方案

错误原因

  • 异步执行顺序冲突:表单提交事件中,grecaptcha.execute是异步操作,需要后台获取验证token,但当前代码仅在表单验证失败时阻止提交,验证通过时直接提交表单,导致token还未赋值到隐藏字段就完成了提交,后端接收到的ge-recaptcha值为空或无效,触发invalid-input-response错误。

修复方案

1. 调整前端提交逻辑

强制阻止表单默认提交行为,先完成表单验证,验证通过后再获取reCAPTCHA token,拿到token后手动提交表单:

<script>
document.querySelector('#form').addEventListener('submit', function(event) {
  // 立即阻止表单默认提交
  event.preventDefault();

  function validateForm() {
    const emailInput = document.querySelector('#email');
    if (emailInput.value.trim() === '') {
      alert('Please enter an email address');
      return false;
    }
    return true;
  }

  // 先做表单验证,不通过则终止流程
  if (!validateForm()) {
    return;
  }

  // 验证通过后获取reCAPTCHA token,完成后手动提交表单
  grecaptcha.ready(function() {
    grecaptcha.execute('6Lf_wNwlAAAAAFNZFttJLg6ii2KMsPvquGTEi1fh', { action: 'submit' }).then(function(token) {
      document.getElementById('recaptchaResponse').value = token;
      document.getElementById('form').submit();
    });
  });
});
</script>

2. 优化后端校验逻辑

增加空值校验,避免无效请求发送到reCAPTCHA验证接口,同时改用POST方式提交验证请求(更安全且无GET长度限制):

<?php
if(isset($_POST['submit'])){
  $url ='https://www.google.com/recaptcha/api/siteverify';
  $secret = '6Lf_wNwlAAAAAJ7eikDFSiBSD0vfuA5XFvcnEjou';
  $response = isset($_POST['ge-recaptcha']) ? trim($_POST['ge-recaptcha']) : '';

  // 先拦截空token的情况
  if(empty($response)){
    echo '<script>alert("请完成reCAPTCHA验证");</script>';
    exit;
  }

  $remoteip = $_SERVER['REMOTE_ADDR'];
  // 用POST方式构造验证请求
  $data = [
    'secret' => $secret,
    'response' => $response,
    'remoteip' => $remoteip
  ];
  $options = [
    'http' => [
      'header'  => "Content-type: application/x-www-form-urlencoded\r\n",
      'method'  => 'POST',
      'content' => http_build_query($data)
    ]
  ];
  $context  = stream_context_create($options);
  $request = file_get_contents($url, false, $context);
  $result=json_decode($request);
  
  print_r($result);
  if($result->success == true){
      ?>
      <script>
      alert("data saved successfully");
      </script>
      <?php
  }else{
      ?>
      <script>
      alert("data not saved");
      </script>
      <?php
  }
}
?>

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.22 17:02:50