Skip to content

Instantly share code, notes, and snippets.

@certainlyakey
Last active May 15, 2022 20:40
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 certainlyakey/86b646559a13f2d87b16afc2c558c79a to your computer and use it in GitHub Desktop.
Save certainlyakey/86b646559a13f2d87b16afc2c558c79a to your computer and use it in GitHub Desktop.
Integrate Google Recaptcha v2 into custom AJAX form (Wordpress)
<?php
// First we register the Google Recaptcha script as a dependency with an onload callback
wp_register_script( 'recaptcha_v2', add_query_arg(['render' => 'explicit', 'onload' => 'onloadRecaptchaCallback'], 'https://www.google.com/recaptcha/api.js'), [], null, true);
wp_enqueue_script( 'recaptcha_v2' );
// Here we validate Google Recaptcha token issued on our frontend with Google servers using our custom 'validate_captcha' WP AJAX hook
function hh_validate_captcha() {
check_ajax_referer( 'hhsubscribe', '_ajax_nonce' );
if ( 'POST' == $_SERVER['REQUEST_METHOD'] && isset( $_POST['fe_token'] ) && !empty( $_POST['fe_token'] ) ) {
$fe_token = $_POST['fe_token'];
$response = file_get_contents( 'https://www.google.com/recaptcha/api/siteverify?secret=' . get_option( 'rg_gforms_captcha_private_key' ) . '&response=' . $fe_token . '&remoteip=' . $_SERVER['REMOTE_ADDR'] );
$obj = json_decode( $response );
// Return the verification response for our JS to handle
wp_send_json( $obj, 200 );
} else {
wp_send_json( ['message' => 'Submission method not POST or captcha blank'], 403 );
}
}
add_action( 'wp_ajax_validate_captcha', 'hh_validate_captcha' );
add_action( 'wp_ajax_nopriv_validate_captcha', 'hh_validate_captcha' );
// Here we do usual AJAX-enabled form sending stuff - saving form fields to a WP post, posting to an API, etc.
function hh_newsletter_subscribe() {
if ( !isset( $_POST['hhsubscribe_nonce'] ) || !wp_verify_nonce( $_POST['hhsubscribe_nonce'], 'hhsubscribe' ) ) {
wp_nonce_ays( '' );
}
// $response = hh_newsletter_sendapplication( $_POST['email'], $_POST['firstname'], $_POST['lastname'] );
// if ( $_POST['email'] && 200 == $response['response']['code'] ) {
// echo 'Success!';
// } else {
// echo 'Error';
// }
die;
}
add_action( 'wp_ajax_hhsubscribe', 'hh_newsletter_subscribe' );
add_action( 'wp_ajax_nopriv_hhsubscribe', 'hh_newsletter_subscribe' );
<script>
// A script that sets a DOM element to attach the captcha to and a callback to execute after a frontend captcha token has been created
function onloadRecaptchaCallback() {
grecaptcha.render('hhsubscribe_submit', {
'sitekey' : <?php echo get_option( 'rg_gforms_captcha_public_key' ); ?>,
'callback' : onRecaptchaFETokenCreated
});
}
// Here we make a request to out WP AJAX action that verifies the FE token with Google servers using our private key and outputs either pass or fail
function onRecaptchaFETokenCreated(recaptchaFEToken) {
const $form = document.getElementById('newsletter-form');
const nonce = $form.querySelector('[name=hhsubscribe_nonce]').value;
fetch(script_data.ajaxurl, {
method: 'post',
body: '_ajax_nonce=' + nonce + '&action=validate_captcha&fe_token=' + recaptchaFEToken,
credentials: 'same-origin',
headers: {
'Content-Type': 'application/x-www-form-urlencoded; charset=utf-8'
},
})
.then(response => response.json())
.then(data => {
if (data.success) {
const request = new XMLHttpRequest();
request.open('POST', $form.getAttribute('action'), true);
request.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded; charset=UTF-8');
const form_data = new URLSearchParams(Array.from(new FormData($form))).toString();
request.send(form_data);
request.onreadystatechange = function() {
if (request.readyState === 4) {
document.getElementById('newsletter-form-output').innerHTML = request.responseText;
}
};
} else {
if (data.message) {
console.log('Validation error! ', data.message);
}
}
})
.catch(function() {
document.getElementById('newsletter-form-output').innerHTML = 'reCAPTCHA verification failed, please try again';
});
};
</script>
<form action="<?php echo admin_url( 'admin-ajax.php' ); ?>" method="post" id="newsletter-form">
<input type="hidden" name="action" value="hhsubscribe">
<?php wp_nonce_field( 'hhsubscribe', 'hhsubscribe_nonce', false ); ?>
...
<button type="submit" id="hhsubscribe_submit">Submit</button>
<output id="newsletter-form-output"></output>
</form>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment