How to Add Google reCAPTCHA to Custom Form​ in Magento 2

How to Add Google reCAPTCHA to Custom Form​ in Magento 2

Google reCAPTCHA helps protect websites from spam, bot attacks, and other automated form submissions.

Adding reCAPTCHA to your Magento 2 custom forms adds an essential layer of security, ensuring only genuine user interactions are processed by your site.

Magento 2 already includes a built-in implementation of Google reCAPTCHA for standard frontend forms, such as:

  1. Customer Login
  2. Forgot Password
  3. Create New Customer Account
  4. Edit Customer Account
  5. Contact Us
  6. Product Review
  7. Newsletter Subscription
  8. Send to Friend
  9. Checkout/Placing Order
  10. Coupon Codes, and 
  11. PayPal PayflowPro payment.

Additionally, Magento’s flexibility allows us to add Google reCAPTCHA to custom forms as needed. This guide will walk you through the process of configuring Google reCAPTCHA in Magento 2, creating a custom extension for your form, and integrating reCAPTCHA into the form template.

How to Add Google reCAPTCHA to Custom Form in Magento 2

  1. Configure Google reCAPTCHA in Magento 2
  2. Create a Custom Extension to Display Your Custom Form
  3. Add the Magento 2 Custom Form to the List of Frontend reCAPTCHA
  4. Integrate Google reCAPTCHA into the Custom Form Template
  5. Build a Controller to Handle Custom Form Submissions
  6. Validate Google reCAPTCHA for the Custom Form in Magento 2

Struggling to Add Google reCAPTCHA to Custom Forms?

Our expert developers can help you seamlessly integrate reCAPTCHA and enhance your form security while minimizing user friction.

Step 1. Сonfigure Google reCAPTCHA on Magento 2

First, register your site at Google reCAPTCHA, and select the type of reCAPTCHA you want to use.

Step 1: register your website at Google reCAPTCHA

Then, go to Stores > Configuration > Security > Google reCAPTCHA Storefront > reCAPTCHA v2 (“I am not a robot”) / reCAPTCHA v2 Invisible / reCAPTCHA v3 Invisible and enter the site key and secret key you created on Google reCAPTCHA after registering. Make sure that the setting name in Magento matches the type of Google reCAPTCHA you created (e.g., reCAPTCHA v2 or v3).

Step 1: enter the site key and secret key

Step 2. Create a Custom Extension to Display Your Custom Form

We need to create the following files.

app/code/Vendor/CustomFormRecaptcha/registration.php
<?php


use Magento\Framework\Component\ComponentRegistrar;


ComponentRegistrar::register(
   ComponentRegistrar::MODULE, 'Vendor_CustomFormRecaptcha',
   __DIR__
);
app/code/Vendor/CustomFormRecaptcha/etc/module.xml
<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:noNamespaceSchemaLocation="urn:magento:framework:Module/etc/module.xsd">
   <module name="Vendor_CustomFormRecaptcha"/>
</config>
app/code/Vendor/CustomFormRecaptcha/etc/frontend/routes.xml
<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:noNamespaceSchemaLocation="urn:magento:framework:Module/etc/module.xsd">
   <module name="Vendor_CustomFormRecaptcha"/>
</config>
app/code/Vendor/CustomFormRecaptcha/Controller/Index/Index.php
<?php


namespace Vendor\CustomFormRecaptcha\Controller\Index;


use Magento\Framework\App\ActionInterface;
use Magento\Framework\App\Action\Context;
use Magento\Framework\View\Result\PageFactory;


class Index implements ActionInterface
{
   /**
    * @var PageFactory
    */
   private $resultPageFactory;


   /**
    * @var Context
    */
   private $context;


   public function __construct(
       Context $context,
       PageFactory $resultPageFactory
   ) {
       $this->context = $context;
       $this->resultPageFactory = $resultPageFactory;
   }


   public function execute()
   {
       return $this->resultPageFactory->create();
   }
}
app/code/Vendor/CustomFormRecaptcha/view/frontend/layout/customformrecaptcha_index_index.xml
<?xml version="1.0"?>
<page xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:View/Layout/etc/page_configuration.xsd">
   <body>
       <referenceContainer name="content">
           <block class="Magento\Framework\View\Element\Template"
                  name="customformrecaptcha"
                  template="Vendor_CustomFormRecaptcha::form.phtml"
           />
       </referenceContainer>
   </body>
