使用 Jquery Ajax 和 PHP 的 Google Invisible Recaptcha

Google Invisible Recaptcha Using Jquery Ajax and PHP

提问人:Dango 提问时间:1/24/2018 更新时间:12/12/2020 访问量:3730

问:

试图让我的表单使用 google invisible recaptcha 与我的 jQuery AJAX 和 PHP 正常工作。根据我的研究,令牌似乎没有通过AJAX正确发送到我的PHP页面。提交表单时,继续从我的PHP页面收到以下错误。

array(2) {
["success"]=>
bool(false)
["error-codes"]=>
array(1) {
[0]=>
string(22) "invalid-input-response"
  }
}

我的HTML / jQuery代码如下

<!doctype html>
<html>
<head>
  <meta charset="utf-8">
  <title>Demo</title>
  <script src="js/jquery-3.2.1.min.js"></script>
  <script src="https://www.google.com/recaptcha/api.js" async defer></script>

  <style>
    .grecaptcha-badge {
      display: block;
      float: left;
    }
  </style>

</head>

<body>
  <form id="myForm">
    <div>First Name*</div>
    <div><input id="first_name" name="first_name" required="" type="text"></div>
    <!--<span class="form-error">Please enter your first name.</span>-->

    <div>Last Name*</div>
    <div><input id="last_name" name="last_name" required="" type="text"></div>
    <!--<span class="form-error">Please enter your last name.</span>-->

    <button class="g-recaptcha" data-sitekey="6Ld1..." data-callback="onSubmit">submit</button>
  </form>
  <div id="status"></div>

    <script defer>
    function onSubmit(token) {
      var f = $("#myForm");

      $.ajax({
        type: "POST",
        url: "request.php",
        data: f.serialize(),
        dataType: "json",
        beforeSend: function() {
          $("#status").html("submitting data...");
        },
        success: function(response) {
          $("#status").html(response.text);
          if (response.type == "success") {
            window.location.replace("/myaccount");
          } else {
            $("#status").html("Captcha failed.");
          }
        },
        error: function() {
          $("#status").html("Failed.");
        }
      });
    }
  </script>
</body>
</html>

我的PHP代码没有正确处理令牌如下

<?php
if(isset($_POST['g-recaptcha-response'])) {
$result = json_decode(file_get_contents('https://www.google.com/recaptcha/api/siteverify?secret=['secret key']&response=$_POST["g-recaptcha-response"]&remoteip=$_SERVER["REMOTE_ADDR"]'), TRUE);

   //echo 'success';
   if($result['success'] == 'true') {
      // Captcha ok
      echo 'success';
        } else {
      // Captcha failed
      echo 'failed';
   }

var_dump($result);
}
?>

提前致谢!reCAPTCHA 文档真的很糟糕......

php jquery html ajax recaptcha

评论

0赞 Lawrence Cherone 1/24/2018
正在发送?如果没有,您是否尝试过使用而不是放在 ?$_POST['g-recaptcha-response']divclass="g-recaptcha"button
0赞 Lawrence Cherone 1/24/2018
此外,通过这样做,它不再是公正的,并且 jQuery 期望一个带有 not 的对象var_dump($result);successtype="success"echo "success"
0赞 Dango 1/24/2018
我尝试了 <div class=“g-recaptcha”></div>并且没有触发 onclick,“function onSubmit(token) { }”。在另一篇帖子中,有人提到“您的 onSubmit 需要处理/将令牌添加到 $.ajax 调用中”你知道这是什么意思吗?无论如何,PHP 将如何处理令牌?在下面发帖。stackoverflow.com/questions/43837623/......
0赞 Lawrence Cherone 1/24/2018
在我的回答后一秒钟,我可以看到为什么它不起作用。
0赞 Dango 1/24/2018
将不胜感激!

答:

4赞 Lawrence Cherone 1/24/2018 #1

我刚刚测试了您的前端代码,它工作正常,但您的后端代码不正确。

