reCaptcha V3仅在首次提交表单时验证失败

时间:2019-09-30 08:20:27

标签: javascript php recaptcha-v3

我正在尝试设置reCaptcha v3,并且可以正常工作。出于某种原因,我第一次提交表单失败,但是从第二次提交开始就可以了。我不知道为什么会这样?

<script src="https://www.google.com/recaptcha/api.js?render=MY_SITE_KEY"></script>
<script>
grecaptcha.ready(function () {
    grecaptcha.execute('MY_SITE_KEY', { action: 'contact' }).then(function (token) {
        var recaptchaResponse = document.getElementById('captcha-response');
        recaptchaResponse.value = token;
    });
});
</script>




 <input type="hidden" name="captcha-response" id="captcha-response">

PHP

$verifyResponse = file_get_contents('https://www.google.com/recaptcha/api/siteverify?secret='.$secretKey.'&response='.$_POST['captcha-response']);
$responseData = json_decode($verifyResponse);

     if(!$responseData->score < 0.5) {
      $message .= "Verification failed " . $responseData->score;
  }

当我第一次提交表单时,出现验证错误,但我的分数是0.9。

2 个答案:

答案 0 :(得分:0)

为什么要添加“!”用“ $ responseData->分数”?您可能需要用以下内容代替您的病情:

替换此:

if(!$responseData->score < 0.5) {
    $message .= "Verification failed " . $responseData->score;
}

有了这个:

if($responseData->score < 0.5) {
    $message .= "Verification failed " . $responseData->score;
}

PS:以下代码需要几秒钟的时间才能正确加载并获得“验证码响应”代码,因此您可能需要禁用所有提交按钮,并等到获得“验证码响应”才能在表单中启用提交按钮否则您需要实施另一种方法来延迟提交,使其仅在收到“验证码响应”代码后才执行。否则,您将不断收到“缺少输入响应”错误消息

<script src="https://www.google.com/recaptcha/api.js?render=MY_SITE_KEY"></script>
<script>
  grecaptcha.ready(function() {
    grecaptcha.execute('MY_SITE_KEY', {
      action: 'contact'
    }).then(function(token) {
      var recaptchaResponse = document.getElementById('captcha-response');
      recaptchaResponse.value = token;
    });
  });
</script>

答案 1 :(得分:0)

您应该在发生错误表单验证后重新生成 reCaptcha 令牌。 令牌 reCaptcha 仅有效一次。

因此,您有两种方法可以解决此问题。

1.发生错误时重新加载页面

这是最简单的方法。您只需要在发生表单验证错误时重新加载页面。

当然,这会触发 reCaptcha 生成新令牌。

2.使用 AJAX 处理(非重新加载页面)

这是最好的方法,因为这将有助于用户不丢失表单数据并继续填写表单。

所以,这是你应该做的。

<!-- Put this hidden input inside of your form tag -->
<input name="_recaptcha" type="hidden">

<script src="https://www.google.com/recaptcha/api.js?render=YOUR_SITEKEY_HERE"></script>
<script>
  // This will generate reCaptcha token and set to input hidden
  const generateRecaptcha = function() {
    grecaptcha.execute(
      "YOUR_SITEKEY_HERE", {
        action: "YOUR_ACTION_NAME"
      }).then(function(token) {
      if (token) {
        document.querySelector("input[name='_recaptcha']").value = token;
      }
    });
  }

  // Call it when page successfully loaded
  grecaptcha.ready(function() {
    generateRecaptcha();
  });

  // Do your AJAX code here
  $.ajax({
    url: "https://example.com",
    success: function(response) {
      console.log(response);
    },
    error: function(error) {
      // Call again the generator token reCaptcha whenever error occured
      generateRecaptcha();
    }
</script>

不要忘记输入您的站点密钥和操作名称。确保操作名称与您的后端操作名称匹配。

Medium Article

相关问题