How to Validate the Google reCaptcha
You should try this code: I have been using this on my site.
<script>
window.onload = function() {
var recaptcha = document.forms["contactForm"]["g-recaptcha-response"];
recaptcha.required = true;
recaptcha.oninvalid = function(e) {
alert("Please complete the captcha");
}
}
</script>
The accepted JavaScript solution above is definitely NOT the way to go in my opinion. Any bot that's not using JS (which is most of them) will simply bypass your validation and you'll get all that spam you're trying to block. Always always always validate on the server. JS validation is just a UX first step.
Anyway, there are multiple solutions, but here's what worked for me in Magento 1.9 after many hours of research. This originally built upon Mike's answer above, but swaps out file_get_contents for cURL since the previous function will usually give you http wrapper errors depending on your server config.
Create your own module by Creating a folder /app/code/local/YourVendorName/ValidateCaptcha/
In your new ValidateCaptcha folder, add a Model folder with a Customer.php file. This will be used to override the core Customer.php file provided by Magento.
Copy & Paste this code:
<?php
class YourVendorName_ValidateCaptcha_Model_Customer extends Mage_Customer_Model_Customer {
/**
* Validate customer attribute values.
*
* @return bool
*/
public function validate()
{
// This section is from the core file
$errors = array();
if (!Zend_Validate::is( trim($this->getFirstname()) , 'NotEmpty')) {
$errors[] = Mage::helper('customer')->__('The first name cannot be empty.');
}
if (!Zend_Validate::is( trim($this->getLastname()) , 'NotEmpty')) {
$errors[] = Mage::helper('customer')->__('The last name cannot be empty.');
}
if (!Zend_Validate::is($this->getEmail(), 'EmailAddress')) {
$errors[] = Mage::helper('customer')->__('Invalid email address "%s".', $this->getEmail());
}
$password = $this->getPassword();
if (!$this->getId() && !Zend_Validate::is($password , 'NotEmpty')) {
$errors[] = Mage::helper('customer')->__('The password cannot be empty.');
}
if (strlen($password) && !Zend_Validate::is($password, 'StringLength', array(6))) {
$errors[] = Mage::helper('customer')->__('The minimum password length is %s', 6);
}
$confirmation = $this->getPasswordConfirmation();
if ($password != $confirmation) {
$errors[] = Mage::helper('customer')->__('Please make sure your passwords match.');
}
$entityType = Mage::getSingleton('eav/config')->getEntityType('customer');
$attribute = Mage::getModel('customer/attribute')->loadByCode($entityType, 'dob');
if ($attribute->getIsRequired() && '' == trim($this->getDob())) {
$errors[] = Mage::helper('customer')->__('The Date of Birth is required.');
}
$attribute = Mage::getModel('customer/attribute')->loadByCode($entityType, 'taxvat');
if ($attribute->getIsRequired() && '' == trim($this->getTaxvat())) {
$errors[] = Mage::helper('customer')->__('The TAX/VAT number is required.');
}
$attribute = Mage::getModel('customer/attribute')->loadByCode($entityType, 'gender');
if ($attribute->getIsRequired() && '' == trim($this->getGender())) {
$errors[] = Mage::helper('customer')->__('Gender is required.');
}
// additional reCAPTCHA validation
// this should actually be in it's own function, but I've added
// it here for simplicity
// Magento uses this method for a few different requests, so make
// sure it's limited only to the 'createpost' action
$action = Mage::app()->getRequest()->getActionName();
if ( $action == 'createpost' ) { // restrict to the registration page only
$captcha = Mage::app()->getRequest()->getPost('g-recaptcha-response', 1);
if ( $captcha == '' ) {
// if the field is empty, add an error which will be
// displayed at the top of the page
$errors[] = Mage::helper('customer')->__('Please check the reCAPTCHA field to continue.');
} else {
$secret = 'your-secret-key-goes-here';
$url = 'https://www.google.com/recaptcha/api/siteverify?secret=' . $secret . '&response=' . $captcha . '&remoteip=' . $_SERVER["REMOTE_ADDR"];
$ch = curl_init();
// if you're testing this locally, you'll likely need to
// add your own CURLOPT_CAINFO parameter or you'll get
// SSL errors
curl_setopt( $ch, CURLOPT_URL, $url );
curl_setopt( $ch, CURLOPT_RETURNTRANSFER, 1);
$response = curl_exec( $ch );
$result = json_decode( $response, true );
if ( trim( $result['success'] ) != true ) {
// Add reCAPTCHA error
// This will be shown at the top of the registration page
$errors[] = Mage::helper('customer')->__('reCAPTCHA unable to verify.');
}
}
}
// now return the errors with your reCAPTCHA validation as well
if (empty($errors)) {
return true;
}
return $errors;
}
}
Now add an etc folder to your module and create a config.xml with the following:
<?xml version="1.0"?>
<config>
<modules>
<YourVendorName_ValidateCaptcha>
<version>1.0</version>
</YourVendorName_ValidateCaptcha>
</modules>
<global>
<models>
<customer>
<rewrite>
<customer>YourVendorName_ValidateCaptcha_Model_Customer</customer>
</rewrite>
</customer>
</models>
</global>
</config>
Next you'll need to add the JS to your theme head. Under app/design/frontend/default/YOURTHEME/template/page/html/head.phtml add this right at the end. If you don't have this file, copy it from the base files. Don't overwrite base files, though. Always make your own!
<?php
/* reCAPTCHA */
if ( strpos( Mage::helper('core/url')->getCurrentUrl(), 'account/create') != false ) { ?>
<script src="https://www.google.com/recaptcha/api.js" async defer></script>
<?php } ?>
Now in app/design/frontend/default/YOURTHEME/template/persistent/customer/form/register.phtml add this right before the button-set div near the bottom:
<div class="g-recaptcha" data-sitekey="your-site-key-goes-here"></div>
<span id="captcha-required" style='display:none; color:#ff0000'><?php echo $this->__('Please Fill Recaptcha To Continue'); ?></span>
Almost done! Now just register your new module by creating a app/etc/modules/YourVendorName/ValidateCaptcha.xml with the following:
<?xml version="1.0"?>
<config>
<modules>
<YourVendorName_ValidateCaptcha>
<active>true</active>
<codePool>local</codePool>
</YourVendorName_ValidateCaptcha>
</modules>
</config>
Replace YourVendorName throughout with whatever you'd like. Your final structure should be something like:
- app
- code
- local
- YourVendorName
- ValidateCaptcha
- etc
config.xml
- Model
Customer.php
- design
- frontend
- default
- YOURTHEME
- template
- customer
- form
register.phtml
- page
- html
head.phtml
- persistent
- customer
- form
register.phtml
- etc
- modules
YourVendorName_ValidateCaptcha.xml
This script use for validation google reCaptcha like a default validation of magento. please use it.
<form name="freeeventForm" id="freeeventForm">
<div id="RecaptchaField"></div>
<input type="hidden" class="validate-reCAPTCHA">
</form>
<script src="https://www.google.com/recaptcha/api.js?onload=CaptchaCallback&render=explicit" async defer></script>
<script type="text/javascript">
//< ![CDATA[
var CaptchaCallback = function() {
grecaptcha.render('RecaptchaField', {'sitekey' : '6LeuiDwUAAAAALByt-xxxxxxxxxxx-xUsZHFkeEP'});
};
var customForm = new VarienForm('freeeventForm');
Validation.add('validate-reCAPTCHA','reCAPTCHA is mandatory',function(){
var response = grecaptcha.getResponse();
if (response.length === 0) {
return false;
}
return true;
});
//]]>
</script>