cancel
Showing results for 
Search instead for 
Did you mean: 

How to add native captcha / google recaptcha in custom form of magento 2 module?

SOLVED

How to add native captcha / google recaptcha in custom form of magento 2 module?

How to add native captcha / google recaptcha in custom form of magento 2 module?

I have  to implement captcha in my custom module form having magento version 2.0.0, which related files are need to customize?

1 ACCEPTED SOLUTION

Accepted Solutions

Re: How to add native captcha / google recaptcha in custom form of magento 2 module?

For adding google recaptcha into your custom form, you have to get the 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. Add the recaptcha js in your respective layout file as coded 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 end of </form> tag. (to display captcha in bottom)

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

Now you can able to see captcha displayed in your form. But the user response is not verified yet.To make it happen, do below 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
}
}
}

Make sure you have replaced the site key and secret key in the above sample codes.

View solution in original post

5 REPLIES 5

Re: How to add native captcha / google recaptcha in custom form of magento 2 module?

For adding google recaptcha into your custom form, you have to get the 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. Add the recaptcha js in your respective layout file as coded 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 end of </form> tag. (to display captcha in bottom)

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

Now you can able to see captcha displayed in your form. But the user response is not verified yet.To make it happen, do below 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
}
}
}

Make sure you have replaced the site key and secret key in the above sample codes.

Re: How to add native captcha / google recaptcha in custom form of magento 2 module?

Thanks jaijune93, Smiley Happy

Re: How to add native captcha / google recaptcha in custom form of magento 2 module?

Wher's the default Save action controller.

/public_html/vendor/magento/module-contact/Controller/Index

and cant find ani

class Save extends \Magento\Framework\App\Action\Action{

in thows folders

Re: How to add native captcha / google recaptcha in custom form of magento 2 module?

@Jay Jay

i just adding @Jay Jay answer to  curl way to retrieve the  verify response

    $secretKey = "yourKeyHere";
    $client_captcha_response=$this->getRequest()->getParam('g-recaptcha-response');
    $user_ip = $_SERVER['REMOTE_ADDR']; //get current user ip
    $ch = curl_init();

        // set url
        curl_setopt($ch, CURLOPT_URL, "https://www.google.com/recaptcha/api/siteverify?secret=$secretKey&response=$client_captcha_response&remoteip=$user_ip");

        //return the transfer as a string
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);

        // $output contains the output string
        $output = curl_exec($ch);

        $captcha_verify_decoded=(json_decode($output));

        // close curl resource to free up system resources
        curl_close($ch);
   
     if(!$captcha_verify_decoded->success):
        //do your logic here
      endif;
Find helpful ? Consider Giving Kudos to this post.
Problem solved? Click Accept as Solution!"
Qaisar Satti

Re: How to add native captcha / google recaptcha in custom form of magento 2 module?

Hello @Jalindar

Here is the extension

https://magecomp.com/magento-2-google-recaptcha.html

  • Option to choose between light and dark theme.
  • You can enable ReCaptcha on:
    • Contact Us page
    • Customer Registration
    • Product Review
    • Forgot Password page
    • Checkout Registration
    • Newsletter Subscription
  • Now, extension can also work with Non-JavaScript browser or browser with disabled JavaScript. 
  • The extension features to verify user response by using server-side validation. 

 

Was my answer helpful? You can accept it as a solution.
175+ Professional Extensions for M1 & M2
Need a developer?Just visit Contact Us Now