1

我最近尝试在我们的一个网站表单上实施 Recaptcha V3,但遇到了一个错误,它不允许某些用户提交表单,因为它返回错误消息“您已被检测为机器人......”在下面的代码中。

我将所有表单提交打印到日志文件中,每次失败时,$recaptcha->success、$recaptcha->action 和 $recaptcha->score 始终为空。

我发现它经常会为用户工作并发送消息。

我自己测试了表单,大部分时间它都可以正常工作,但我注意到如果我多次尝试提交表单,它偶尔会失败并返回错误。当 $recaptcha->success 失败时,$recaptcha->action 和 $recaptcha->score 始终为空。

我还注意到 $_POST['recaptcha_response'] 在这些情况下似乎是空的,即使它通过了第一个 isset if 语句。

//verify google captcha v3
if(isset($_POST['recaptcha_response'])){
    //build request
    $recaptcha_url = 'https://www.google.com/recaptcha/api/siteverify';
    $recaptcha_secret = 'MY_SECRET_KEY';
    $recaptcha_response = $_POST['recaptcha_response'];

    //get verify response data
    $ch = curl_init();

    curl_setopt_array($ch, [
        CURLOPT_URL => 'https://www.google.com/recaptcha/api/siteverify',
        CURLOPT_POST => true,
        CURLOPT_POSTFIELDS => [
            'secret' => $recaptcha_secret,
            'response' => $recaptcha_response
        ],
    CURLOPT_RETURNTRANSFER => true
    ]);

    $output = curl_exec($ch);
    curl_close($ch);

    $recaptcha = json_decode($output);


    // Take action based on the score returned:
    if ($recaptcha->success && $recaptcha->action == 'reportadvert' && $recaptcha->score > 0.1){            
        // Verified - success
        $save['captcha'] = "1";
    } else {
        // Not verified - show form error
        $errors['captcha'] = "You have been detected as a bot and blocked from sending this report for security reasons, please try again shortly or Contact us if you are still having issues.";
    }
} else {
     $errors['captcha'] = "You have been detected as a bot and blocked from sending this report for security reasons, please try again shortly or Contact us if you are still having issues.";
}  

这是我的表格(删除了我的一些其他字段)。请注意,我的表单/页面包含在一个 php 脚本中,我将表单发布到同一个 php 脚本:

<form method="post">
  <input type="hidden" name="recaptcha_response" id="recaptchaResponse">

  <button type="submit" name="SendEm">Report Advert</button>
  <input type="hidden" name="submitted" value="TRUE" />
</form>

我在页面顶部包含了 javascrit,我在发布此内容时删除了我的站点密钥:

<script src="https://www.google.com/recaptcha/api.js?render=MY_SITE_RECAPTCHA_KEY"></script>

grecaptcha.ready(function() {
    grecaptcha.execute('MY_SITE_RECAPTCHA_KEY', {action: 'reportadvert'}).then(function(token) {
    var recaptchaResponse = document.getElementById('recaptchaResponse');
    recaptchaResponse.value = token;
   });
});
4

1 回答 1

0

我会检查siteverify 响应中的错误代码。如果出现错误,您将不会得到响应的动作评分参数。

站点验证响应错误代码参考

于 2019-06-04T14:05:19.940 回答