Last active
November 5, 2020 13:46
-
-
Save stuartpearman/fc96f758ae61644b40480f5fff3c4056 to your computer and use it in GitHub Desktop.
recaptcha-v3
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function initRecaptcha () { | |
// If you want recaptcha enabled on a form, give it the data-recaptcha attribute | |
var recaptchaForms = document.querySelectorAll('form[data-recaptcha]'); | |
recaptchaForms.forEach(form => { | |
form.addEventListener('submit', e => { | |
e.preventDefault(); | |
grecaptcha.ready(function() { | |
grecaptcha.execute('PUBLICKEY', { action: 'submit' }).then(function(token) { | |
// Directly creates and appends hidden field with recaptcha response to the form | |
var input = document.createElement("input"); | |
input.setAttribute("type", "hidden"); | |
input.setAttribute("name", "g-recaptcha-response"); | |
input.setAttribute("value", token); | |
form.appendChild(input); | |
form.submit(); | |
}); | |
}); | |
}); | |
}); | |
} | |
initRecaptcha(); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
// This code goes in your form handler | |
$captcha = $_POST['g-recaptcha-response']; | |
$secret = 'SECRETKEY'; | |
$querystring = '?secret=' . $secret . '&response=' . $captcha; | |
// This is a GET Request, replace `wp_remote_get` if not using wordpress | |
$recaptcha_response = wp_remote_get( | |
'https://www.google.com/recaptcha/api/siteverify' . $querystring | |
); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment