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
Add above code before "form" tag. Replace sitekey tag.