Magento – Implement Google Invisible reCaptcha in custom Ajax Form

magento-1.9

I have a custom form on the product page and this form is same as Contact Us form. I have already implemented Google invisible reCaptcha code on this page.

Google invisible reCaptcha is implemented along with the Google conversion code. While when we are submitting the form it is not throwing any errors and Form is submitted successfully Issue is we are getting spam emails and it seems user bypass reCaptcha.

Also when we are generating an analytic report then getting an error.

"We detected that your site is verifying reCAPTCHA passed solutions less than 50% of the time. This could indicate a problem with your integration with reCAPTCHA. Please see our developer site for more information."

Google invisible reCaptcha code is implemented with below code

 <button id='recaptcha' class="g-recaptcha" data-sitekey="site-key here" data-callback="doRecaptcha" data-size="invisible"><?php echo $this->__('Submit Form') ;?></button>



var formId = 'customform';
var myForm = new VarienForm(formId, true);
var postUrl = '<?php echo $this->getUrl("submit url") ?>';

new Event.observe(formId, 'submit', function(e){    
    e.stop();
    validateFunction();
});

function validateFunction(){
     if (myForm.validator.validate()) {
        grecaptcha.execute();
    }
}   


function doRecaptcha(token) {
        conversionCode();
    }


function conversionCode(){ 
        gtag('event', 'conversion', {
              'send_to': 'hdasdhasdasdklkada',
              'event_callback': ajaxCall()
            });
    }

function ajaxCall() {
   custom code here
}

is anybody implemented this before? Please share your ideas so that I can implement it properly.

Best Answer

I have implemented it recently. But I use it like that:

<div class="g-recaptcha" data-sitekey="MY-RECAPTCHA-KEY"></div>

For validation I added something like this in jQuery:

    jQuery('#form').on('submit', function (e) {
        var response = grecaptcha.getResponse();
        if (response.length == 0) {
            e.preventDefault();
            jQuery('.recaptcha.validation-advice').show();
        }
        else {
            jQuery('.recaptcha.validation-advice').hide();
        }
    });

where validation-advice is an element inside a form that I created. Simple, and it is working - if your visitors have javascript enabled in browser.