如何解决 Google v3 reCaptcha 超时?

Bur*_*dog 11 php invisible-recaptcha recaptcha-v3

我们有一个 PHP 表单,它在 reCaptcha 上有几个选项卡和超时。一切都在一页中完成,如果表格在 <3 分钟内完成,它就可以正常工作。

一个解决方案的想法是将表单处理和 reCaptcha 移动到辅助页面进行处理。

问题是表单页面轮询谷歌服务以获取 reCaptcha 并将令牌值收集到隐藏字段。

<input type="hidden" name="recaptcha_response" id="recaptchaResponse">
Run Code Online (Sandbox Code Playgroud)

问题是如何在服务端处理页面请求这个token?这是客户端表单页面上使用的代码。我需要以某种方式重新生成要应用的令牌值:

$recaptcha_response

这是表单页面上的工作版本。从表单页面删除对发布令牌的要求很容易,只是不确定如何重新生成令牌以在服务器端页面上使用。

if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['recaptcha_response'])) {

// Build POST request:
$recaptcha_url = 'https://www.google.com/recaptcha/api/siteverify';
$recaptcha_secret = RECAPTCHA_SECRET_KEY;
$recaptcha_response = $_POST['recaptcha_response'];
$remoteip = $_SERVER['REMOTE_ADDR'];

// Make and decode POST request:
$recaptcha = file_get_contents($recaptcha_url . '?secret=' . $recaptcha_secret . '&response=' . $recaptcha_response. '&remoteip='.$remoteip);
$recaptcha = json_decode($recaptcha);

// Take action based on the score returned:
if ($recaptcha->score >= 0.5) {
Run Code Online (Sandbox Code Playgroud)

编辑添加:将重新验证码的初始化直到提交延迟计时问题,因为这似乎是一个选项:

https://developers.google.com/recaptcha/docs/v3

“2. 在操作或页面加载时调用 grecaptcha.execute”

Mik*_*ole 17

如果您不想过多更改代码,那么另一种方法是将 reCaptcha JavaScript 包装在一个命名函数中,设置一个时间间隔并轮询该函数,提示 reCaptcha 每三分钟向您的表单元素添加一个新令牌:

function getReCaptcha(){
    grecaptcha.ready(function() {
       ...
     });
 }

 getReCaptcha();  // This is the initial call
 setInterval(function(){getReCaptcha();}, 150000);
Run Code Online (Sandbox Code Playgroud)


ahw*_*hwm 6

我们最近也遇到了这个问题。我在GitHub 上找到了这个解决方案,它对我们来说运行良好。

这样做的好处是仅在用户与页面交互(例如提交表单)时才要求令牌,而不必一直要求令牌。

<script>
  grecaptcha.ready(function() {
      document.getElementById('contactform').addEventListener("submit", function(event) {

        event.preventDefault();

        grecaptcha.execute('mykey', {action: 'homepage'}).then(function(token) {
           document.getElementById("googletoken").value = token; 
           document.getElementById('contactform').submit();
        });        
      }, false);

  });
</script>
Run Code Online (Sandbox Code Playgroud)

  • rifton007 于 2 月 13 日评论@iwasherefirst2 该解决方案并不完美。因为,当我们在发送之前请求令牌时。该表单需要等待几秒钟才能接收令牌并随数据一起发送。 (2认同)