Merchant Stories

CAPTCHA Module for Registration in Magento ®

Nov 7, 2014 8 min read 578 views
Listen audio
CAPTCHA Module for Registration in Magento ®

Additional modules are necessary in Magento ® system in order to create new features for web stores and extend the default options. Let us review how to create a CAPTCHA module for registration in Magento®.

The code was taken from http://habrhabr.ru.

In this article we will discuss the following points:

1. The process of the module creation;

2. Transformation of different blocks;

3. Controller reconfiguration;

4. Development of module installation scripts.

Why the CAPTCHA module is necessary

Having so many modules for Magento ® to choose from you may indeed find it strange to create a module by yourself. First of all, this will give you more experience that will be useful for your further work on the site. Secondly, it is not always possible to find a module with the functionality you need, or you are not satisfied with its price or quality.

Why CAPTCHA module is needed? It serves as your protection from spammers and bots which try to litter your web store with malicious links and comments. Beside that we also recommend using a closed invitation code that will save you and your customers from potential intruders. It is actually quite easy to create such an extension and we are going to show you how to do that.

Registration page

Our registration page is located at this path: /magento/customer/account/create. We need to add CAPTCHA check and also an invitation code field that will require customers to enter their code. By default, there are three customer groups in Magento ®: General, Wholesale and Retailer. A customer will need to choose their group. But Magento ® system does not know anything about an invitation code yet, so you need to create a new attribute for it.

In order to start the work, locate the registration form template.

For example:

/magento/app/design/frontend/default/default/template/customer/form/register.phtml — it is a registration form.

The attributes are added in the module installer, below is an example for the core variant but it is not recommended to modify the core:

/magento/app/code/core/Mage/Customer/sql/customer_setup/mysql4-upgrade-0.8.7-0.8.8.php

It is better to write your own installer and add it to the module.

Find the description of the attributes that are being edited in the module configuration:

/magento/app/code/core/Mage/Customer/etc/config.xml

In tags <fieldsets>

In its turn, registration is also posted by the following URL:

http://localhost/magento/customer/account/createpost/

After this description we understand that the whole process is controlled by Mage_Customer_AccountController.

Please note that we will not modify the existing files, we will create new ones. The existing files will serve as a sample for the future work. We begin with creating a new folder in the catalog:

/magento/app/design/frontend/default/mytheme

default — interface name

mytheme — a name of the future theme

Here we will create the extension templates.

The future theme files with the same names will override the files of the standard template.

So, actually the standard theme will not be modified manually.

Now we need to create a module CustomerMod. The folder structure is the same for all extensions:

magento/app/code/local/
    Examples
        CustomerMod
            - Block
            - etc
            - Helper
            - Model
            - sql

 

 

It is necessary to create a file with the extension descriptions:

magento/app/etc/modules/Examples_All.xml
<config>
	<modules>
   	<Examples_CustomerMod>
       	<active>true</active>
           <codePool>local</codePool>
   	</Examples_CustomerMod>
	</modules>
</config>

 

 

Additional Captcha module fields on the registration page

We need to create additional fields on the registration page that will allow users choose to which group they will be assigned («General», «Wholesale», «Retailer»). In order to realize that we only need to create an additional block on the registration page where the necessary group will be located.

A group selection template should be located in a separate file:

/magento/app/design/frontend/default/example_theme/template/customer/form/register/groupselect.phtml

See below the content of that file:

<?php $customer_groups = Mage::helper('customer')->getGroups()->toOptionArray(); ?>
<fieldset class="group-select">
<h4 class="legend"><?php echo $this->__('Customer Group') ?></h4>
<ul>
<?php foreach($customer_groups as $cg) { ?>
           	<li class="f-left" style="margin: 2px 4px;" >
                          	<input type="radio" name="group_id" id="group_id"
                                          	value="<?php echo $cg['value']; ?>"
                                          	<?php if ($cg['value']==1) 
                                            echo 'checked=1' ?>  />
                          	<label><?php echo $cg['label']; ?></label>
           	</li>
<?php } //end foreach?>
</ul>
</fieldset>

 

 

Please note that “group_id” field name must correspond to the attribute name.

Layout correction

Location of the blocks and their relation to the templates is described in ‘layout’ section. These are xml files which you will find at magento/app/design/interface_name/theme_name/layout.

In the template sample being reviewed the path and the file look as follows:

/magento/app/design/frontend/default/example_theme/layout/customermod.xml

<layout version="0.1.0">
    <customer_account_create>                               	                           	
        <reference name="customer_form_register">                                          	
            <block type="core/template" name="customergroups-select" template="customer/
            form/register/groupselect.phtml" />
            <block type="captcha/recaptcha" name="captcha" />                            	
        </reference>               	
    </customer_account_create>             	
</layout>

 

 

The file refers to customer_form_register. Inside it you need to add a path to the block being created:

type is a block class. In this case it is “core/template” which also means Mage_Core_Block_Template.

name — any name you like.

template — block template.

Do not forget to setup the layout update in the module configuration files so that Magento ® could apply all changes specified by customermod.xml:

/magento/app/code/local/Examples/CustomerMod/etc/config.xml

<frontend>
<layout>
 	<updates>
     	<customermod>
             <file>customermod.xml</file>
     	</customermod>
 	</updates>
</layout>
</frontend>

 

 

Now we need to call the block.

We will do that using getChildHtml(name_block).

Copy the file register.phtml from default theme into the one being used and add the call before ‘Login Information’:

/magento/app/design/frontend/default/example_theme/template/customer/form/register.phtml

...
<?php echo $this->getChildHtml('customergroups-select') ?>
 
<fieldset class="group-select wide">
   	<h4 class="legend"><?php echo $this->__('Login Information') ?></h4>
…

 

 

Then save the changes and the customer group selection block should become visible to customers. If something goes wrong please consult with our development team.

New module attribute

All attributes are stored in eav_attributes table, so usually the work with the attributes includes making changes to the data in eav_attributes table.

You should also remember about static attributes because their values are stored on other tables.

1. Installer scripts

All actions related to the module modifications are done in the installer scripts which are stored in ‘sql’ folder inside each module:

/magento/app/code/core/Mage/Customer/sql/customer_setup

The scripts can be of two types – setup and upgrade. Magento ® runs the necessary script once during the installation or update of your extension. After the installation is complete a new line is added to ‘core_resource’ tables, like this:

‘customermod_setup’, ‘0.1.0’

Remember that the scripts will not be removed automatically, you will need to remove them manually if needed.

2. Attribute script

The samples of installer scripts can be found in standard modules for Magento ®. Let’s say, it looks as follows:

$installer = $this;
/* @var $installer Mage_Customer_Model_Entity_Setup */
$installer->startSetup();
$installer->addAttribute('customer', 'invitation_code', array(
    'type' => 'varchar',
    'input' => 'text',
    'label' => 'Invitation Code',
    'global' => 1,
    'visible' => 1,
    'required' => 1,
    'user_defined' => 1,
    'default' => null,
    'visible_on_front' => 1
));
$installer->endSetup();

 

 

Now you need to update the template.

Add an additional field into the registration form:

/magento/app/design/frontend/default/example_theme/template/customer/form/register.phtml

<div class="input-box">
    <label for="invitation_code"><?php echo $this->__('Invitation Code') ?> 
    <span class="required">*</span></label>
    <input type="text" name="invitation_code" id="invitation_code" 
    title="<?php echo $this->__('Invitation Code') ?>" class="required-entry 
    input-text" />
</div>

 

 

Now update the settings. Particularly, add the installer script characteristics:

/magento/app/code/local/Examples/CustomerMod/etc/config.xml

<global>
    <resources>
        <customermod_setup>
            <setup>
                <module>Examples_CustomerMod</module>
                <class>Mage_Eav_Model_Entity_Setup</class>
            </setup>
            <connection><use>core_setup</use></connection>
        </customermod_setup>
        <customermod_write><connection><use>core_write</use></connection>
        </customermod_write>
        <customermod_read><connection><use>core_read</use></connection>
        </customermod_read>
    </resources>

 

 

Indicate the new field in fieldsets:

<fieldsets>
    <customer_account>
        <group_id><create>1</create><update>1</update></group_id>
        <invitation_code><create>1</create><update>1</update></invitation_code>                                      	            	            	
    </customer_account>
</fieldsets>

 

 

After that the registration form will have a field for entering an invitation code, called Invitation Code. Its value is stored in ‘invitation_code’ attribute for each customer individually.

CAPTCHA

Before starting to work you need to download recaptcha-php library and copy it into /magento/lib folder.

In the module configuration CustomerMod we need to describe the controller being used:

<config>
	...
	<frontend>
	...
	<routers>
    	<customer>
       	<args>
          	<modules>
             	<Examples_CustomerMod before="Mage_Customer">Examples_CustomerMod
              </Examples_CustomerMod>
          	</modules>
       	</args>
    	</customer>
 	</routers>
	…

 

 

The controller itself should be located in catalog

/magento/app/code/local/Examples/CustomerMod/controllers/AccountController.php

require_once("Mage/Customer/controllers/AccountController.php");
require_once('recaptcha/recaptchalib.php');
class Examples_CustomerMod_AccountController extends Mage_Customer_AccountController {
                          	
    public function createPostAction() {                  	
        $request = $this->getRequest();                         	
        $captchaIsValid =  Mage::helper('captcha')->captchaIsValid($request);
        
        if ($captchaIsValid) {
            parent::createPostAction();
        } else {
            $this->_getSession()->setCustomerFormData($this->getRequest()->getPost());
            $this->_getSession()->addError($this->__('Verification code was not correct. 
            Please try again.'));
            $this->_redirectError(Mage::getUrl('*/*/create', array('_secure'=>true)));
        }
    }
}

 

 

In order to check CAPTCHA use controller:

Examples_Captcha_Helper_Data:

/magento/app/code/local/Examples/Captcha/Helper/Data.php

require_once('recaptcha/recaptchalib.php');
class Examples_Captcha_Helper_Data extends Mage_Core_Helper_Abstract
{          	
    const CAPTCHA_PUBLIC_KEY = "public-key-for-the-website";
    const CAPTCHA_PRIVATE_KEY = "private-key-for-the-website";

    public function captchaIsValid(Mage_Core_Controller_Request_Http $request) {     	
        if ($request) {
            $resp = recaptcha_check_answer (self::CAPTCHA_PRIVATE_KEY,
                   $_SERVER["REMOTE_ADDR"],
                   $request->getParam("recaptcha_challenge_field"),
                $request->getParam("recaptcha_response_field") );                   	
            return $resp->is_valid;
        }
        return false;                                                                                 	
    }

    public function captchaGetError(Mage_Core_Controller_Request_Http $request) {
        if ($request) {
            $resp = recaptcha_check_answer (self::CAPTCHA_PRIVATE_KEY,
               $_SERVER["REMOTE_ADDR"],
                   $request->getParam("recaptcha_challenge_field"),
                   $request->getParam("recaptcha_response_field") );
            return $resp->error;
        }
        return false;
                    
    }

    public function getPublicKey() { return  Examples_Captcha_Helper_Data::CAPTCHA_PUBLIC
    _KEY; }
           	
}

 

 

CAPTCHA block

The registration page should have a CAPTCHA image displayed. For this a special function recaptcha_get_html() is used. The function can be called from the template itself (phtml) but it is recommended to create an additional class. In order to do this, you need to describe the class Examples_Captcha_Block_Recaptcha.

/magento/app/code/local/Examples/Captcha/Block/Recaptcha.php

require_once('recaptcha/recaptchalib.php');
class Examples_Captcha_Block_Recaptcha extends Mage_Core_Block_Abstract {                    	
    public function _toHtml() {
        $html = recaptcha_get_html( Mage::helper('captcha')->getPublicKey() );
        return $html;
    }
}

 

 

Now add this block to layout.

/magento/app/design/frontend/default/example_theme/layout/customermod.xml

<?xml version="1.0"?>
<layout version="0.1.0">
    <customer_account_create>                                                              	
        <reference name="customer_form_register">                                          	
            <block type="core/template" name="customergroups-select" template="customer/
            form/register/groupselect.phtml" />
            <block type="captcha/recaptcha" name="captcha" />                            	
        </reference>               	
    </customer_account_create>
</layout>

 

 

Now tell Captcha extension that it has a block and helper:

/magento/app/code/local/Examples/Captcha/etc/config.xml

<?xml version="1.0" encoding="UTF-8"?>
<config>          	
    <modules>
       <Examples_Captcha>
          <version>0.1.0</version>
       </Examples_Captcha>
    </modules>

    <global>    	                  	
        <blocks>
            <captcha><class>Examples_Captcha_Block</class></captcha>
        </blocks>                                                      	
        <helpers>
            <captcha>
                <class>Examples_Captcha_Helper</class>
            </captcha>
        </helpers>                                                    	
    </global>        	
</config>

 

 

Now, your CAPTCHA block for Magento ® is complete.0

That's where you contact us!

    By submitting this form you agree to GoMage's Terms of Use and Privacy Policy
    woo-hoo! Now its time to keep checking your inbox, as we will be getting in touch soon. Promise :)
    oops! Thanks. But it seems like some kind of technical issues stop you from meeting GOMAGE. Could you try again?