2

Magento 2.4

How to add Google Recaptcha in Custom Form ?

4
  • check this link - meetanshi.com/blog/add-google-recaptcha-to-magento-2 Aug 23 '20 at 5:06
  • @MohitPatel This is not right way to add Google Recaptcha in Custom Form. I am looking for a Magento's way. how Magento use this. That Method i want to use.
    – Msquare
    Aug 24 '20 at 8:45
  • You want to using custom module?? Aug 24 '20 at 17:46
  • Yes i i have Custom Module and Custom Form.
    – Msquare
    Aug 25 '20 at 5:32
4

Module Name : VendoreName_DemoRecaptcha

app/code/VendoreName/DemoRecaptcha

registration.php

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

app/code/VendoreName/DemoRecaptcha/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="VendoreName_DemoRecaptcha" setup_version="1.0.0">
    </module>
</config>

app/code/VendoreName/DemoRecaptcha/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="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>

app/code/VendoreName/DemoRecaptcha/etc

config.xml

<?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>

app/code/VendoreName/DemoRecaptcha/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="demorecaptcha" id="demorecaptcha">
            <module name="VendoreName_DemoRecaptcha"/>
        </route>
    </router>
</config>

app/code/VendoreName/DemoRecaptcha/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_demorecaptcha_index_save">
        <observer name="recaptcha_demo_form" instance="VendoreName\DemoRecaptcha\Observer\RecapchaFormObserver"/>
    </event>
</config>

app/code/VendoreName/DemoRecaptcha/Observer

RecapchaFormObserver.php

<?php
declare(strict_types=1);

namespace VendoreName\DemoRecaptcha\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 RecapchaFormObserver 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)) {
            /** @var Action $controller */
            $controller = $observer->getControllerAction();
            $request = $controller->getRequest();
            $response = $controller->getResponse();
            $redirectOnFailureUrl = $this->redirect->getRedirectUrl();
            $this->requestHandler->execute($key, $request, $response, $redirectOnFailureUrl);
        }
    }
}

app/code/VendoreName/DemoRecaptcha/Controller/Index

Index.php

<?php

namespace VendoreName\DemoRecaptcha\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(__('Recaptcha Demo'));
        return $resultPage;
    }
}

app/code/VendoreName/DemoRecaptcha/Controller/Index

Save.php

<?php

namespace VendoreName\DemoRecaptcha\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()
    {
        echo "<pre>";
        $data = $this->_request->getPostValue();
        print_r($data);
        echo "save you data here";
        exit();
    } // main Executtion function
}

app/code/VendoreName/DemoRecaptcha/view/frontend/layout

demorecaptcha_index_index.xml

<?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="VendoreName_DemoRecaptcha::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>

app/code/VendoreName/DemoRecaptcha/view/frontend/templates

form.phtml

<?php

$form_url = $this->getUrl('demorecaptcha/index/save');
?>
<div id="modal-call-for-price">
    <div class="modal-body">
        <form class="form"
            action="<?= $block->escapeHtmlAttr($form_url) ?>"
            id="demo-recaptcha-form"
            method="post"
            enctype='multipart/form-data'
            autocomplete="off">
            <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.

4
  • app/code/VendoreName/DemoRecaptcha/view/frontend/layout/form.phtml should be app/code/VendoreName/DemoRecaptcha/view/frontend/templates/form.phtml rest seems good will check to confirm output Apr 5 '21 at 13:02
  • @zuberbandi Thanks i update answer.
    – Msquare
    Apr 6 '21 at 5:20
  • @Msquare i have followed the same way for adding a recpatcha in my custom form and ir's working fine for recapcta V2 but facing the issue in recapcha invisible V3 .. can you please help ?? Nov 19 '21 at 4:59
  • Please ask a new question with your code and what is your requirement. and share your question link.
    – Msquare
    Nov 19 '21 at 8:29

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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