Oh snap! You are using an old version of browser. Update your browser to get new awesome features. Click for more details.

Magento 2 add google recaptcha in custom form


Add recaptcha js file in your xml
Path: app/code/Name_space/Module_name/view/frontend/layout

<?xml version="1.0"?>
<page layout="1column" 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>


Add recaptcha code in your phtml file
Path: app/code/Name_space/Module_name/view/frontend/templates

First add onsubmit event in form, It's validate recaptcha field via javascript.

<form class="test-form"
      action="<?php echo $block->getFormAction(); ?>"
      id="test_form"
      method="post"
      enctype="multipart/form-data"
      onsubmit="return capatcheFunction()"
      data-hasrequired="<?php echo __('* Required Fields') ?>"
      data-mage-init='{"validation":{}}'>



Add recaptcha field in form

<div class="field recaptcha">
    <div class="g-recaptcha" name="recaptcha" id="recaptcha" data-sitekey="Put Your Google Captcha Site Key Here"></div>
</div>


Add JavaScript function after form

<script type="text/javascript">
function capatcheFunction() {
    var exists = document.getElementById("g-recaptcha-response");
    if(exists == null){

    } else{
        var check = document.getElementById("g-recaptcha-response").value;
        if(check=='' || check == null){
            document.getElementById("recaptcha").style.border = "1px solid #ea0e0e";
            return false;
        }
        else{
            document.getElementById("recaptcha").style.border = "none";
            return true;
        }
    }
}
</script>


Full code example is below

<div>
    <form class="form-rma"
          action="<?php echo $block->getFormAction(); ?>"
          id="rma_form"
          method="post"
          enctype="multipart/form-data"
          onsubmit="return capatcheFunction()"
          data-hasrequired="<?php echo __('* Required Fields') ?>"
          data-mage-init='{"validation":{}}'>

        <h3><?php echo __('Testing Form')?></h3>
        <fieldset class="fieldset rma-info">
            <div class="field name required">
                <label class="label" for="customer_name"><?php echo __('Name')?></label>
                <input name="customer_name" id="customer_name" class="input-text" type="text" data-validate="{required:true}" />
            </div>

            <div class="field email required">
                <label class="label" for="email"><?php echo __('Email')?></label>
                <input name="email" id="email" class="input-text" type="email" data-validate="{required:true, 'validate-email':true}" />
            </div>

            <div class="field phone required">
                <label class="label" for="phone"><?php echo __('Phone Number') ?></label>
                <input name="phone" id="phone" class="input-text" type="text" data-validate="{required:true}" />
            </div>

            <div class="field address required">
                <label class="label" for="address"><?php echo __('Address') ?></label>
                <input name="address" id="address" class="input-text" type="text" data-validate="{required:true}" />
            </div>

            <div class="field recaptcha">
                <div class="g-recaptcha" name="recaptcha" id="recaptcha" data-sitekey="Put Your Google Captcha Site Key Here"></div>
            </div>
        </fieldset>

        <div class="actions-toolbar">
            <div class="primary">
                <button type="submit" title="<?php echo __('Submit') ?>" class="action submit primary">
                    <span><?php echo __('Submit') ?></span>
                </button>
            </div>
        </div>
    </form>
</div>
<script type="text/javascript">
function capatcheFunction() {
    var exists = document.getElementById("g-recaptcha-response");
    if(exists == null){

    } else{
        var check = document.getElementById("g-recaptcha-response").value;
        if(check=='' || check == null){
            document.getElementById("recaptcha").style.border = "1px solid #ea0e0e";
            return false;
        }
        else{
            document.getElementById("recaptcha").style.border = "none";
            return true;
        }
    }
}
</script>


Validate recaptcha in controller
Path: app/code/Name_space/Module_name/Controller/Index

public function execute()
{
    $post = $this->getRequest()->getParams();
    $request = $this->getRequest();
    $remoteAddress = new \Magento\Framework\Http\PhpEnvironment\RemoteAddress($this->getRequest());
    $visitorIp = $remoteAddress->getRemoteAddress();

    $storeScope = \Magento\Store\Model\ScopeInterface::SCOPE_STORE;
    $secret = 'Put Google Captcha Secret Key Here';
    $response = null;
    $path = 'https://www.google.com/recaptcha/api/siteverify?';
    $secretKey = $secret;
    $response = $post["g-recaptcha-response"];
    $remoteIp = $visitorIp;

    $response = file_get_contents($path."secret=$secretKey&response=$response&remoteip=$remoteIp");
    $answers = json_decode($response, true);
    if (trim($answers['success']) != true) {
        echo 'Invalid captcha please enter the valid captcha';exit;
    } else {
    echo 'Captcha is valid';exit;
    }
}

5 comments

  1. India Data Entry Services is a trusted Professional Magento Product Data Entry Services provider to e-commerce companies and platforms. Be it e-commerce product cataloguing or Product Upload Services, since our inception in 2010, we are striving to get all best o cater global organizations. The company is strategically positioned to support big or small e-Commerce Stores working on various domains such as fashion apparels, crockery items, furniture, accessories, shoes.

    ReplyDelete
  2. We are really grateful for your blog post. You will find a lot of approaches after visiting your post. I was exactly searching for. Thanks for such post and please keep it up. Great work. call center data entry

    ReplyDelete
  3. Hi, It works.
    Really it is wonderful script.

    ReplyDelete
  4. Today, I was just browsing along and came upon your blog. keep posting. captcha app

    ReplyDelete
  5. This comment has been removed by the author.

    ReplyDelete