I have custom phtml form which am calling in multiple CMS pages, i want to add google recaptcha V3 in all the cms pages wherever the custom form is calling.
How i can achive this?
thank you.
here's a quick guide on adding Google reCAPTCHA v3 to a custom PHTML form in Magento 2 CMS pages:
Steps to Add Google reCAPTCHA v3 Get reCAPTCHA Site Key and Secret Key:
Go to Google reCAPTCHA and register your site. Choose reCAPTCHA v3 and get your site key and secret key. Include reCAPTCHA Script in Your PHTML File:
In your custom PHTML file, include the Google reCAPTCHA v3 script: html
<script src="https://www.google.com/recaptcha/api.js?render=your_site_key"></script>
Add reCAPTCHA v3 Integration:
Add a div for the reCAPTCHA token and a script to handle it. Place this just before your form closing tag ():
<input type="hidden" name="g-recaptcha-response" id="g-recaptcha-response">
<script>
grecaptcha.ready(function() {
grecaptcha.execute('your_site_key', {action: 'submit'}).then(function(token) {
document.getElementById('g-recaptcha-response').value = token;
});
});
</script>
Form Handling in Your Custom Module/Controller:
Ensure your form handler (probably a controller in a custom module) verifies the reCAPTCHA response. In your form processing logic, add:
$recaptchaResponse = $this->getRequest()->getParam('g-recaptcha-response');
$secretKey = 'your_secret_key';
$url = 'https://www.google.com/recaptcha/api/siteverify';
$data = [
'secret' => $secretKey,
'response' => $recaptchaResponse
];
$options = [
'http' => [
'header' => "Content-type: application/x-www-form-urlencoded\r\n",
'method' => 'POST',
'content' => http_build_query($data),
],
];
$context = stream_context_create($options);
$result = file_get_contents($url, false, $context);
$resultJson = json_decode($result);
if ($resultJson->success != true) {
// Handle reCAPTCHA verification failure
}
Testing:
After setting this up, test your form to ensure that the reCAPTCHA token is generated and verified correctly.