</page>
app/code/Vendor/CustomFormRecaptcha/view/frontend/templates/form.phtml
<?php /** @var \Magento\Framework\View\Element\Template $block */ ?>
<form action="" method="post">
   <div>
       <label for="name">Name:</label>
       <input type="text" name="name" id="name" required/>
   </div>
   <div>
       <label for="email">Email:</label>
       <input type="email" name="email" id="email" required/>
   </div>
   <div>
       <button type="submit">Submit</button>
   </div>
   <input name="form_key" type="hidden" value="<?php echo $block->getFormKey(); ?>" />
</form>

After creating the files, run the following commands:

php bin/magento setup:upgrade
php bin/magento setup:di:compile
php bin/magento setup:static-content:deploy
php bin/magento cache:flush

Now we can see our form following the link: https://your-website-url/customformrecaptcha/index/index

Step 2. Create a Custom Extension to Display Your Custom Form

Step 3. Add the Magento 2 Custom Form to the List of Frontend reCAPTCHA

Create a file app/code/Vendor/CustomFormRecaptcha/etc/adminhtml/system.xml
<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:module:Magento_Config:etc/system_file.xsd">
   <system>
       <section id="recaptcha_frontend">
           <group id="type_for">
               <field id="customformrecaptcha" translate="label" type="select" sortOrder="600" showInDefault="1" showInWebsite="1" showInStore="0" canRestore="1">
                   <label>Enable for Custom Form Recaptcha</label>
                   <source_model>Magento\ReCaptchaAdminUi\Model\OptionSource\Type</source_model>
               </field>
           </group>
       </section>
   </system>
</config>

Clean magento cache.
php bin/magento cache:flush

Go to the Magento Admin panel, navigate to Stores > Configuration > Security > Google reCAPTCHA > Storefront, and you will see an option to enable Google reCAPTCHA for our custom form.

Step 3. Add the Magento 2 Custom Form to the List of Frontend reCAPTCHA

Step 4. Display Google reCAPTCHA in the Magento 2 Custom Form

Create a reCAPTCHA block in the layout file app/code/Vendor/CustomFormRecaptcha/view/frontend/layout/customformrecaptcha_index_index.xml
After adding the block, the content of file will be the following:

<?xml version="1.0"?>
<page xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:View/Layout/etc/page_configuration.xsd">
   <body>
       <referenceContainer name="content">
           <block class="Magento\Framework\View\Element\Template"
                  name="customformrecaptcha"
                  template="Vendor_CustomFormRecaptcha::form.phtml">
               <block class="Magento\ReCaptchaUi\Block\ReCaptcha"
                      name="recaptcha"
                      after="-"
                      template="Magento_ReCaptchaFrontendUi::recaptcha.phtml"
                      ifconfig="recaptcha_frontend/type_for/customformrecaptcha">
                   <arguments>
                       <argument name="recaptcha_for" xsi:type="string">customformrecaptcha</argument>
                       <argument name="jsLayout" xsi:type="array">
                           <item name="components" xsi:type="array">
                               <item name="recaptcha" xsi:type="array">
                                   <item name="component" xsi:type="string">Magento_ReCaptchaFrontendUi/js/reCaptcha</item>
                               </item>
                           </item>
                       </argument>
                   </arguments>
               </block>
           </block>
       </referenceContainer>
   </body>
</page>

Now let’s output the reCAPTCHA block in the form template.

The content of the file app/code/Vendor/CustomFormRecaptcha/view/frontend/templates/form.phtml will change to the following:

<?php /** @var \Magento\Framework\View\Element\Template $block */ ?>
<form action="<?= $block->getUrl('customformrecaptcha/index/post') ?>" method="post">
   <div>
       <label for="name">Name:</label>
       <input type="text" name="name" id="name" required/>
   </div>
   <div>
       <label for="email">Email:</label>
       <input type="email" name="email" id="email" required/>
   </div>
   <div>
       <?php echo $block->getChildHtml('recaptcha'); ?>
   </div>
   <div>
       <button type="submit">Submit</button>
   </div>
   <input name="form_key" type="hidden" value="<?php echo $block->getFormKey(); ?>" />
</form>

Now we can see Google reCAPTCHA on our custom form.

Step 4. Display Google reCAPTCHA in the Magento 2 Custom Form

Step 5. Build a Controller to Handle Custom Form Submissions

Create file app/code/Vendor/CustomFormRecaptcha/Controller/Index/Post.php
<?php


namespace Vendor\CustomFormRecaptcha\Controller\Index;


use Magento\Framework\App\Action\Action;
use Magento\Framework\App\Action\HttpPostActionInterface;
use Magento\Framework\Controller\Result\RedirectFactory;
use Magento\Framework\Message\ManagerInterface;
use Magento\Framework\Exception\LocalizedException;


class Post extends Action implements HttpPostActionInterface
{
   protected $resultRedirectFactory;
   protected $messageManager;


   public function __construct(
       \Magento\Framework\App\Action\Context $context,
       RedirectFactory $resultRedirectFactory,
       ManagerInterface $messageManager
   ) {
       parent::__construct($context);
       $this->resultRedirectFactory = $resultRedirectFactory;
       $this->messageManager = $messageManager;
   }


   public function execute()
   {
       $postData = $this->getRequest()->getPostValue();


       if ($postData) {
           try {
               $this->_eventManager->dispatch('customformrecaptcha_validate_recaptcha', ['request' => $this->getRequest()]);
               // Save data
               $this->messageManager->addSuccessMessage(__('Form submitted successfully.'));
           } catch (LocalizedException $e) {
               $this->messageManager->addErrorMessage($e->getMessage());
           } catch (\Exception) {
               $this->messageManager->addErrorMessage(__('An error occurred: %1', $e->getMessage()));
           }
       } else {
           $this->messageManager->addErrorMessage(__('No data received.'));
       }


       return $this->resultRedirectFactory->create()->setPath('*/*/');
   }
}

Step 6. Create an Observer to Validate Google reCAPTCHA for the Custom Form in Magento 2

Create file: app/code/CustomFormRecaptcha/Module/etc/frontend/events.xml
<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework/Event/etc/events.xsd">
   <event name="customformrecaptcha_validate_recaptcha">
       <observer name="validate_recaptcha" instance="Vendor\CustomFormRecaptcha\Observer\ValidateRecaptcha" />
   </event>
</config>
Create file: app/code/Vendor/CustomFormRecaptcha/Observer/ValidateRecaptcha.php

<?php


namespace Vendor\CustomFormRecaptcha\Observer;


use Magento\Framework\Event\Observer;
use Magento\Framework\Event\ObserverInterface;
use Magento\Framework\Exception\InputException;
use Magento\Framework\Exception\LocalizedException;
use Magento\Framework\ObjectManagerInterface;
use Magento\ReCaptchaUi\Model\IsCaptchaEnabledInterface;
class ValidateRecaptcha implements ObserverInterface
{
   /**
    * @var IsCaptchaEnabledInterface
    */
   private $isCaptchaEnabled;


   /**
    * @var ObjectManagerInterface
    */
   private $objectManager;


   public function __construct(
       IsCaptchaEnabledInterface $isCaptchaEnabled,
       ObjectManagerInterface $objectManager,
   ) {
       $this->isCaptchaEnabled = $isCaptchaEnabled;
       $this->objectManager = $objectManager;
   }


   /**
    * @throws InputException
    */
   public function execute(Observer $observer)
   {
       $key = 'customformrecaptcha';
       $request = $observer->getRequest();
       if ($this->isCaptchaEnabled->isCaptchaEnabledFor($key)) {


           $validationConfigResolver = $this->objectManager->get(
               \Magento\ReCaptchaUi\Model\ValidationConfigResolverInterface::class
           );


           $captchaResponseResolver = $this->objectManager->get(
               \Magento\ReCaptchaUi\Model\CaptchaResponseResolverInterface::class
           );


           $captchaValidator = $this->objectManager->get(
               \Magento\ReCaptchaValidationApi\Api\ValidatorInterface::class
           );


           $validationConfig = $validationConfigResolver->get($key);


           try {
               $reCaptchaResponse = $captchaResponseResolver->resolve($request);
           } catch (InputException $e) {
               throw new LocalizedException(__('Please complete the reCAPTCHA validation.'));
           }


           $validationResult = $captchaValidator->isValid($reCaptchaResponse, $validationConfig);
           if (false === $validationResult->isValid()) {
               throw new LocalizedException(__('reCAPTCHA validation failed. Please try again.'));
           }
       }
   }
}

Conclusion

By taking these simple steps, you improve not just the functionality of your website but also the confidence your customers have in your brand. Keep optimizing and securing your store to provide the best possible experience for your users.

About The Author: Volodymyr Holovatskiy

Magento 2 developer passionate about creating efficient and functional ecommerce solutions. Loves skiing and hiking in the mountains, finding inspiration for new ideas and solutions in web development. View more posts