How to attach Google reCAPTCHA in custom form of Magento 2 module?

In this blog, the following steps help you to connect native Captcha / Google reCAPTCHA in the custom form of the Magento 2 module.

For attaching Google reCAPTCHA in custom form, you have to get the site key  and secret key  for your domain from https://www.google.com/recaptcha/intro/index.html

Get build your Magento marketplace with a simple installation, check here!!!

Attach Google reCAPTCHA in custom form of Magento 2 module

Google recaptcha in Magento 2

First, call the Google reCAPTCHA JavaScript file in your header. Fix the reCAPTCHA Js in your individual layout file as coded mentioned below:

<page xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:View/Layout/etc/page_configuration.xsd">

<head>

<script src="https://www.google.com/recaptcha/api.js" src_type="url" />

</head>

.....

.....

</page>

Then add the below code in your custom form before the end of the </form> tag. (to display captcha at the bottom)

<div class="g-recaptcha" data-sitekey="<--your site key-->"></div>

Google reCAPTCHA sync

Now you can be capable to observe the captcha shown in your form. But the consumer response is not confirmed yet. To build it, perform the following code changes in your Save action controller.

namespace Jay\SampleModule\Controller;

class Save extends \Magento\Framework\App\Action\Action
{
/**
* @var Google reCaptcha Options
*/
private static $_siteVerifyUrl = "https://www.google.com/recaptcha/api/siteverify?";
private $_secret;
private static $_version = "php_1.0";
/**
* Save Form Data
*
* @return array
*/
public function execute()
{
$captcha = $this->getRequest()->getParam('g-recaptcha-response');
$secret = "<--your secret key-->"; //Replace with your secret key
$response = null;
$path = self::$_siteVerifyUrl;
$dataC = array (
'secret' => $secret,
'remoteip' => $_SERVER["REMOTE_ADDR"],
'v' => self::$_version,
'response' => $captcha
);
$req = "";
foreach ($dataC as $key => $value) {
 $req .= $key . '=' . urlencode(stripslashes($value)) . '&';
}
// Cut the last '&'
$req = substr($req, 0, strlen($req)-1);
$response = file_get_contents($path . $req);
$answers = json_decode($response, true);
if(trim($answers ['success']) == true) {
 // Captcha Validated
 // Save Form Data
}else{
 // Dispay Captcha Error
}
}
}

Assure that you have changed the site key and secret key from the above-mentioned sample codes. Now you can witness the Google reCAPTCHA got integrated with Magento.

So if you’re looking to build a Magento store or have any Magento development related queries? click here.


Posted

in

, ,

by

Comments

Leave a Reply

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