首页 文章

使用jQuery ajax进行隐形ReCaptcha

提问于
浏览
9

我正在尝试使用jQuery和"ajax"请求在表单中实现最新的ReCaptcha(aka "invisible" ReCaptcha) .
ReCaptcha文档:https://developers.google.com/recaptcha/docs/invisible

我的表格:

<form id="myForm" >
    <input type="email" name="email" />
<input type="password" name="password" />
<!--<input type="submit" value="log in" />--> <button class="g-recaptcha" data-sitekey="6LdK..." data-callback="onSubmit">log in</button> </form> <div id="status"></div>

我的javascript(jQuery):

<script>

    function onSubmit(token){
        document.getElementById("myForm").submit();
    }

    $(document).ready(function(){

        $("#myForm").submit(function(event){
            event.preventDefault();
            var datas = $("#myForm").serialize();
            $.ajax({
                type: "POST",
                url: "test.php",
                data: datas,
                dataType: "json",
                    beforeSend: function(){
                        $("#status").html("logging in...");
                    },
                    success: function(response){
                        $("#status").html(response.text);
                        if(response.type=="success"){
                            window.location.replace("/myaccount");
                        }
                    },
                    error: function(){
                        $("#status").html("Failed.");
                    }
            });
        });

    });
</script>

ReCaptcha需要设置"data-callback",我不知道如何绑定我已经存在的".submit(function(event)"函数 .
我的"onSubmit()"技巧不起作用,它忽略"ajax"并刷新页面 .

如何在"datas"变量中发送"g-recaptcha-response"值以将其发送到test.php?

2 回答

  • 2
    <script defer>              
    function onSubmit(token) {                      
        var f = $("#myForm");
    
        $.ajax({
            type: "POST",
            url: "test.php",
            data: f.serialize(),
            dataType: "json",
            beforeSend: function(){
                $("#status").html("logging in...");
            },
            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>
    

    在test.php中,您需要验证服务器端的验证码:

    <?php
    if(isset($_POST['g-recaptcha-response'])) {
        $result = json_decode(file_get_contents('https://www.google.com/recaptcha/api/siteverify?secret=[YOUR_SECRET_KEY]&response=$_POST["g-recaptcha-response"]&remoteip=$_SERVER["REMOTE_ADDR"]'), TRUE);
    
        if($result['success'] == 1) {
            // Captcha ok
        } else {
            // Captcha failed
        }
    }
    ?>
    
  • 9

    所以这里是我在Invisible reCAPTCHA的文档中进一步挖掘之后如何解决它,并且明显学习了一些jQuery,因为我不熟悉JS(很酷的东西):

    我的头标记有javascript(和一些css删除丑陋的Google徽章):

    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
    <script src="https://www.google.com/recaptcha/api.js?onload=onloadCallback&render=explicit&hl=fr" async defer></script>
    
    <style>
        .grecaptcha-badge{
            display:none;
        }
    </style>
    
    <script>
        var onloadCallback = function(){
            grecaptcha.render("emplacementRecaptcha",{
                "sitekey": "YOUR_RECAPTCHA_SITEKEY_HERE",
                "badge": "inline",
                "type": "image",
                "size": "invisible",
                "callback": onSubmit
            });
        };
        var onSubmit = function(token){
            var userEmail = $("#userEmail").val();
            var userPassword = $("#userPassword").val();
            var userTfaOtp = $("#userTfaOtp").val();
            $.ajax({
                type: "POST",
                url: location.href,
                data:{
                        userEmail: userEmail,
                        userPassword: userPassword,
                        userTfaOtp: userTfaOtp,
                        userJetonRecaptcha: token
                    },
                dataType: "json",
                    beforeSend: function(){
                        $("#statutConnexion").html("Traitement de votre requête d'authentification en cours...");
                    },
                    success: function(response){
                        $("#statutConnexion").html(response.Message);
                        if(response.Victoire){
                            $("#formulaireConnexion").slideUp();
                            window.location.replace("/compte");
                        }
                        else{
                            grecaptcha.reset();
                        }
                    },
                    error: function(){
                        $("#statutConnexion").html("La communication avec le système d'authentification n'a pas pu être établie. Veuillez réessayer.");
                        grecaptcha.reset();
                    }
            });
        };
        function validate(event){
            event.preventDefault();
            $("#statutConnexion").html("Validation de votre épreuve CAPTCHA en cours...");
            grecaptcha.execute();
        }
        function onload(){
            var element = document.getElementById("boutonConnexion");
            element.onclick = validate;
        }
    </script>
    

    HTML:

    <div id="formulaireConnexion">
        <input type="email" name="userEmail" id="userEmail" placeholder="Courriel" title="Courriel" required="required" />
    <input type="password" name="userPassword" id="userPassword" placeholder="Mot de passe" title="Mot de passe" required="required" />
    <input type="text" name="userTfaOtp" id="userTfaOtp" placeholder="Double authentification (optionnelle)" autocomplete="off" pattern="[0-9]{6}" title="Six caractères numériques" maxlength="6" />
    <div id="emplacementRecaptcha"></div> <button id="boutonConnexion">Connexion</button> </div> <div id="statutConnexion"></div> <script>onload();</script>

    如果你需要整个PHP,请告诉我,因为它超出了这个问题的范围 . 您可能需要在JS中更改“url:location.href”,因为在我的情况下,呈现HTML表单和JS以及处理POST变量的脚本是相同的(不是很好,测试目的) . 基本上我只是验证POST变量,然后最终返回一个json,如:

    $jsonVictoire = true; // boolean
    $jsonMessage = 'anything you want to tell your visitor'; // string
    
    $return = 
        json_encode(
            array(
                'Victoire'=>$jsonVictoire,
                'Message'=>$jsonMessage
            )
        );
    die($return);
    

相关问题