Magento – Magento 2.2.5 How to add google captcha to newsletter form without use any third party extension

googlemagento-2.2.5newsletterrecaptcha

There is so many extension available for Google Captcha implement to Magento 2 newsletter form or any other form.

But i want to add Google Captcha from scratch, without using any third party extension.

Could anyone help or give guidance how to achieve this things.

Edit :(What i try)


I add code to below file to get google captcha. google captcha is showing but newsletter form stop working and give error like Something went wrong with the subscription

app/design/frontend/Rocketbazaar/tgbl/Magento_Newsletter/templates/subscribe.phtml

<form class="form subscribe"
        novalidate
        action="<?php /* @escapeNotVerified */ echo $block->getFormActionUrl() ?>"
        method="post"
        data-mage-init='{"validation": {"errorClass": "mage-error"}}'
        id="newsletter-validate-detail">
        <div class="field newsletter">
            <label class="label" for="newsletter"><span><?php /* @escapeNotVerified */ echo __('Sign Up for Our Newsletter:') ?></span></label>
            <div class="control">
                <input name="email" type="email" id="newsletter"
                            placeholder="<?php /* @escapeNotVerified */ echo __('Enter your email address') ?>"
                            data-validate="{required:true, 'validate-email':true}"/>
            </div>
        </div>
        <div class="actions">
            <button class="action subscribe primary" title="<?php /* @escapeNotVerified */ echo __('Yes please!') ?>" type="submit">
                <span><?php /* @escapeNotVerified */ echo __('Yes please!') ?></span>
            </button>
        </div>
        <div class="recaptcha" style="overflow:hidden;position:relative;">
            <input type="checkbox" id="recaptcha-verification-1" name="recaptcha-verification-1" value="" class="hide required-entry" style="visibility:hidden;position:absolute;left:-1000000px" />
            <div id="recaptcha-1"></div>
        </div>
    </form>
<script type="text/javascript">
var onloadCallback = function() {
    grecaptcha.render('recaptcha-1', {
        'sitekey': "6LeIxAcTAAAAAJcZVRqyHh71UMIEGNQ_MXjiZKhI",
        'theme': "light",
        'callback': function(response) {
            if (response.length > 0) {
                $('recaptcha-verification-1').writeAttribute('value', 'checked');
                $('recaptcha-verification-1').checked = true;
            }
        }
    });
};
</script>
<script src="https://www.google.com/recaptcha/api.js?onload=onloadCallback&render=explicit&hl=en" async defer></script>

Any help would be appreciated!Thanks.

Best Answer

<div class="recaptcha" style="overflow:hidden;position:relative;">
   <input type="checkbox" id="recaptcha-verification-1" name="recaptcha-verification-1" value="" class="hide required-entry" style="" />
   <div id="recaptcha-1"></div>
   <script type="text/javascript">
       var onloadCallback = function() {
           grecaptcha.render('recaptcha-1', {
               'sitekey': "6LdE5KoZAAAAAA3pqP2DwRex",
               'theme': "light",
           });
       };
       document.getElementById("newsletter-validate-detail").addEventListener("submit",function(evt)
  {
  var response = grecaptcha.getResponse();
  if(response.length == 0) 
  { 
    //reCaptcha not verified
    alert("Please Complete Google Recaptcha!"); 
    evt.preventDefault();
    return false;
  }
  //captcha verified
  //do the rest of your validations here
});
   </script>
   <script src="https://www.google.com/recaptcha/api.js?onload=onloadCallback&render=explicit&hl=en" async defer></script></div>

Add above code before "form" tag. Replace sitekey tag.