PHP Magento Tips

Add Google reCAPTCHA on Contact US Page in Magento

Rate this posting:
{[['']]}

In Previous post, you found "How to Add Magento Default Captcha on Default Contact us page in Magento".

But in this post, you will learn "How to Add Google reCAPTCHA on Contact US Page in Magento".

Before Starting to build module for that, you must need Google reCAPTCHA Site key (Public key) and Secret key (Private key), Which you can get easily from Google reCaptcha site.

Step 1: Create Module Initialization file. Create file in app/etc/modules/Mycompany_Contactsrecaptcha.xml and add below code in it.

<?xml version="1.0" encoding="UTF-8"?>
<config>
 <modules>
  <Mycompany_Contactsrecaptcha>
   <active>true</active>
   <codePool>local</codePool>
   <depends>
                <Mage_Contacts/>
            </depends>
  </Mycompany_Contactsrecaptcha>
 </modules>
</config>

Step 2: Create Module's Config and System.xml file.
a:) Create file in app/code/local/Mycompany/Contactsrecaptcha/etc/config.xml and add below code in it.

<?xml version="1.0" encoding="UTF-8"?>
<config>
    <modules>
        <Mycompany_Contactsrecaptcha>
            <version>1.0.0</version>            
        </Mycompany_Contactsrecaptcha>
    </modules>

    <global>
        <models>
            <mycompany_contactsrecaptcha>
                <class>Mycompany_Contactsrecaptcha_Model</class>
            </mycompany_contactsrecaptcha>
        </models>
    </global>

    <frontend>
        <routers>
            <contacts>
                <args>
                    <modules>
                        <mycompany_contactsrecaptcha before="Mage_Customer">Mycompany_Contactsrecaptcha</mycompany_contactsrecaptcha>
                    </modules>
                </args>
            </contacts>
        </routers>
        <layout>
            <updates>
                <mycompany_contactsrecaptcha module="Mycompany_Contactsrecaptcha">
                    <file>contactsrecaptcha.xml</file>
                </mycompany_contactsrecaptcha>
            </updates>
        </layout>
    </frontend>
</config>

b:) Create System.xml file. Create file in app/code/local/Mycompany/Contactsrecaptcha/etc/system.xml and add below code in it.

<?xml version="1.0" encoding="UTF-8"?>

<config>

    <sections>

        <contacts>

            <groups>

                <mycompany_contactsrecaptcha translate="label">

                    <label>Contacts Form Captcha</label>

                    <frontend_type>text</frontend_type>

                    <sort_order>100</sort_order>

                    <show_in_default>1</show_in_default>

                    <show_in_website>1</show_in_website>

                    <show_in_store>1</show_in_store>

                    <fields>

                        <enabled translate="label">

                            <label>Enable Captcha</label>

                            <frontend_type>select</frontend_type>

                            <source_model>adminhtml/system_config_source_yesno</source_model>

                            <backend_model>contacts/system_config_backend_links</backend_model>

                            <sort_order>10</sort_order>

                            <show_in_default>1</show_in_default>

                            <show_in_website>1</show_in_website>

                            <show_in_store>1</show_in_store>

                        </enabled>

                        <public_key translate="label">

                            <label>Site Key</label>

                            <comment><![CDATA[You got this from the signup page: <a href='https://www.google.com/recaptcha/admin/create' target='_blank'>www.google.com/recaptcha/</a>.]]></comment>

                            <frontend_type>text</frontend_type>

                            <sort_order>20</sort_order>

                            <show_in_default>1</show_in_default>

                            <show_in_website>1</show_in_website>

                            <show_in_store>1</show_in_store>

                            <depends><enabled>1</enabled></depends>

                        </public_key>

                        <private_key translate="label">

                            <label>Secret Key</label>

                            <comment><![CDATA[You got this from the signup page: <a href='https://www.google.com/recaptcha/admin/create' target='_blank'>www.google.com/recaptcha/</a>.]]></comment>

                            <frontend_type>text</frontend_type>

                            <sort_order>30</sort_order>

                            <show_in_default>1</show_in_default>

                            <show_in_website>1</show_in_website>

                            <show_in_store>1</show_in_store>

                            <depends><enabled>1</enabled></depends>

                        </private_key>

                        <theme translate="label">

                            <label>reCaptcha Theme</label>

                            <comment>Customizing the Look of reCAPTCHA</comment>

                            <frontend_type>select</frontend_type>

                            <source_model>mycompany_contactsrecaptcha/system_config_source_dropdown_theme</source_model>

                            <sort_order>40</sort_order>

                            <show_in_default>1</show_in_default>

                            <show_in_website>1</show_in_website>

                            <show_in_store>1</show_in_store>

                            <depends><enabled>1</enabled></depends>

                        </theme>

                        <lang translate="label">

                            <label>reCaptcha Language</label>

                            <comment>Which language is used in the reCaptcha interface</comment>

                            <frontend_type>select</frontend_type>

                            <source_model>mycompany_contactsrecaptcha/system_config_source_dropdown_lang</source_model>

                            <sort_order>50</sort_order>

                            <show_in_default>1</show_in_default>

                            <show_in_website>1</show_in_website>

                            <show_in_store>1</show_in_store>

                            <depends><enabled>1</enabled></depends>

                        </lang>

                    </fields>

                </mycompany_contactsrecaptcha>

            </groups>

        </contacts>

    </sections>

