How to combine recaptcha in Magento 2 contact page

Here I will discuss How to combine reCaptcha into contact page. So the following steps describes you to combine reCaptcha in Magento 2 contact page

Step 1: Build Module.xml [SR/ReCaptcha/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="SR_ReCaptcha" setup_version="2.1.0">
 </module>
</config>

Step 2:Build registration.php [SR/ReCaptcha/registration.php]

\Magento\Framework\Component\ComponentRegistrar::register(
 \Magento\Framework\Component\ComponentRegistrar::MODULE,
 'SR_ReCaptcha',
 __DIR__
);

Step 3: Build system configuration [SR/ReCaptcha/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>
 <tab id="sr_reCaptcha">
 Re Captcha
 </tab>
 <section id="reCaptcha" type="text" showInDefault="1">
 <label>Re Captcha Configuration</label>
 <tab>sr_reCaptcha</tab>
 <resource>SR_ReCaptcha::reCaptcha</resource>
 <group id="settings" type="text" sortOrder="10" showInDefault="1" showInWebsite="1" showInStore="1" canRestore="1">
 <label>Extension Settings</label>
 <field id="enabled" translate="label" type="select" sortOrder="10" showInDefault="1" showInWebsite="1" showInStore="1" canRestore="1">
 <label>Enabled</label>
 <source_model>Magento\Config\Model\Config\Source\Yesno</source_model>
 </field>
 <field id="site_key" translate="label" type="text" sortOrder="20" showInDefault="1" showInWebsite="1" showInStore="1" canRestore="1">
 <label>Site Key</label>
 </field>
 <field id="secret_key" translate="label" type="text" sortOrder="30" showInDefault="1" showInWebsite="1" showInStore="1" canRestore="1">
 <label>Secret Key</label>
 </field>
 </group>
 </section>
 </system>
</config>

Step 4: Allocate default value for system configuration [SR/ReCaptcha/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>
 <settings>
 <enabled>0</enabled>
 <site_key></site_key>
 <secret_key></secret_key>
 </settings>
 </reCaptcha>
 </default>
</config>

Step 5: Build helper [SR/ReCaptcha/Helper/Data.php]

use Magento\Store\Model\ScopeInterface;

class Data extends \Magento\Framework\App\Helper\AbstractHelper
{
 const MODULE_ENABLED = 'reCaptcha/settings/enabled';
 const SITE_KEY = 'reCaptcha/settings/site_key';
 const SECRET_KEY = 'reCaptcha/settings/secret_key';

/**
 * @var \Magento\Store\Model\StoreManagerInterface
 */
 protected $storeManager;

/**
 * @var \Magento\Framework\App\Config\ScopeConfigInterface
 */
 protected $scopeConfig;

/**
 * Data constructor.
 *
 * @param \Magento\Framework\App\Helper\Context $context
 * @param \Magento\Store\Model\StoreManagerInterface $storeManager
 * @param \Magento\Framework\App\Config\ScopeConfigInterface $scopeConfig
 */
 public function __construct(
 \Magento\Framework\App\Helper\Context $context,
 \Magento\Store\Model\StoreManagerInterface $storeManager,
 \Magento\Framework\App\Config\ScopeConfigInterface $scopeConfig
 ) {
 parent::__construct($context);
 $this->storeManager = $storeManager;
 $this->scopeConfig = $scopeConfig;
 }

/**
 * Is the module enabled in configuration.
 *
 * @return bool
 */
 public function isEnabled()
 {
 return $this->getStoreConfig(self::MODULE_ENABLED);
 }

/**
 * The recaptcha site key.
 *
 *
 * @return string
 */
 public function getSiteKey()
 {
 return $this->getStoreConfig(self::SITE_KEY);
 }

/**
 * The recaptcha secret key.
 *
 *
 * @return string
 */
 public function getSecretKey()
 {
 return $this->getStoreConfig(self::SECRET_KEY);
 }

public function getStoreConfig($path)
 {
 $store = $this->getStoreId();
 return $this->scopeConfig->getValue($path, ScopeInterface::SCOPE_STORE, $store);
 }

public function getStoreId()
 {
 return $this->storeManager->getStore()->getStoreId();
 }
}

Step 6: Describe configuration [SR/ReCaptcha/view/frontend/layout/contact_index_index.xml]

<?xml version="1.0"?>
<page xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" layout="1column" xsi:noNamespaceSchemaLocation="urn:magento:framework:View/Layout/etc/page_configuration.xsd">
 <body>
 <referenceContainer name="form.additional.info">
 <block class="SR\ReCaptcha\Block\ReCaptcha" name="recaptchaForm" template="SR_ReCaptcha::captcha.phtml" after="-" cacheable="false" />
 </referenceContainer>
 </body>
</page>

Step 7: Build phtml file [SR/ReCaptcha/view/frontend/templates/captcha.phtml]

<?php /** @var $block \SR\ReCaptcha\Block\ReCaptcha */ ?>
<?php if ($block->isEnabled()): ?>
 https://www.google.com/recaptcha/api.js

getSiteKey();?>==">

<?php endif; ?>

Step 8:Build a plugin [SR/ReCaptcha/etc/frontend/di.xml]

<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:ObjectManager/etc/config.xsd">
 <type name="Magento\Contact\Controller\Index\Post">
 <plugin name="reCaptcha_Post_Action" type="SR\ReCaptcha\Plugin\Contact\Controller\Index\Post" sortOrder="1"/>
 </type>
</config>

Step 9: Build a plugin class [SR/ReCaptcha/Plugin/Contact/Controller/Index/Post.php]

namespace SR\ReCaptcha\Plugin\Contact\Controller\Index;
class Post
{
 /**
 * @var \Magento\Framework\Controller\Result\RedirectFactory
 */
 protected $resultRedirectFactory;

/**
 * @var \Magento\Framework\Message\ManagerInterface
 */
 protected $messageManager;

/**
 * @var \SR\ReCaptcha\Helper\Data $dataHelper
 */
 protected $dataHelper;

/**
 * @param \Magento\Framework\Controller\Result\RedirectFactory $resultRedirectFactory
 * @param \Magento\Framework\Message\ManagerInterface $messageManager
 * @param \SR\ReCaptcha\Helper\Data $dataHelper
 */
 public function __construct(
 \Magento\Framework\Controller\Result\RedirectFactory $resultRedirectFactory,
 \Magento\Framework\Message\ManagerInterface $messageManager,
 \SR\ReCaptcha\Helper\Data $dataHelper
 ) {
 $this->resultRedirectFactory = $resultRedirectFactory;
 $this->messageManager = $messageManager;
 $this->dataHelper = $dataHelper;
 }

public function aroundExecute(
 \Magento\Contact\Controller\Index\Post $subject,
 \Closure $proceed
 ) {
 if($this->dataHelper->isEnabled()) {
 $recaptcha_response_field = $subject->getRequest()->getPost('g-recaptcha-response');
 if($recaptcha_response_field) {
 $secretKey = $this->dataHelper->getSecretKey();
 $response = file_get_contents("https://www.google.com/recaptcha/api/siteverify?secret=".$secretKey."&response=".$recaptcha_response_field."&remoteip=".$_SERVER['REMOTE_ADDR']);
 $result = json_decode($response, true);
 if(isset($result['success']) && ($result['success'])) {
 return $proceed();
 } else {
 $resultRedirect = $this->resultRedirectFactory->create();
 $this->messageManager->addError(
 __('There was an error with the recaptcha code, please try again.')
 );
 $resultRedirect->setPath('contact/index');
 return $resultRedirect;
 }
 } else {
 $this->messageManager->addError(
 __('There was an error with the recaptcha code, please try again.')
 );
 $resultRedirect = $this->resultRedirectFactory->create();
 $resultRedirect->setPath('contact/index/index');
 return $resultRedirect;
 }
 }

return $proceed();
 }
}

The following steps show you how to combine recaptcha in Magento 2 contact page


Posted

in

by

Tags:

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *