Javascript 如何正确添加Google ReCaptcha

Javascript 如何正确添加Google ReCaptcha,javascript,php,ajax,validation,recaptcha,Javascript,Php,Ajax,Validation,Recaptcha,我有一个PHP联系人表单,它在服务器端通过AJAX/JSON执行验证,并将错误推送到Javascript以打印错误并相应地修改HTML/CSS 如何使用AJAX验证正确地实现Google ReCaptcha 这是我的代码尝试 recompcha片段: //reCAPTCHA validation if (isset($_POST['g-recaptcha-response'])) { require('component/recaptcha/src/autolo

我有一个PHP联系人表单,它在服务器端通过AJAX/JSON执行验证,并将错误推送到Javascript以打印错误并相应地修改HTML/CSS

如何使用AJAX验证正确地实现Google ReCaptcha

这是我的代码尝试

recompcha片段:

    //reCAPTCHA validation
    if (isset($_POST['g-recaptcha-response'])) {

        require('component/recaptcha/src/autoload.php');

        $recaptcha = new \ReCaptcha\ReCaptcha(SECRET_KEY, new \ReCaptcha\RequestMethod\SocketPost());

        $resp = $recaptcha->verify($_POST['g-recaptcha-response'], $_SERVER['REMOTE_ADDR']);

          if (!$resp->isSuccess()) {
                $errors = json_encode(array('type'=>'error', 'text' => 'Captcha is Required!'));
                die($output);
          }
    }
<?php

$errors         = array();      // array to hold validation errors
$data           = array();      // array to pass back data

// validate the variables ======================================================
    // if any of these variables don't exist, add an error to our $errors array

    if (empty($_POST['firstName']))
        $errors['firstName'] = 'First Name is required.';

    if (empty($_POST['lastName']))
        $errors['lastName'] = 'Last Name is required.';

    if (empty($_POST['companyName']))
        $errors['companyName'] = 'Company Name is required.';

    if (empty($_POST['companyAddress']))
        $errors['companyAddress'] = 'Company Address is required.';

    if (empty($_POST['city']))
        $errors['city'] = 'City is required.';

    if (empty($_POST['state']))
        $errors['state'] = 'State is required.';

    if (empty($_POST['emailAddress']))
        $errors['emailAddress'] = 'Email Address is required.';

    if (empty($_POST['comment']))
        $errors['comment'] = 'Comment is required.';

        //reCAPTCHA validation
        if (isset($_POST['g-recaptcha-response'])) {

            require('component/recaptcha/src/autoload.php');

            $recaptcha = new \ReCaptcha\ReCaptcha(SECRET_KEY, new \ReCaptcha\RequestMethod\SocketPost());

            $resp = $recaptcha->verify($_POST['g-recaptcha-response'], $_SERVER['REMOTE_ADDR']);

              if (!$resp->isSuccess()) {
                    $errors = json_encode(array('type'=>'error', 'text' => 'Captcha is Required!'));
                    die($output);
              }
        }


// return a response ===========================================================

    // if there are any errors in our errors array, return a success boolean of false
    if ( ! empty($errors)) {

        // if there are items in our errors array, return those errors
        $data['success'] = false;
        $data['errors']  = $errors;
    } else {

        // if there are no errors process our form, then return a message

        // DO ALL YOUR FORM PROCESSING HERE
        // THIS CAN BE WHATEVER YOU WANT TO DO (LOGIN, SAVE, UPDATE, WHATEVER)

        // show a message of success and provide a true success variable
        $data['success'] = true;
        $data['message'] = 'Success!';
    }

    // return all our data to an AJAX call
    echo json_encode($data);
// Start
$(document).ready(function() {

    // process the form
    $('form').submit(function(event) {

        $('.form-group').removeClass('has-error'); // remove the error class
        $('.help-block').remove(); // remove the error text

        // get the form data
        // there are many ways to get this data using jQuery (you can use the class or id also)
        var formData = {
            'firstName'                 : $('input[name=firstName]').val(),
            'lastName'              : $('input[name=lastName]').val(),
            'companyName'               : $('input[name=companyName]').val(),
            'companyAddress'                : $('input[name=companyAddress]').val(),
            'city'              : $('input[name=city]').val(),
            'state'                 : $('input[name=state]').val(),
            'emailAddress'          : $('input[name=emailAddress]').val(),
            'comment'   : $('input[name=comment]').val()
        };

        // process the form
        $.ajax({
            type        : 'POST', // define the type of HTTP verb we want to use (POST for our form)
            url         : 'formMaster.php', // the url where we want to POST
            data        : formData, // our data object
            dataType    : 'json', // what type of data do we expect back from the server
            encode      : true
        })
            // using the done promise callback
            .done(function(data) {

                // log data to the console so we can see
                console.log(data);

                // here we will handle errors and validation messages
                if ( ! data.success) {

                    // handle errors for name ---------------
                    if (data.errors.firstName) {
                        $('#firstName-group').addClass('has-error'); // add the error class to show red input
                        $('#firstName-group').append('<div class="help-block">' + data.errors.firstName + '</div>'); // add the actual error message under our input
                    }

                    // handle errors for name ---------------
                    if (data.errors.lastName) {
                        $('#lastName-group').addClass('has-error'); // add the error class to show red input
                        $('#lastName-group').append('<div class="help-block">' + data.errors.lastName + '</div>'); // add the actual error message under our input
                    }

                    // handle errors for name ---------------
                    if (data.errors.companyName) {
                        $('#companyName-group').addClass('has-error'); // add the error class to show red input
                        $('#companyName-group').append('<div class="help-block">' + data.errors.companyName + '</div>'); // add the actual error message under our input
                    }

                    // handle errors for Company Address ---------------
                    if (data.errors.companyAddress) {
                        $('#companyAddress-group').addClass('has-error'); // add the error class to show red input
                        $('#companyAddress-group').append('<div class="help-block">' + data.errors.companyAddress + '</div>'); // add the actual error message under our input
                    }

                    // handle errors for Company Address ---------------
                    if (data.errors.city) {
                        $('#city-group').addClass('has-error'); // add the error class to show red input
                        $('#city-group').append('<div class="help-block">' + data.errors.city + '</div>'); // add the actual error message under our input
                    }

                    // handle errors for Company Address ---------------
                    if (data.errors.state) {
                        $('#state-group').addClass('has-error'); // add the error class to show red input
                        $('#state-group').append('<div class="help-block">' + data.errors.state + '</div>'); // add the actual error message under our input
                    }

                    // handle errors for Email Address ---------------
                    if (data.errors.emailAddress) {
                        $('#emailAddress-group').addClass('has-error'); // add the error class to show red input
                        $('#emailAddress-group').append('<div class="help-block">' + data.errors.emailAddress + '</div>'); // add the actual error message under our input
                    }

                    // handle errors for superhero alias ---------------
                    if (data.errors.comment) {
                        $('#comment-group').addClass('has-error'); // add the error class to show red input
                        $('#comment-group').append('<div class="help-block">' + data.errors.comment + '</div>'); // add the actual error message under our input
                    }

                } else {

                    // ALL GOOD! just show the success message!
                    $('form').append('<div class="alert alert-success">' + data.message + '</div>');

                    // usually after form submission, you'll want to redirect
                    // window.location = '/thank-you'; // redirect a user to another page

                }
            })

            // using the fail promise callback
            .fail(function(data) {

                // show any errors
                // best to remove for production
                console.log(data);
            });

        // stop the form from submitting the normal way and refreshing the page
        event.preventDefault();
    });

});
<!doctype html>
<html>
<head>
    <title>Form Master</title>
    <link rel="stylesheet" href="//netdna.bootstrapcdn.com/bootstrap/3.0.3/css/bootstrap.min.css"> <!-- load bootstrap via CDN -->

    <script src="//ajax.googleapis.com/ajax/libs/jquery/2.0.3/jquery.min.js"></script> <!-- load jquery via CDN -->
    <script src="formMaster.js"></script> <!-- load our javascript file -->
</head>
<body>
<div class="col-sm-6 col-sm-offset-3">

    <h1>Contact Form</h1>

    <!-- OUR FORM -->
    <form name="form" id="form" action="formMaster.php" method="POST">

        <!-- NAME -->
        <div id="firstName-group" class="form-group">
            <label for="firstName">First Name</label>
            <input type="text" class="form-control" name="firstName" placeholder="Henry Pym">
            <!-- errors will go here -->
        </div>

        <!-- NAME -->
        <div id="lastName-group" class="form-group">
            <label for="lastName">Last Name:</label>
            <input type="text" class="form-control" name="lastName" placeholder="Henry Pym">
            <!-- errors will go here -->
        </div>

        <!-- NAME -->
        <div id="companyName-group" class="form-group">
            <label for="companyName">Company Name:</label>
            <input type="text" class="form-control" name="companyName" placeholder="Henry Pym">
            <!-- errors will go here -->
        </div>

        <!-- NAME -->
        <div id="companyAddress-group" class="form-group">
            <label for="companyAddress">Company Address:</label>
            <input type="text" class="form-control" name="companyAddress" placeholder="Henry Pym">
            <!-- errors will go here -->
        </div>

        <!-- NAME -->
        <div id="city-group" class="form-group">
            <label for="city">City:</label>
            <input type="text" class="form-control" name="city" placeholder="Henry Pym">
            <!-- errors will go here -->
        </div>

        <div id="state-group" class="form-group">
      <label for="state">State</label>
      <select id="statea" name="state" class="form-control">
        <option selected>Choose...</option>
        <option>...</option>
      </select>
    </div>

        <!-- EMAIL ADDRESS -->
        <div id="emailAddress-group" class="form-group">
            <label for="emailAddress">Email Address:</label>
            <input type="text" class="form-control" name="emailAddress" placeholder="rudd@avengers.com">
            <!-- errors will go here -->
        </div>

        <!-- COMMENT -->
        <div id="comment-group" class="form-group">
            <label for="comment">Comment:</label>
            <input type="text" class="form-control" name="comment" placeholder="Ant Man">
            <!-- errors will go here -->
        </div>

                    <div id="recaptcha" class="form-group">
                        <div class="g-recaptcha" data-sitekey="6LfKURIUAAAAAO50vlwWZkyK_G2ywqE52NU7YO0S" data-callback="verifyRecaptchaCallback" data-expired-callback="expiredRecaptchaCallback"></div>
                        <input class="form-control d-none" data-recaptcha="true" required data-error="Please complete the Captcha">
                        <div class="help-block with-errors"></div>
                    </div>

        <button type="submit" class="btn btn-success">Submit <span class="fa fa-arrow-right"></span></button>

    </form>

</div>
</body>
</html>
PHP:

    //reCAPTCHA validation
    if (isset($_POST['g-recaptcha-response'])) {

        require('component/recaptcha/src/autoload.php');

        $recaptcha = new \ReCaptcha\ReCaptcha(SECRET_KEY, new \ReCaptcha\RequestMethod\SocketPost());

        $resp = $recaptcha->verify($_POST['g-recaptcha-response'], $_SERVER['REMOTE_ADDR']);

          if (!$resp->isSuccess()) {
                $errors = json_encode(array('type'=>'error', 'text' => 'Captcha is Required!'));
                die($output);
          }
    }
<?php

$errors         = array();      // array to hold validation errors
$data           = array();      // array to pass back data

// validate the variables ======================================================
    // if any of these variables don't exist, add an error to our $errors array

    if (empty($_POST['firstName']))
        $errors['firstName'] = 'First Name is required.';

    if (empty($_POST['lastName']))
        $errors['lastName'] = 'Last Name is required.';

    if (empty($_POST['companyName']))
        $errors['companyName'] = 'Company Name is required.';

    if (empty($_POST['companyAddress']))
        $errors['companyAddress'] = 'Company Address is required.';

    if (empty($_POST['city']))
        $errors['city'] = 'City is required.';

    if (empty($_POST['state']))
        $errors['state'] = 'State is required.';

    if (empty($_POST['emailAddress']))
        $errors['emailAddress'] = 'Email Address is required.';

    if (empty($_POST['comment']))
        $errors['comment'] = 'Comment is required.';

        //reCAPTCHA validation
        if (isset($_POST['g-recaptcha-response'])) {

            require('component/recaptcha/src/autoload.php');

            $recaptcha = new \ReCaptcha\ReCaptcha(SECRET_KEY, new \ReCaptcha\RequestMethod\SocketPost());

            $resp = $recaptcha->verify($_POST['g-recaptcha-response'], $_SERVER['REMOTE_ADDR']);

              if (!$resp->isSuccess()) {
                    $errors = json_encode(array('type'=>'error', 'text' => 'Captcha is Required!'));
                    die($output);
              }
        }


// return a response ===========================================================

    // if there are any errors in our errors array, return a success boolean of false
    if ( ! empty($errors)) {

        // if there are items in our errors array, return those errors
        $data['success'] = false;
        $data['errors']  = $errors;
    } else {

        // if there are no errors process our form, then return a message

        // DO ALL YOUR FORM PROCESSING HERE
        // THIS CAN BE WHATEVER YOU WANT TO DO (LOGIN, SAVE, UPDATE, WHATEVER)

        // show a message of success and provide a true success variable
        $data['success'] = true;
        $data['message'] = 'Success!';
    }

    // return all our data to an AJAX call
    echo json_encode($data);
// Start
$(document).ready(function() {

    // process the form
    $('form').submit(function(event) {

        $('.form-group').removeClass('has-error'); // remove the error class
        $('.help-block').remove(); // remove the error text

        // get the form data
        // there are many ways to get this data using jQuery (you can use the class or id also)
        var formData = {
            'firstName'                 : $('input[name=firstName]').val(),
            'lastName'              : $('input[name=lastName]').val(),
            'companyName'               : $('input[name=companyName]').val(),
            'companyAddress'                : $('input[name=companyAddress]').val(),
            'city'              : $('input[name=city]').val(),
            'state'                 : $('input[name=state]').val(),
            'emailAddress'          : $('input[name=emailAddress]').val(),
            'comment'   : $('input[name=comment]').val()
        };

        // process the form
        $.ajax({
            type        : 'POST', // define the type of HTTP verb we want to use (POST for our form)
            url         : 'formMaster.php', // the url where we want to POST
            data        : formData, // our data object
            dataType    : 'json', // what type of data do we expect back from the server
            encode      : true
        })
            // using the done promise callback
            .done(function(data) {

                // log data to the console so we can see
                console.log(data);

                // here we will handle errors and validation messages
                if ( ! data.success) {

                    // handle errors for name ---------------
                    if (data.errors.firstName) {
                        $('#firstName-group').addClass('has-error'); // add the error class to show red input
                        $('#firstName-group').append('<div class="help-block">' + data.errors.firstName + '</div>'); // add the actual error message under our input
                    }

                    // handle errors for name ---------------
                    if (data.errors.lastName) {
                        $('#lastName-group').addClass('has-error'); // add the error class to show red input
                        $('#lastName-group').append('<div class="help-block">' + data.errors.lastName + '</div>'); // add the actual error message under our input
                    }

                    // handle errors for name ---------------
                    if (data.errors.companyName) {
                        $('#companyName-group').addClass('has-error'); // add the error class to show red input
                        $('#companyName-group').append('<div class="help-block">' + data.errors.companyName + '</div>'); // add the actual error message under our input
                    }

                    // handle errors for Company Address ---------------
                    if (data.errors.companyAddress) {
                        $('#companyAddress-group').addClass('has-error'); // add the error class to show red input
                        $('#companyAddress-group').append('<div class="help-block">' + data.errors.companyAddress + '</div>'); // add the actual error message under our input
                    }

                    // handle errors for Company Address ---------------
                    if (data.errors.city) {
                        $('#city-group').addClass('has-error'); // add the error class to show red input
                        $('#city-group').append('<div class="help-block">' + data.errors.city + '</div>'); // add the actual error message under our input
                    }

                    // handle errors for Company Address ---------------
                    if (data.errors.state) {
                        $('#state-group').addClass('has-error'); // add the error class to show red input
                        $('#state-group').append('<div class="help-block">' + data.errors.state + '</div>'); // add the actual error message under our input
                    }

                    // handle errors for Email Address ---------------
                    if (data.errors.emailAddress) {
                        $('#emailAddress-group').addClass('has-error'); // add the error class to show red input
                        $('#emailAddress-group').append('<div class="help-block">' + data.errors.emailAddress + '</div>'); // add the actual error message under our input
                    }

                    // handle errors for superhero alias ---------------
                    if (data.errors.comment) {
                        $('#comment-group').addClass('has-error'); // add the error class to show red input
                        $('#comment-group').append('<div class="help-block">' + data.errors.comment + '</div>'); // add the actual error message under our input
                    }

                } else {

                    // ALL GOOD! just show the success message!
                    $('form').append('<div class="alert alert-success">' + data.message + '</div>');

                    // usually after form submission, you'll want to redirect
                    // window.location = '/thank-you'; // redirect a user to another page

                }
            })

            // using the fail promise callback
            .fail(function(data) {

                // show any errors
                // best to remove for production
                console.log(data);
            });

        // stop the form from submitting the normal way and refreshing the page
        event.preventDefault();
    });

});
<!doctype html>
<html>
<head>
    <title>Form Master</title>
    <link rel="stylesheet" href="//netdna.bootstrapcdn.com/bootstrap/3.0.3/css/bootstrap.min.css"> <!-- load bootstrap via CDN -->

    <script src="//ajax.googleapis.com/ajax/libs/jquery/2.0.3/jquery.min.js"></script> <!-- load jquery via CDN -->
    <script src="formMaster.js"></script> <!-- load our javascript file -->
