Add Recaptcha in Custom From Magento 2.4

Integrate Magepack with Magento/Adobe commerce

This post is related to add Google Recaptcha to Custom Form in Magento 2.4.X

Module Name: Integerbyte_MyRecaptcha

Files List:

app/code/Integerbyte/MyRecaptcha/registration.php
app/code/Integerbyte/MyRecaptcha/etc/module.xml
app/code/Integerbyte/MyRecaptcha/etc/adminhtml/system.xml
app/code/Integerbyte/MyRecaptcha/etc/config.xml
app/code/Integerbyte/MyRecaptcha/etc/frontend/routes.xml
app/code/Integerbyte/MyRecaptcha/etc/frontend/events.xml
app/code/Integerbyte/MyRecaptcha/Observer/RecapchaObserver.php
app/code/Integerbyte/MyRecaptcha/Controller/Index/Index.php
app/code/Integerbyte/MyRecaptcha/Controller/Index/Save.php
app/code/Integerbyte/MyRecaptcha/view/frontend/layout/myrecaptcha_index_index.xml
app/code/Integerbyte/MyRecaptcha/view/frontend/templates/form.phtml

1. Module Registarion file

app/code/Integerbyte/MyRecaptcha/registration.php

<?php
\Magento\Framework\Component\ComponentRegistrar::register(
\Magento\Framework\Component\ComponentRegistrar::MODULE,
 'Integerbyte_MyRecaptcha',
 __DIR__
);

2. Create module.xml file

app/code/Integerbyte/MyRecaptcha/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="Integerbyte_MyRecaptcha" setup_version="1.0.0">
  </module>
</config>
    

3. Create system.xml file

app/code/Integerbyte/MyRecaptcha/etc/adminhtml/system.xml
Note: section id recaptcha_frontend and group id type_for are static, you can change ‘customform’ acoording to you

This configuration show in Admin -> Stores -> Configuration ->Security tab

<?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="customform" translate="label" type="select" sortOrder="140" showInDefault="1"
showInWebsite="1" showInStore="0" canRestore="1">
     <label>Enable for Custom Form</label>
     <source_model>Magento\ReCaptchaAdminUi\Model\OptionSource\Type</source_model>
    </field>
   </group>
  </section>
 </system>
</config>

4. Create config.xml file

app/code/Integerbyte/MyRecaptcha/etc/config.xml
Note: recaptcha_frontend and type_for are static

<?xml version="1.0"?>

<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:module:Magento_Store:etc/config.xsd">
<default>
 <recaptcha_frontend>
   <type_for>
     <customform/>
   </type_for>
 </recaptcha_frontend>
</default>
</config>

5. Create routes.xml file

app/code/Integerbyte/MyRecaptcha/etc/frontend/routes.xml

<?xml version="1.0" ?>

<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:App/etc/routes.xsd">
<router id="standard">
  <route frontName="myrecaptcha" id="myrecaptcha">
     <module name="Integerbyte_MyRecaptcha"/>
  </route>
</router>
</config>

6. Create events.xml file

app/code/Integerbyte/MyRecaptcha/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="controller_action_predispatch_myrecaptcha_index_save">
    <observer name="recaptcha_demo_form" instance="Integerbyte\MyRecaptcha\Observer\RecapchaObserver"/>
</event>
</config>

7. Create RecapchaObserver file

app/code/Integerbyte/MyRecaptcha/Observer/RecapchaObserver.php
Note: here key value is ‘customform’

<?php
declare(strict_types=1);
namespace Integerbyte\MyRecaptcha\Observer;

use Magento\Framework\App\Action\Action;
use Magento\Framework\Event\Observer;
use Magento\Framework\Event\ObserverInterface;
use Magento\Framework\Exception\LocalizedException;
use Magento\Framework\UrlInterface;
use Magento\ReCaptchaUi\Model\IsCaptchaEnabledInterface;
use Magento\ReCaptchaUi\Model\RequestHandlerInterface;
use Magento\Framework\App\Response\RedirectInterface;

class RecapchaObserver implements ObserverInterface
{
protected $redirect;
private $url;
private $isCaptchaEnabled;
private $requestHandler;

public function __construct(
UrlInterface $url,
IsCaptchaEnabledInterface $isCaptchaEnabled,
RequestHandlerInterface $requestHandler,
RedirectInterface $redirect
) {
  $this->url = $url;
  $this->isCaptchaEnabled = $isCaptchaEnabled;
  $this->requestHandler = $requestHandler;
  $this->redirect = $redirect;
}

public function execute(Observer $observer): void
{
  $key = 'customform';
  if ($this->isCaptchaEnabled->isCaptchaEnabledFor($key)) { 
  $controller = $observer->getControllerAction();
  $request = $controller->getRequest();
  $response = $controller->getResponse();
  $redirectOnFailureUrl = $this->redirect->getRedirectUrl();
  $this->requestHandler->execute($key, $request, $response, $redirectOnFailureUrl);
}
}
}

