Magento 2.3.X - How to add the google captcha V2 on the checkout page before place the order button.
1 Answer
First of all add your captcha element in any html template as per your need.
<div class="g-recaptcha" data-sitekey="YOUR_GOOGLE_CAPTCHA_KEY" id="html_element"></div>
Now add below code in your any .phtml template file which one must load on checkout page
I used /vendor/magento/module-checkout/view/frontend/templates/onepage.phtml
<script src='https://www.google.com/recaptcha/api.js?onload=waitForElement&render=explicit' async defer></script>
<script type="text/javascript">
function waitForElement(query){
var poops = setInterval(function(){
if(document.querySelector('.g-recaptcha')){
clearInterval(poops);
window.checkout_captcha = grecaptcha.render("html_element", {
sitekey: '--GzJK',
callback: function() {
console.log('recaptcha callback');
}
});
}
}, 100);
}
</script>
Now we need to prevent to place order without select google captcha so we need JS validation.
you can write as per your need at place order function /vendor/magento/module-checkout/view/frontend/web/js/proceed-to-checkout.js
if(jQuery('.g-recaptcha').html() !=''){
var response = grecaptcha.getResponse(window.checkout_captcha);
if(response.length==0){
//your condition
errorMessage = $.mage.__('Please verify that you are not a robot');
alert({ content: errorMessage });
return;
}
}
If work for you then please mark as a solution.
Note: don't add any code directly in vendor. override file in your theme/module