How to attach native captcha / Google recaptcha in custom form of Magento 2 module

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

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

First call the Google recaptha 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 in the bottom)

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

Now you can capable to observe 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 in the following sample codes.

Last Update: February 26, 2019  

February 17, 2018   395   Nandini R    Magento2    
Total 1 Votes:
0

Tell us how can we improve this post?

+ = Verify Human or Spambot ?

Leave a Reply

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

Facebook
Twitter
INSTAGRAM
LinkedIn