8. Create Index controller file

app/code/Integerbyte/MyRecaptcha/Controller/Index/Index.php

<?php
namespace Integerbyte\MyRecaptcha\Controller\Index;
use Magento\Customer\Model\Session;
use Magento\Framework\App\Action\Action;
use Magento\Framework\App\Action\Context;
use Magento\Framework\App\RequestInterface;
use Magento\Framework\View\Result\PageFactory;

class Index extends \Magento\Framework\App\Action\Action
{
/**
* @var PageFactory
*/
protected $resultPageFactory;
/**
* @var Session
*/
protected $customerSession;
/**
* @param Context $context
* @param PageFactory $resultPageFactory
* @param Session $customerSession
*/
public function __construct(
Context $context,
PageFactory $resultPageFactory,
Session $customerSession
) {
  $this->resultPageFactory = $resultPageFactory;
  $this->customerSession = $customerSession;
  parent::__construct($context);
}

 public function execute()
 {
   $resultPage = $this->resultPageFactory->create();
   $resultPage->getConfig()->getTitle()->set(__('My custom form'));
   return $resultPage;
 }
}

9. Create Save controller file

app/code/Integerbyte/MyRecaptcha/Controller/Index/Save.php

<?php
namespace Integerbyte\MyRecaptcha\Controller\Index;
class Save extends \Magento\Framework\App\Action\Action
{
protected $_request;

public function __construct(
\Magento\Framework\App\Action\Context $context,
\Magento\Framework\App\Request\Http $request
) {
$this->_request = $request;
parent::__construct($context);
}
public function execute()
{ 
$formData = $this->_request->getPostValue(); 
    // your logic 
    die();
} 
}

10. Create layout file

app/code/Integerbyte/MyRecaptcha/view/frontend/layout/myrecaptcha_index_index.xml
Note: ifconfig is check module is enable or disble

<?xml version="1.0"?>

<page xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../../../../../../../lib/internal/Magento/Framework/View/Layout/etc/page_configuration.xsd">

<body>
<referenceContainer name="content">
<block class="Magento\Framework\View\Element\Template" name="demo.for.recaptcha"
template="Integerbyte_MyRecaptcha::form.phtml" >

<container name="form.additional.info.demo.for.recaptcha">
<block class="Magento\ReCaptchaUi\Block\ReCaptcha" name="recaptcha" after="-"
template="Magento_ReCaptchaFrontendUi::recaptcha.phtml"
ifconfig="recaptcha_frontend/type_for/customform">
    <arguments>
       <argument name="recaptcha_for" xsi:type="string">customform</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>
</container>
</block>
</referenceContainer>
</body>
</page>

11. Create template file

app/code/Integerbyte/MyRecaptcha/view/frontend/templates/form.phtml
Add childhtml ‘form.additional.info.demo.for.recaptcha’

<?php $form_url = $this->getUrl('myrecaptcha/index/save'); ?>
<div id="myrecaptcha-div">
<div class="modal-body">
<form class="form" action="<?= $block->escapeHtmlAttr($form_url) ?>"
id="demo-recaptcha-form" method="post" enctype='multipart/form-data' >
<input type="hidden" name="product_id" >
<fieldset class="fieldset">
<div class="field required">
<label for="user_name" class="label">
<span><?= $block->escapeHtml('Name:') ?></span>
</label>
   <div class="control">
       <input type="text" name="customer_name" title="<?= $block->escapeHtml('Name') ?>"
class="input-text" data-validate="{required:true}"> </div>
   </div>
  <div class="field required">
    <label for="user_name" class="label">
   <span><?= $block->escapeHtml('E-mail:') ?></span>
  </label>
  <div class="control">
      <input type="email" name="customer_email" title="<?= $block->escapeHtml('E-mail') ?>"
     class="input-text" data-validate="{required:true, 'validate-email':true}">
</div>
</div>
<?= $block->getChildHtml('form.additional.info.demo.for.recaptcha') ?>
</fieldset>
<div class="actions-toolbar">
<div class="primary">
       <button type="submit" class="action submit primary " title="<?= $block->escapeHtml('Submit') ?>">
<span>
      <?= $block->escapeHtml('Submit') ?>
</span>
</button>
</div>
</div>
</form>
     <script type="text/x-magento-init">
       {
         "#demo-recaptcha-form": {
         "validation": {}
        }
       }
      </script>
</div>
</div>

Note:- You must have Recaptcha key which put on Configuration -> Security -> Google reCAPTCHA Storefront And you must enable it below this configuration at Storefront section Otherwise Recaptcha is not show.

The Above code tested with Magento 2.4.3 version

Back To Top