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

In this blog, the following steps help 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

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="" xsi:noNamespaceSchemaLocation="urn:magento:framework:View/Layout/etc/page_configuration.xsd">


<script src="" src_type="url" />





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 = "";
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
 // Dispay Captcha Error

Assure that you have changed the site key and secret key in the following sample codes.

Last Update: October 9, 2019  

February 17, 2018   958   Nandini Ramachandran    Magento2    
Total 1 Votes:

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 *