</config>


Step 3: Create Model files to give option in system.xml
a:) Create file in app/code/local/Mycompany/Contactsrecaptcha/Model/System/Config/Source/Dropdown/Lang.php and add below code in it.

<?php
class Mycompany_Contactsrecaptcha_Model_System_Config_Source_Dropdown_Lang
{
    /**
     * Generate lang options array
     * @return array
     */
 public function toOptionArray() {
  return array (
    array (
      'value' => 'en',
      'label' => 'English (default)'
    ),
    array (
      'value' => 'ar',
      'label' => 'Arabic'
    ),
    array (
      'value' => 'af',
      'label' => 'Afrikaans'
    ),
    array (
      'value' => 'am',
      'label' => 'Amharic'
    ),
    array (
      'value' => 'hy',
      'label' => 'Armenian'
    ),
    array (
      'value' => 'az',
      'label' => 'Azerbaijani'
    ),
    array (
      'value' => 'eu',
      'label' => 'Basque'
    ),
    array (
      'value' => 'bn',
      'label' => 'Bengali'
    ),
    array (
      'value' => 'bg',
      'label' => 'Bulgarian'
    ),
    array (
      'value' => 'ca',
      'label' => 'Catalan'
    ),
    array (
      'value' => 'zh-HK',
      'label' => 'Chinese (Hong Kong)'
    ),
    array (
      'value' => 'zh-CN',
      'label' => 'Chinese (Simplified)'
    ),
    array (
      'value' => 'zh-TW',
      'label' => 'Chinese (Traditional)'
    ),
    array (
      'value' => 'hr',
      'label' => 'Croatian'
    ),
    array (
      'value' => 'cs',
      'label' => 'Czech'
    ),
    array (
      'value' => 'da',
      'label' => 'Danish'
    ),
    array (
      'value' => 'nl',
      'label' => 'Dutch'
    ),
    array (
      'value' => 'en-GB',
      'label' => 'English (UK)'
    ),
    array(
      'value' => 'et',
      'label' => 'Estonian',
    ),
    array(
      'value' => 'fil',
      'label' => 'Filipino',
    ),
    array(
      'value' => 'fi',
      'label' => 'Finnish',
    ),
    array(
      'value' => 'fr',
      'label' => 'French',
    ),
    array(
      'value' => 'fr-CA',
      'label' => 'French (Canadian)',
    ),
    array(
      'value' => 'gl',
      'label' => 'Galician',
    ),
    array(
      'value' => 'ka',
      'label' => 'Georgian',
    ),
    array(
      'value' => 'de',
      'label' => 'German',
    ),
    array(
      'value' => 'de-AT',
      'label' => 'German (Austria)',
    ),
    array(
      'value' => 'de-CH',
      'label' => 'German (Switzerland)',
    ),
    array(
      'value' => 'el',
      'label' => 'Greek',
    ),
    array(
      'value' => 'gu',
      'label' => 'Gujarati',
    ),
    array(
      'value' => 'iw',
      'label' => 'Hebrew',
    ),
    array(
      'value' => 'hi',
      'label' => 'Hindi',
    ),
    array(
      'value' => 'hu',
      'label' => 'Hungarain',
    ),
    array(
      'value' => 'is',
      'label' => 'Icelandic',
    ),
    array(
      'value' => 'id',
      'label' => 'Indonesian',
    ),
    array(
      'value' => 'it',
      'label' => 'Italian',
    ),
    array(
      'value' => 'ja',
      'label' => 'Japanese',
    ),
    array(
      'value' => 'kn',
      'label' => 'Kannada',
    ),
    array(
      'value' => 'ko',
      'label' => 'Korean',
    ),
    array(
      'value' => 'lo',
      'label' => 'Laothian',
    ),
    array(
      'value' => 'lv',
      'label' => 'Latvian',
    ),
    array(
      'value' => 'lt',
      'label' => 'Lithuanian',
    ),
    array(
      'value' => 'ms',
      'label' => 'Malay',
    ),
    array(
      'value' => 'ml',
      'label' => 'Malayalam',
    ),
    array(
      'value' => 'mr',
      'label' => 'Marathi',
    ),
    array(
      'value' => 'mn',
      'label' => 'Mongolian',
    ),
    array(
      'value' => 'no',
      'label' => 'Norwegian',
    ),
    array(
      'value' => 'fa',
      'label' => 'Persian',
    ),
    array(
      'value' => 'pl',
      'label' => 'Polish',
    ),
    array(
      'value' => 'pt',
      'label' => 'Portuguese',
    ),
    array(
      'value' => 'pt-BR',
      'label' => 'Portuguese (Brazil)',
    ),
    array(
      'value' => 'pt-PT',
      'label' => 'Portuguese (Portugal)',
    ),
    array(
      'value' => 'ro',
      'label' => 'Romanian',
    ),
    array(
      'value' => 'ru',
      'label' => 'Russian',
    ),
    array(
      'value' => 'sr',
      'label' => 'Serbian',
    ),
    array(
      'value' => 'si',
      'label' => 'Sinhalese',
    ),
    array(
      'value' => 'sk',
      'label' => 'Slovak',
    ),
    array(
      'value' => 'sl',
      'label' => 'Slovenian',
    ),
    array(
      'value' => 'es',
      'label' => 'Spanish',
    ),
    array(
      'value' => 'es-419',
      'label' => 'Spanish (Latin America)',
    ),
    array(
      'value' => 'sw',
      'label' => 'Swahili',
    ),
    array(
      'value' => 'sv',
      'label' => 'Swedish',
    ),
    array(
      'value' => 'ta',
      'label' => 'Tamil',
    ),
    array(
      'value' => 'te',
      'label' => 'Telugu',
    ),
    array(
      'value' => 'th',
      'label' => 'Thai',
    ),
    array(
      'value' => 'tr',
      'label' => 'Turkish',
    ),
    array(
      'value' => 'uk',
      'label' => 'Ukrainian',
    ),
    array(
      'value' => 'ur',
      'label' => 'Urdu',
    ),
    array(
      'value' => 'vi',
      'label' => 'Vietnamese',
    ),
    array(
      'value' => 'zu',
      'label' => 'Zulu',
    )
  );
 }
}

b:) Create file in app/code/local/Mycompany/Contactsrecaptcha/Model/System/Config/Source/Dropdown/Theme.php and add below code in it.

<?php
class Mycompany_Contactsrecaptcha_Model_System_Config_Source_Dropdown_Theme
{
    /**
     * Generate theme options array
     * @return array
     */
    public function toOptionArray()
    {
        return array(
            array(
                'value' => 'light',
                'label' => 'Light (default)',
            ),
            array(
                'value' => 'dark',
                'label' => 'Dark',
            )
        );
    }
}

Step 4: Create Controller file and Customize index and Post action to display and validate google reCAPTCHA.

Create file in app/code/local/Mycompany/Contactsrecaptcha/controllers/IndexController.php and add below code in it.

<?php
//include controller to override it
require_once Mage::getBaseDir('app') . DS . 'code' . DS . 'core' . DS . 'Mage' . DS . 'Contacts' . DS . 'controllers' . DS . 'IndexController.php';

class Mycompany_Contactsrecaptcha_IndexController extends Mage_Contacts_IndexController
{
    /**
     * XML system configuration paths
     * @var string
     */
    const XML_PATH_CFC_ENABLED     = 'contacts/mycompany_contactsrecaptcha/enabled';
    const XML_PATH_CFC_PUBLIC_KEY  = 'contacts/mycompany_contactsrecaptcha/public_key';
    const XML_PATH_CFC_PRIVATE_KEY = 'contacts/mycompany_contactsrecaptcha/private_key';
    const XML_PATH_CFC_THEME       = 'contacts/mycompany_contactsrecaptcha/theme';
    const XML_PATH_CFC_LANG        = 'contacts/mycompany_contactsrecaptcha/lang';