</head>
<body>
<div class="col-sm-6 col-sm-offset-3">

    <h1>Contact Form</h1>

    <!-- OUR FORM -->
    <form name="form" id="form" action="formMaster.php" method="POST">

        <!-- NAME -->
        <div id="firstName-group" class="form-group">
            <label for="firstName">First Name</label>
            <input type="text" class="form-control" name="firstName" placeholder="Henry Pym">
            <!-- errors will go here -->
        </div>

        <!-- NAME -->
        <div id="lastName-group" class="form-group">
            <label for="lastName">Last Name:</label>
            <input type="text" class="form-control" name="lastName" placeholder="Henry Pym">
            <!-- errors will go here -->
        </div>

        <!-- NAME -->
        <div id="companyName-group" class="form-group">
            <label for="companyName">Company Name:</label>
            <input type="text" class="form-control" name="companyName" placeholder="Henry Pym">
            <!-- errors will go here -->
        </div>

        <!-- NAME -->
        <div id="companyAddress-group" class="form-group">
            <label for="companyAddress">Company Address:</label>
            <input type="text" class="form-control" name="companyAddress" placeholder="Henry Pym">
            <!-- errors will go here -->
        </div>

        <!-- NAME -->
        <div id="city-group" class="form-group">
            <label for="city">City:</label>
            <input type="text" class="form-control" name="city" placeholder="Henry Pym">
            <!-- errors will go here -->
        </div>

        <div id="state-group" class="form-group">
      <label for="state">State</label>
      <select id="statea" name="state" class="form-control">
        <option selected>Choose...</option>
        <option>...</option>
      </select>
    </div>

        <!-- EMAIL ADDRESS -->
        <div id="emailAddress-group" class="form-group">
            <label for="emailAddress">Email Address:</label>
            <input type="text" class="form-control" name="emailAddress" placeholder="rudd@avengers.com">
            <!-- errors will go here -->
        </div>

        <!-- COMMENT -->
        <div id="comment-group" class="form-group">
            <label for="comment">Comment:</label>
            <input type="text" class="form-control" name="comment" placeholder="Ant Man">
            <!-- errors will go here -->
        </div>

                    <div id="recaptcha" class="form-group">
                        <div class="g-recaptcha" data-sitekey="6LfKURIUAAAAAO50vlwWZkyK_G2ywqE52NU7YO0S" data-callback="verifyRecaptchaCallback" data-expired-callback="expiredRecaptchaCallback"></div>
                        <input class="form-control d-none" data-recaptcha="true" required data-error="Please complete the Captcha">
                        <div class="help-block with-errors"></div>
                    </div>

        <button type="submit" class="btn btn-success">Submit <span class="fa fa-arrow-right"></span></button>

    </form>

