web-dev-qa-db-fra.com

Comment ajouter plusieurs recaptcha invisible dans une seule page?

J'ai ajouté deux div recaptcha invisibles, mais lorsque j'ai vu le code dans l'élément inspect, un seul recaptcha invisible a été ajouté sur une seule page . Mon code est le suivant:

 <div id="captcha1" class="g-recaptcha"
      data-sitekey="your_site_key"
      data-callback="onSubmit"
      data-size="invisible"></div>
<div id="captcha2" class="g-recaptcha"
      data-sitekey="your_site_key"
      data-callback="onSubmit"
     ></div>

Obtenir la référence de Invoquer par programme recaptcha

Pouvez-vous m'aider qu'est-ce que je fais mal?

7
Versha Gupta

Ci-dessous, une solution plus fiable à Peter et Alessandro répond lors de l'imbrication d'éléments.

<script>
$(".g-recaptcha").each(function() {
    var object = $(this);
    grecaptcha.render(object.attr("id"), {
        "sitekey" : "6LdwRC0UAAAAAK0hjA8O4y1tViGPk9ypXEH_LU22",
        "callback" : function(token) {
            object.parents('form').find(".g-recaptcha-response").val(token);
            object.parents('form').submit();
        }
    });
});
</script>

<form>
    <input type="text" name="example"/>
    <button id="captcha1" class="g-recaptcha">submit form 1</button>
</form>

<form>
    <input type="text" name="example"/>
    <button id="captcha2" class="g-recaptcha">submit form 2</button>
</form>

<script src='https://www.google.com/recaptcha/api.js?onload=onloadCallback&render=explicit' async defer></script>
10
user1788978

Avait le même problème. Après un peu de perplexité, je me suis mis au travail.

A utilisé l'idée fournie par Alessandro et l'a faite pour que le formulaire soit automatiquement soumis en cas de succès.

<script type="text/javascript">
    var onloadCallback = function() {
        $(".g-recaptcha").each(function() {
            var el = $(this);
            grecaptcha.render($(el).attr("id"), {
                "sitekey" : SITE_KEY,
                "callback" : function(token) {
                    $(el).parent().find(".g-recaptcha-response").val(token);
                    $(el).parent().submit();
                }
            });
        });
    };
</script>

<script src="https://www.google.com/recaptcha/api.js?onload=onloadCallback&render=explicit" async defer></script>
3
Peter Bode

Vous devez faire un rendu explicite sur chaque bouton de soumission

<form>
    <button id="captcha1" class="g-recaptcha invisible-recaptcha">submit form 1</button>
</form>

<form>
    <button id="captcha2" class="g-recaptcha invisible-recaptcha">submit form 2</button>
</form>

<script>
    function verifyCaptcha(token){
        console.log('success!');
    };

    var onloadCallback = function() {
        $( ".invisible-recaptcha" ).each(function() {
            grecaptcha.render($( this ).attr('id'), {
                'sitekey' : $key,
                'callback' : verifyCaptcha
            });
        });
    };
</script>

<script src='https://www.google.com/recaptcha/api.js?onload=onloadCallback&render=explicit' async defer></script>
2
Alessandro

Vous pouvez utiliser invisible recaptcha. Sur votre bouton, utilisez une balise telle que "formname = 'rcaptchaformname" "pour spécifier le formulaire à soumettre et masquer une entrée de formulaire de soumission. 

Cela vous permet de conserver la validation du formulaire html5 intacte, une seule interface recaptcha, mais plusieurs interfaces de bouton. Capturez simplement la valeur d'entrée "captcha" pour la clé de jeton générée par recaptcha.

<script src="https://www.google.com/recaptcha/api.js" async defer ></script>

<div class="g-recaptcha" data-sitekey="yours" data-callback="onSubmit" data-size="invisible"></div>
<script>

$('button').on('click', function () { formname = '#'+$(this).attr('formname');
    if ( $(formname)[0].checkValidity() == true) { grecaptcha.execute(); }
    else { $(formname).find('input[type="submit"]').click() }
    });

var onSubmit = function(token) {
    $(formname).append("<input type='hidden' name='captcha' value='"+token+"' />");
    $(formname).find('input[type="submit"]').click()
    };
</script>
1
eatmeimadanish

Multiple Invisible reCaptcha V2 sur une seule page de manière dynamique

Code Github: https://github.com/prathameshsawant7/multiple-invisible-recaptcha

Étape 1>

Ajouter ci-dessous 2 bibliothèque Js sur la page

<!--  reCaptcha Library -->
<script type="text/javascript" src="https://www.google.com/recaptcha/api.js?render=explicit"></script>

<!--  Customized Init for invisible reCaptcha  -->
<script src="js/init_recaptcha.js" async defer></script>

Étape 2>

Ajouter ci-dessous div dans les formes respectives.

<div id="recaptcha-form-1" style="display:none;"></div> <!--for Form 1-->
<div id="recaptcha-form-2" style="display:none;"></div> <!--for Form 2-->
<div id="recaptcha-form-3" style="display:none;"></div> <!--for Form 3-->

Étape 3> 

