Previously, you read how to add Google reCAPTCHA to Magento 2.
Today, I’ve come up with a similar solution for Magento 1.
Captcha, i.e., Completely Automated Public Turing test to tell Computers and Humans Apart, is a service by Google that prevents the store from spam and bots. Implementing Google reCAPTCHA v2 helps to identify if a visitor in your site is a human or a bot.
As Magento, by default, does not offer a reliable solution for security against spams, merchants have to rely on 3rd party solutions and the best choice is Google-developed anti-spam reCAPTCHA that displays the “I’m not a robot” checkbox.
To add Google reCAPTCHA to Magento, you need to follow the given method.
Additionally, check these steps prior to implementing the programmatic method:
- Register for the public and secret key pair Magento store’s domain.
- Ensure if the reCAPTCHA authentication works for the subdomains as well to avoid any error.
- Refer to Google reCAPTCHA documentation.
Method to Add Google reCAPTCHA to Magento :
1. Add the below script to any head or where you want to use google recaptcha
<script src="https://www.google.com/recaptcha/api.js" type="text/javascript" xml="space"></script>
2. Add captcha code to phtml or block/page where you want to add v2 google recaptcha in the form
<div class="form-group required"> //change class as per themes
<div class="g-recaptcha required" id="recaptcha"
data-sitekey="your-site-key">
</div>
<div style="display:none" id="error-msg">
<span><?php echo __('This is a required field.') ?></span>
</div>
</div>
3. If the captcha does not validate then add below code
<script>
function checkCaptcha() {
if ((jQuery('#g-recaptcha-response').val()) === '') {
jQuery('#error-msg').css('display', 'block');
jQuery('#error-msg').css('color', '#df280a');
jQuery('#error-msg').css('font-size', 13);
return false;
}
else {
jQuery('#error-msg').css('display', 'none');
}
}
</script>
In any form, add onSubmit event like :
<form class="form contact" action="<?php echo $block->getFormAction(); ?>" id="contact-form" method="post" data-hasrequired="<?php echo __('* Required Fields') ?>" data-mage-init='{"validation":{}}' onSubmit="return checkCaptcha() ;">
That’s it.
Stay Secure ️