Skip to content

Instantly share code, notes, and snippets.

@stuartpearman
Last active November 5, 2020 13:46
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save stuartpearman/fc96f758ae61644b40480f5fff3c4056 to your computer and use it in GitHub Desktop.
Save stuartpearman/fc96f758ae61644b40480f5fff3c4056 to your computer and use it in GitHub Desktop.
recaptcha-v3
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();
<?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