</div>
</body>
</html>

reCaptcha检查在客户端完成,浏览器连接到google reCaptcha并检查输入是否来自机器人。然后将验证码返回到浏览器。
该验证代码是“
g-recaptcha-response
”,随后在服务器端进行验证

要在服务器端执行检查,您需要在ajax调用中添加一个名为g-recaptcha-response的传统字段,并使用验证返回的值

formData
中,您需要包括
g-recaptcha-response
此传统数据字段

var formData = {
            'firstName'                 : $('input[name=firstName]').val(),
            'lastName'              : $('input[name=lastName]').val(),
            'companyName'               : $('input[name=companyName]').val(),
            'companyAddress'                : $('input[name=companyAddress]').val(),
            'city'              : $('input[name=city]').val(),
            'state'                 : $('input[name=state]').val(),
            'emailAddress'          : $('input[name=emailAddress]').val(),
            'comment'   : $('input[name=comment]').val(),
            'g-recaptcha-response' : !!! PUT THE VERIFICATION CODE HERE !!!
        };
我不确定您使用的是哪个reCaptcha版本,因此获得验证的方式会有所不同,但这里有一个链接,可以检查不同版本的不同备选方案:

编辑I

在html文件中,在
标记中添加recaptcha api:

<script src="//ajax.googleapis.com/ajax/libs/jquery/2.0.3/jquery.min.js">
<script src="https://www.google.com/recaptcha/api.js" async defer></script>
</script> <!-- load jquery via CDN -->
    <script src="formMaster.js"></script> <!-- load our javascript file -->
最后,在Javascript中,使用
recpatcha
对象获取响应,并将其添加到
ajax
调用中

var formData = {
            'firstName'                 : $('input[name=firstName]').val(),
            'lastName'              : $('input[name=lastName]').val(),
            'companyName'               : $('input[name=companyName]').val(),
            'companyAddress'                : $('input[name=companyAddress]').val(),
            'city'              : $('input[name=city]').val(),
            'state'                 : $('input[name=state]').val(),
            'emailAddress'          : $('input[name=emailAddress]').val(),
            'comment'   : $('input[name=comment]').val(),
            'g-recaptcha-response' : recaptcha.getResponse();
})

通过这些更改,您应该可以在php中获得
$\u POST['g-recaptcha-response']


之后,使用此信息按照验证步骤进行操作。

那么会是这样的:
if(空($\u POST['g-recaptcha-response'])$errors['captcha']='captcha是必需的'?1)在ajax调用中,该字段丢失,因此它将永远无法到达$\u POST。2) 在当前带有“empty”的代码中,应该得到一些未定义的索引或类似的内容。请改用isset,或者将其与array_key_组合。我使用的是Google ReCaptcha的v2,但验证码的输入值是多少
'g-recaptcha-response':$('input[name=g-recaptcha-response]')。val()
您可以添加您正在使用的html吗有关在html页面中设置g-recaptcha并将验证提交到php页面的详细信息,请参见编辑I。