本文介绍了Google Invisible Recaptcha使用Jquery Ajax和PHP的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

试图让我的表单使用谷歌隐形recaptcha正确使用我的jQuery AJAX和PHP。从我的研究看来,令牌似乎没有通过AJAX正确发送到我的PHP页面。

 数组(2){
[成功] =>
bool(false)
[error-codes] =>
array(1){
[0] =>
string(22)invalid-input-response
}
}

下面的HTML / jQuery代码
$ b

 <!doctype html>< html>< head> < meta charset =utf-8> <标题>演示< /标题> < script src =js / jquery-3.2.1.min.js>< / script> < script src =https://www.google.com/recaptcha/api.jsasync defer>< / script> <风格> .grecaptcha-badge {display:block;向左飘浮; }< / style>< / head>< body> < form id =myForm> < div>名字*< / div> < div>< input id =first_namename =first_namerequired =type =text>< / div> <! - < span class =form-error>请输入您的名字。< / span>  - > < div>姓*< / div> < div>< input id =last_namename =last_namerequired =type =text>< / div> <! - < span class =form-error>请输入您的姓氏。< / span>  - > < button class =g-recaptchadata-sitekey =6Ld1 ...data-callback =onSubmit> submit< / button> < /形式> < 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(提交数据...);},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。) ;}}); $ lt; / body>< / html>  

 <$ c  

如果(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'){
//验证码确定
echo'success';
} else {
//验证码失败
echo'failed';
}

var_dump($ result);
}
?>

预先感谢! reCAPTCHA文档确实很糟糕。

解决方案

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



我调整了所有的代码来处理json和错误等,但本质上这个问题是因为你传递

以下是测试和工作:



$ b p> request.php

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

// json响应助手
$ json_response =函数($ data = []){
header('Content-Type:application / json; charset = utf-8' );
exit(json_encode($ data));
};
$ b $ //处理后
if($ _SERVER ['REQUEST_METHOD'] =='POST'){

//定义错误数组
$错误= [];

//检查g-recaptcha-response
if(!isset($ _ POST ['g-recaptcha-response'])){
$ errors ['recaptcha'] ='检查验证码表单。';


//检查其他参数
if(empty($ _ POST ['first_name'])){
$ errors ['first_name'] ='First名称是必填字段。';


if(empty($ _ POST ['last_name'])){
$ errors ['last_name'] ='姓是必填字段。
}

//如果所有好的调用API都错误
if(!empty($ errors)){
$ json_response(['errors'=> ; $ errors]);
}

//调用recaptcha网站验证
$回复= 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);

//处理状态并用json响应
if(intval($ response [success])!== 1){
$ json_response(['errors'= > ['recaptcha'=>'验证码失败。']]);
} 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.jsintegrity =sha256-FgpCb / KJQlLNfOu91ta32o / NMZxltwRo8QtmkMRdAu8 =crossorigin = 匿名 >< /脚本>
< 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>名字*< / div>
< div>< input id =first_namename =first_namerequired =type =text>< / div>
< span class =form-error>请输入您的名字。< / span>

< div>姓*< / div>
< div>< input id =last_namename =last_namerequired =type =text>< / div>
< span class =form-error>请输入您的姓氏。< / span>

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

< script defer>
函数onSubmit(令牌){

var f = $(#myForm);

f.find('。form-error')。hide();
$ b $ .ajax({
类型:POST,
url:./request.php,
data:f.serialize(),
dataType:json,
beforeSend:function(){
$(#status)。html(submitting data ...);
},
成功:函数(响应){
if(response.errors){
if(response.errors.first_name){
$('#first_name')。parent()。next ();
}

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

if(response.errors.recaptcha){
$('#status')。html(response.errors.recaptcha);
} else {
$(#status)。html(请填写表单。);
}
} else if(response.success){
window.location.replace(/ myaccount);
} else {
$(#status)。html(验证码失败。);


error:function(){
$(#status)。html(Failed。);
}
});
}
< / script>
< / body>
< / html>

希望它有帮助。


Trying to get my form which uses google invisible recaptcha to work correctly with my my jQuery AJAX and PHP. From my research it seems that the token is not being sent to my PHP page correctly via AJAX. Keep getting the Error below from my PHP page when form is submitted.

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

My HTML / jQuery Code Below

<!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>

My PHP code which is not handling the token correctly is below

<?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);
}
?>

Thanks in advance! The reCAPTCHA documentation really sucks....

解决方案

I just tested your front end code and it works fine, but your backend code is incorrect.

I've tweaked all the code to handle json and errors etc, but essentially the problem is because of the way your passing the $_POST parameters to the site verify url.

Below is tested and working:

request.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]);
    }
}
?>

Your frontend code, just added handling of the 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>

Hope it helps.

这篇关于Google Invisible Recaptcha使用Jquery Ajax和PHP的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-02 01:49