10

I have added the google recaptcha in contact us form but value is also submitting without captcha. I have used in my contact page following codes for captcha:

 <div class="g-recaptcha" data-sitekey="XXXXXXXXXX"></div> 
 <script src='https://www.google.com/recaptcha/api.js'></script>

These two code i have used. please tell me how can i validate captcha.

3

6 Answers 6

9

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> 
36
  • will it work on built in contact us page in the theme...?? Jul 13, 2017 at 9:44
  • yes.. it will..let me know if it worked
    – NID
    Jul 13, 2017 at 9:46
  • 2
    then replace form-validate with contactForm
    – NID
    Jul 13, 2017 at 9:50
  • 1
    you could just install an extension for Google Analytics. magentocommerce.com/magento-connect/… . Google does a great job tracking all this stuff already. If you want something more robust later on, there are paid extensions that do more.
    – NID
    Jul 17, 2017 at 3:46
  • 1
    may be this will help u .. magento.stackexchange.com/questions/37363/…
    – NID
    Jul 17, 2017 at 6:27
7

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>
4
  • Thank you so much, this is the right answer for validating reCaptcha on magento using prototype/validate.js. Working like a charm! Oct 31, 2018 at 17:21
  • This should be the accepted answer, successfully adapted for my purposes
    – ajmedway
    Apr 25, 2019 at 13:02
  • same here. Thanks May 16, 2019 at 13:41
  • I want to use this in my billing.phtml file, can you please suggest me I am using this code but not validating recaptcha. ` <script> window.onload = function() { //var recaptcha = document.forms["co-billing-form"]["g-recaptcha-response"]; var recaptcha = jQuery('.g-recaptcha-response').val(); recaptcha.required = true; recaptcha.oninvalid = function(e) { alert("Please complete the captcha"); return false; } } </script>` May 24, 2019 at 8:20
7

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
6

I used recaptcha in contact form..

<form action="<?php echo Mage::getUrl('mcrecaptcha/index/save'); ?>" id="contactForm" method="post" onSubmit="return checkcaptcha() ;">
    <ul class="form-list">
            <li class="fields">
                <div class="field">
                    <div class="input-box">
                        <input placeholder="Name" name="name" id="name" title="<?php echo Mage::helper('contacts')->__('Name') ?>" value="<?php echo $this->escapeHtml($this->helper('contacts')->getUserName()) ?>" class="input-text required-entry" type="text" />
                    </div>
                </div>
                <div class="field">
                    <div class="input-box">
                        <input placeholder="Email" name="email" id="email" title="<?php echo Mage::helper('contacts')->__('Email') ?>" value="<?php echo $this->escapeHtml($this->helper('contacts')->getUserEmail()) ?>" class="input-text required-entry validate-email contact_us_margin_top" type="text" />
                    </div>
                </div>
            </li>
            <li>
                <div class="input-box">
                    <input placeholder="Telephone" name="telephone" id="telephone" title="<?php echo Mage::helper('contacts')->__('Telephone') ?>" value="" class="input-text contact_us_margin_top" type="text" />
                </div>
            </li>
            <li class="wide">
                <div class="input-box">
                    <textarea placeholder="Comment" name="comment" id="comment" title="<?php echo Mage::helper('contacts')->__('Comment') ?>" class="required-entry input-text contact_us_margin_top" cols="5" rows="3" style="width:100%;"></textarea>
                </div>
            </li>
               <li id="rcode">  
                        <div class="captcha">
                                <div class="g-recaptcha contact_us_margin_top" data-sitekey="6Ldi8xsUAAAAAHsK15YxKsdhIn6lGk-RUIk222-f"> </div>
                        </div>
                        <div class="buttons-set contact_us_margin_top">
                            <input type="text" name="hideit" id="hideit" value="" style="display:none !important;" />
                            <button type="submit" title="<?php echo Mage::helper('contacts')->__('Submit') ?>" class="button" onClick="_gaq.push(['_trackEvent', 'Submit', 'contacts click','Contact Us'])"><span><span><?php echo Mage::helper('contacts')->__('Submit') ?></span></span></button>
                        </div>
                        <span class='captcha-error'><?php echo Mage::helper('contacts')->__('Please check the the captcha form.') ?></span>
                </li>      
        </ul>
</form>

<script>
function checkcaptcha()
{
    if((jQuery('#g-recaptcha-response').val())=='')
    {
        jQuery('.captcha-error').css('display','block');
        return false;
    }
    else
    {
        jQuery('.captcha-error').css('display','none');
    }

}
</script>
5
  • i have implemented the captcha code in built contact form of the theme.... will you will please tell me accordingly my theme. i am beginner in magento so please help me Jul 13, 2017 at 9:49
  • i implement this code in built in contact form Jul 13, 2017 at 10:04
  • you just have to implement this code in your form and change only data-sitekey Jul 13, 2017 at 10:04
  • Please Accept my answer if You Getting your answer Jul 13, 2017 at 10:45
  • yeah......... will you please look for answer of this question magento.stackexchange.com/questions/183456/… Jul 13, 2017 at 11:07
3

To validate captcha, create a save controller for saving your form values and also the validation.

namespace Mike\SampleModule\Controller;

class Save extends \Magento\Framework\App\Action\Action
{
/**
* @var Google reCaptcha Options
*/
private static $_siteVerifyUrl = "https://www.google.com/recaptcha/api/siteverify?";
private $_secret;
private static $_version = "php_1.0";
/**
* Save Form Data
*
* @return array
*/
public function execute()
{
$captcha = $this->getRequest()->getParam('g-recaptcha-response');
$secret = "<--your secret key-->"; //Replace with your secret key
$response = null;
$path = self::$_siteVerifyUrl;
$dataC = array (
'secret' => $secret,
'remoteip' => $_SERVER["REMOTE_ADDR"],
'v' => self::$_version,
'response' => $captcha
);
$req = "";
foreach ($dataC as $key => $value) {
     $req .= $key . '=' . urlencode(stripslashes($value)) . '&';
}
// Cut the last '&'
$req = substr($req, 0, strlen($req)-1);
$response = file_get_contents($path . $req);
$answers = json_decode($response, true);
if(trim($answers ['success']) == true) {
    // Captcha Validated
    // Save Form Data
}else{
    // Display Captcha Error
}
}
}

Make sure you have replaced the site key and secret key in the above sample codes.

1
  • How do I link my form to this file? The form goes to action="<?php echo $this->getPostActionUrl() ?>" with a POST method.
    – Peanuts
    Nov 4, 2017 at 17:22
1

NID,

Your reCaptcha script snippit looks like it will work but clarify is it entered into the Magento's source head.phtml ? (or the form.phtml ?) to be placed Right below outside of Magento default pre PHP in green type because its a .

Question when entering especially php is it regular practice to enter it after that immediate php comments section that Magento places in the top for most of their template source pages like this example below?

Magento Disclaimer code here in php tags. PLACE THE RECAPTCHA HERE snippit script here ?

Also what makes this reCaptcha response verification code in this video below more catered for Magento's structure of methods: This tutorial uses on the first line the $reCaptcha = $_POST line ?

Last Question alternative: What if i use the php version to do this reCaptcha response verification would php code snippit be entered after the top magento default template green comments section of php like this

Some code i dont want messages appearing on front end because default contactForm already gives its red alerts if user doesnt enter all info it will say below each field, I just want to get reCaptcha to work for this contactForm. But in a way that I will understand for future use too. Your way is created by yourself as a developer or programmer?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.