    /**
     * Method which handle action of displaying contact form
     */
    public function indexAction()
    {
        $this->loadLayout();

        $this->getLayout()->getBlock('contactForm')->setFormAction( Mage::getUrl('*/*/post', array('_secure' => $this->getRequest()->isSecure())) );

        if (Mage::getStoreConfigFlag(self::XML_PATH_CFC_ENABLED)) {
            //create captcha html-code
            $siteKey = Mage::getStoreConfig(self::XML_PATH_CFC_PUBLIC_KEY);

            //get reCaptcha theme name
            $theme = Mage::getStoreConfig(self::XML_PATH_CFC_THEME);
            if (strlen($theme) == 0 || !in_array($theme, array('dark', 'light'))) {
                $theme = 'light';
            }

            //get reCaptcha lang name
            $lang = Mage::getStoreConfig(self::XML_PATH_CFC_LANG);
            if (strlen($lang) == 0) {
                $lang = 'en';
            }

            $this->getLayout()->getBlock('contactForm')
                ->setSiteKey($siteKey)
                ->setCaptchaTheme($theme)
                ->setCaptchaLang($lang);
        }

        $this->_initLayoutMessages('customer/session');
        $this->_initLayoutMessages('catalog/session');
        $this->renderLayout();
    }

    /**
     * Handle post request of Contact form
     */
    public function postAction()
    {
        if (Mage::getStoreConfigFlag(self::XML_PATH_CFC_ENABLED)) {
            try {
                $post = $this->getRequest()->getPost();
                $formData = new Varien_Object();
                $formData->setData($post);
                Mage::getSingleton('core/session')->setData('contactForm', $formData);

                if ($post) {
                    if ((!isset($post['g-recaptcha-response']))
                        || (!$this->_isCaptchaValid($post['g-recaptcha-response']))
                    ) {
                        throw new Exception(
                            $this->__("The reCAPTCHA wasn't entered correctly. Go back and try it again."),
                            1
                        );
                    }

                    Mage::getSingleton('core/session')->unsetData('contactForm');
                } else {
                    throw new Exception('', 1);
                }
            } catch (Exception $e) {
                if (strlen($e->getMessage()) > 0) {
                    Mage::getSingleton('customer/session')->addError($this->__($e->getMessage()));
                }
                $this->_redirect('*/*/');
                return;
            }
        }

        //everything is OK - call parent action
        parent::postAction();
    }

    /**
     * Check if captcha is valid
     * @param  string $captchaResponse
     * @return boolean
     */
    protected function _isCaptchaValid($captchaResponse)
    {
        $result = false;

        $params = array(
            'secret' => Mage::getStoreConfig(self::XML_PATH_CFC_PRIVATE_KEY),
            'response' => $captchaResponse
        );

        $ch = curl_init('https://www.google.com/recaptcha/api/siteverify');
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_HEADER, 0);
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($params));
        curl_setopt($ch, CURLOPT_VERBOSE, 1);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
        curl_setopt($ch, CURLOPT_TIMEOUT, 30);
        $requestResult = trim(curl_exec($ch));
        curl_close($ch);

        if (is_array(json_decode($requestResult, true))) {
            $response = json_decode($requestResult, true);

            if (isset($response['success']) && $response['success'] === true) {
                $result = true;
            }
        }

        return $result;
    }
}
Step 5: Create layout file. Create file in app/design/frontend/rwd/default/layout/contactsrecaptcha.xml and add below code in it.

<?xml version="1.0" encoding="UTF-8"?>
<layout version="0.1.0">
    <contacts_index_index>
        <reference name="content">
            <reference name="contactForm">
                <action method="setTemplate" ifconfig="contacts/mycompany_contactsrecaptcha/enabled"><template>contactsrecaptcha/form.phtml</template></action>
            </reference>
        </reference>
    </contacts_index_index>
</layout>

Step 6: Create Template file to render HTML. Create file in app/design/frontend/rwd/default/template/contactsrecaptcha/form.phtml and add below code in it.

<?php
/**
 * Magento
 *
 * NOTICE OF LICENSE
 *
 * This source file is subject to the Academic Free License (AFL 3.0)
 * that is bundled with this package in the file LICENSE_AFL.txt.
 * It is also available through the world-wide-web at this URL:
 * http://opensource.org/licenses/afl-3.0.php
 * If you did not receive a copy of the license and are unable to
 * obtain it through the world-wide-web, please send an email
 * to license@magentocommerce.com so we can send you a copy immediately.
 *
 * DISCLAIMER
 *
 * Do not edit or add to this file if you wish to upgrade Magento to newer
 * versions in the future. If you wish to customize Magento for your
 * needs please refer to http://www.magentocommerce.com for more information.
 *
 * @category    design
 * @package     base_default
 * @copyright   Copyright (c) 2012 Magento Inc. (http://www.magentocommerce.com)
 * @license     http://opensource.org/licenses/afl-3.0.php  Academic Free License (AFL 3.0)
 */
?>
<?php $contactForm = Mage::getSingleton('core/session')->getData('contactForm'); ?>
<?php $contactForm = $contactForm ? $contactForm : new Varien_Object(); ?>
<?php $contactForm->setName( (strlen($contactForm->getName()) > 0 ? $contactForm->getName() : $this->helper('contacts')->getUserName()) ); ?>
<?php $contactForm->setEmail( (strlen($contactForm->getEmail()) > 0 ? $contactForm->getEmail() : $this->helper('contacts')->getUserEmail()) ); ?>

<div id="messages_product_view"><?php echo $this->getMessagesBlock()->toHtml() ?></div>
<div class="page-title">
    <h1><?php echo Mage::helper('contacts')->__('Contact Us') ?></h1>
</div>
<script src="https://www.google.com/recaptcha/api.js?onload=renderReCaptcha&render=explicit&hl=<?php echo $this->getCaptchaLang(); ?>" async defer></script>
<script type="text/javascript">
    function renderReCaptcha() {
        grecaptcha.render('re_captcha', {
          sitekey: '<?php echo $this->getSiteKey(); ?>',
          theme: '<?php echo $this->getCaptchaTheme(); ?>',
          lang: '<?php echo $this->getCaptchaLang(); ?>'
        });
    }
</script>
<form action="<?php echo $this->getFormAction(); ?>" id="contactForm" method="post" class="scaffold-form">
    <div class="fieldset">
        <h2 class="legend"><?php echo Mage::helper('contacts')->__('Contact Information') ?></h2>
        <ul class="form-list">
            <li class="fields">
                <div class="field">
                    <label for="name" class="required"><em>*</em><?php echo Mage::helper('contacts')->__('Name') ?></label>
                    <div class="input-box">
                        <input name="name" id="name" title="<?php echo Mage::helper('contacts')->__('Name') ?>" value="<?php echo $this->htmlEscape($contactForm->getName()) ?>" class="input-text required-entry" type="text" />
                    </div>
                </div>
                <div class="field">
                    <label for="email" class="required"><em>*</em><?php echo Mage::helper('contacts')->__('Email') ?></label>
                    <div class="input-box">
                        <input name="email" id="email" title="<?php echo Mage::helper('contacts')->__('Email') ?>" value="<?php echo $this->htmlEscape($contactForm->getEmail()) ?>" class="input-text required-entry validate-email" type="text" />
                    </div>
                </div>
            </li>
            <li>
                <label for="telephone"><?php echo Mage::helper('contacts')->__('Telephone') ?></label>
                <div class="input-box">
                    <input name="telephone" id="telephone" title="<?php echo Mage::helper('contacts')->__('Telephone') ?>" value="<?php echo $this->htmlEscape($contactForm->getTelephone()) ?>" class="input-text" type="text" />
                </div>
            </li>
            <li class="wide">
                <label for="comment" class="required"><em>*</em><?php echo Mage::helper('contacts')->__('Comment') ?></label>
                <div class="input-box">
                    <textarea name="comment" id="comment" title="<?php echo Mage::helper('contacts')->__('Comment') ?>" class="required-entry input-text" cols="5" rows="3"><?php echo $this->htmlEscape($contactForm->getComment()) ?></textarea>
                </div>
            </li>
            <li class="wide">
                <div class="input-box">
                    <div id="re_captcha"></div>
                </div>
            </li>
        </ul>
    </div>
    <div class="buttons-set">
        <p class="required"><?php echo Mage::helper('contacts')->__('* Required Fields') ?></p>
        <input type="text" name="hideit" id="hideit" value="" style="display:none !important;" />
        <button type="submit" title="<?php echo Mage::helper('contacts')->__('Submit') ?>" class="button"><span><span><?php echo Mage::helper('contacts')->__('Submit') ?></span></span></button>
    </div>
</form>
<script type="text/javascript">
//<![CDATA[
    var contactForm = new VarienForm('contactForm', true);
//]]>
</script>

Now Fill up your google reCAPTCHA site key and secret key from admin under
system >> Configuration >> General >> Contacts.

You will google reCAPTCHA as per below:

Download Whole Module from Github: https://github.com/vijayrami/Contact-US-reCAPTCHA
Tag : Magento
0 Comments On "Add Google reCAPTCHA on Contact US Page in Magento"

Back To Top