我已经调整了所有代码以处理json和错误等,但本质上问题在于您将参数传递给站点验证url的方式。$_POST

下面经过测试并正常工作:

请求.php

<?php
define('RECAPTCHA_SECRET_KEY', '******');

// json response helper
$json_response = function($data = []) {
    header('Content-Type: application/json; charset=utf-8');
    exit(json_encode($data));
};

// handle post
if ($_SERVER['REQUEST_METHOD'] == 'POST') {

    // define errors array
    $errors = [];

    // check g-recaptcha-response
    if (!isset($_POST['g-recaptcha-response'])) {
        $errors['recaptcha'] = 'Check the captcha form.';
    }

    // check other params
    if (empty($_POST['first_name'])) {
        $errors['first_name'] = 'First name is a required field.';
    }

    if (empty($_POST['last_name'])) {
        $errors['last_name'] = 'Last name is a required field.';
    }

    // if all good call API else error out
    if (!empty($errors)) {
        $json_response(['errors' => $errors]);
    }

    // call recaptcha site verify
    $response = file_get_contents(
        'https://www.google.com/recaptcha/api/siteverify?'.http_build_query([
            'secret'   => RECAPTCHA_SECRET_KEY,
            'response' => $_POST['g-recaptcha-response'],
            'remoteip' => $_SERVER['REMOTE_ADDR'],
        ])
    );
    $response = json_decode($response, true);

    // handle status and respond with json
    if (intval($response["success"]) !== 1) {
        $json_response(['errors' => ['recaptcha' => 'Captcha failed.']]);
    } else {
        $json_response(['success' => true]);
    }
}
?>

您的前端代码,只是添加了对 json 的处理。

<!doctype html>
<html>
    <head>
        <meta charset="utf-8">
        <title>Demo</title>
        <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js" integrity="sha256-FgpCb/KJQlLNfOu91ta32o/NMZxltwRo8QtmkMRdAu8=" crossorigin="anonymous"></script>
        <script src='https://www.google.com/recaptcha/api.js'></script>
        <style>
            .grecaptcha-badge {
                display: block;
                float: left;
            }
            .form-error {
                display:none;
            }
        </style>
    </head>

    <body>
        <form id="myForm">
            <div>First Name*</div>
            <div><input id="first_name" name="first_name" required="" type="text"></div>
            <span class="form-error">Please enter your first name.</span>

            <div>Last Name*</div>
            <div><input id="last_name" name="last_name" required="" type="text"></div>
            <span class="form-error">Please enter your last name.</span>

            <button class="g-recaptcha" data-sitekey="******" data-callback="onSubmit">submit</button>
        </form>
        <div id="status"></div>

        <script defer>
            function onSubmit(token) {

                var f = $("#myForm");

                f.find('.form-error').hide();

                $.ajax({
                    type: "POST",
                    url: "./request.php",
                    data: f.serialize(),
                    dataType: "json",
                    beforeSend: function() {
                        $("#status").html("submitting data...");
                    },
                    success: function(response) {
                        if (response.errors) {
                            if (response.errors.first_name) {
                                $('#first_name').parent().next().show();
                            }

                            if (response.errors.last_name) {
                                $('#last_name').parent().next().show();
                            }

                            if (response.errors.recaptcha) {
                                $('#status').html(response.errors.recaptcha);
                            } else {
                                $("#status").html("Please complete form.");
                            }
                        } else if (response.success) {
                            window.location.replace("/myaccount");
                        } else {
                            $("#status").html("Captcha failed.");
                        }
                    },
                    error: function() {
                        $("#status").html("Failed.");
                    }
                });
            }
        </script>
    </body>
</html>

希望它有所帮助。

评论

1赞 Lawrence Cherone 1/24/2018
NP,很乐意帮忙。
0赞 Sh.Dehnavi 1/24/2021
你也愿意在这个问题上帮助我吗?wordpress.stackexchange.com/questions/381919/......