Créez init_recaptcha.js

  • Étape 1 - Initialiser la clé de site et le widget reCaptcha, par exemple: widget_1 pour le formulaire 1
  • Étape 2 - Dans la fonction init, ajoutez du code pour créer une action de rappel de soumission de formulaire.
  • Étape 3 - Appelez la fonction renderInvisibleReCaptcha en passant l'ID reCaptcha et la réponse createCallbackFn.

    "use strict";
    
    var PS = PS || {};
    var widget_1;var widget_2;var widget_3;
    var recaptcha_site_key = 'RECAPTCHA_SITE_KEY';
    
    if( typeof PS.RECAPTCHA === 'undefined' ) {
        (function (a, $) {
            var retryTime = 300;
            var x = {
                init: function(){
                    if(typeof grecaptcha != 'undefined'){
    
                        //For Form 1 Initialization
                        if($('#form1 #recaptcha-form-1').length > 0){
                            var callbackFn = {
                                action : function(){
                                    saveData('1'); //Here Callback Function
                                }
                            }
                            /*--- 'recaptcha-form-1' - reCaptcha div ID | 'form1' - Form ID ---*/
                            widget_1 = x.renderInvisibleReCaptcha('recaptcha-form-1',x.createCallbackFn(widget_1,'form1',callbackFn));
                        }
    
                                               //For Form 2 Initialization
                        if($('#form2 #recaptcha-form-2').length > 0){
                            var callbackFn = {
                                action : function(){
                                    saveData('2'); //Here Callback Function
                                }
                            }
                            /*--- 'recaptcha-form-2' - reCaptcha div ID | 'form2' - Form ID ---*/
                            widget_2 = x.renderInvisibleReCaptcha('recaptcha-form-2',x.createCallbackFn(widget_2,'form2',callbackFn));
                        }
    
                                                //For Form 3 Initialization
                        if($('#form3 #recaptcha-form-3').length > 0){
                            var callbackFn = {
                                action : function(){
                                    saveData('3'); //Here Callback Function
                                }
                            }
                            /*--- 'recaptcha-form-3' - reCaptcha div ID | 'form3' - Form ID ---*/
                            widget_3 = x.renderInvisibleReCaptcha('recaptcha-form-3',x.createCallbackFn(widget_3,'form3',callbackFn));
                        }
    
                    }else{
                        setTimeout(function(){ x.init();} , retryTime);
                    }
                },
                renderInvisibleReCaptcha: function(recaptchaID,callbackFunction){
                        return grecaptcha.render(recaptchaID, {
                                'sitekey'   : recaptcha_site_key,
                                "theme" : "light",
                                'size'      : 'invisible',
                                'badge' : 'inline',
                                'callback'  : callbackFunction
                            });
                },
                createCallbackFn: function (widget,formID,callbackFn) {
                    return function(token) {
                        $('#'+formID+' .g-recaptcha-response').val(token);
                        if($.trim(token) == ''){
                            grecaptcha.reset(widget);
                        }else{
                            callbackFn.action();
                        }
                    }
                }
            }
            a.RECAPTCHA = x;
        })( PS, $ );
    }
    
    $(window).load(function(){
        PS.RECAPTCHA.init();
    });
    

Étape 4> Modifications de la validation de formulaire JS - 

/* Execute respective Widget on form submit after form Validations  */
function formSubmit(form){
    var text = $.trim($('#text'+form).val());
    if(text != ''){
        switch(form){
            case '1' : grecaptcha.execute(widget_1); break;
            case '2' : grecaptcha.execute(widget_2); break;
            case '3' : grecaptcha.execute(widget_3); break;
        }
    }
}

Étape 5> Validez reCaptcha à partir du côté serveur - 

<?php
    define('RECAPTCHA_SECRET_KEY','KEY');
    /**
    *  @Desc:   To Validate invisible recaptcha from server-side
    *  @Param:  g-recaptcha-response value
    *  @Return: True/False
    **/
    if(!function_exists('check_recaptcha')){
        function check_recaptcha($recaptcha_response){
            $test = array ('secret' => RECAPTCHA_SECRET_KEY,'remoteip' => $_SERVER["REMOTE_ADDR"],'response' => $recaptcha_response);
            foreach ($test as $key => $value) {
                $req .= $key . '=' . urlencode(stripslashes($value)) . '&';
            }
            $req=substr($req, 0, strlen($req)-1);
            $path = 'https://www.google.com/recaptcha/api/siteverify?';
            $response = file_get_contents($path . $req);
            $responseData = json_decode($response);
            if($responseData->success){
                return true;            
            }else{
                return false;
            }
        }
    }

    // Validate reCaptcha
    if (isset($_SERVER['REQUEST_METHOD']) && $_SERVER['REQUEST_METHOD'] == "POST" && !empty($_POST)) {
        $checkCapcha = false;
            $recaptcha = $_POST['g-recaptcha-response'];
                $checkCapcha = check_recaptcha($recaptcha);
                if($checkCapcha){
                    echo $_POST['textmsg']; exit;
                    /** Perform Actions Here (Add,Update,Delete etc) 
**/
                }
    else{
            echo “reCaptcha Error”;
        }
    }
    echo "failed";exit;
?>

Étape 6> Réinitialiser le widget après l'appel du serveur - 

// saveData will be automatically get called on grecaptacha.execute 
function saveData(form){
$.ajax( {
    type: 'POST',
    url:  $("#form"+form).attr( 'action' ),
    data: $("#form"+form).serialize(),
    success: function( response ) {
                switch(form){
            case '1' : grecaptcha.reset(widget_1); break;
            case '2' : grecaptcha.reset(widget_2); break;
            case '3' : grecaptcha.reset(widget_3); break;
            }
        }
    } );
}
1