I'm having an issue with reCaptcha V3. The issue is that I'm struggling to communicate with the server when it comes to recording the analytics and the logic of the newsletter itself. I'm trying to let the form go through the reCaptcha thus confirming the user is not a bot, and if so then the fields the user inputs can be recorded on the database(firebase). Now I have the logic already set up for recording the user inputs on the database and connecting the reCaptcha on the front-end but I cannot seem to figure out how to connect the front-end to the back-end with Google' reCaptcha.
I've tried different ways to connect it as StackOverflow already has some solid solutions but none worked for me, as I'm struggling understanding the logic behind the POST methods. I'm a javascript newbie. Here's what I've done:
grecaptcha.ready(function() {
// do request for recaptcha token
// response is promise with passed token
grecaptcha.execute('6LdFL6kUAAAAAH1J3WcBt9_s4dV2Rk-3wqlwETI9', {action: 'create_user'}).then(function(token) {
// add token to form
$('#newsletterform').prepend('<input type="hidden" name="g-recaptcha-response" value="' + token + '">');
$.post("captcha.php",{ firstname: firstName,
lastname: lastName,
email: email,
token: token},
function(result) {
console.log(result);
if(result.success) {
//put logic for recording user's data on database
}
And my php is here:
<?php
$firstname;$lastname;$email;$captcha;
$firstname = filter_input(INPUT_POST, 'firstName', FILTER_SANITIZE_STRING);
$lastname = filter_input(INPUT_POST, 'lastName', FILTER_SANITIZE_STRING);
$email = filter_input(INPUT_POST, 'email', FILTER_VALIDATE_EMAIL);
$captcha = filter_input(INPUT_POST, 'token', FILTER_SANITIZE_STRING);
if(!$captcha){
echo '<h2>Please check the the captcha form.</h2>';
exit;
} else{
$secretKey = "6LdFL6kUAAAAAEZ8e2yzKZ6J8r6G9locFg_6oFe4";
$ip = $_SERVER['REMOTE_ADDR'];
// post request to server
$url = 'https://www.google.com/recaptcha/api/siteverify';
$data = array('secret' => $secretKey, 'response' => $captcha);
$options = array(
'http' => array(
'header' => "Content-type: application/x-www-form-urlencoded
",
'method' => 'POST',
'content' => http_build_query($data)
)
);
$context = stream_context_create($options);
$response = file_get_contents($url, false, $context);
$responseKeys = json_decode($response,true);
header('Content-type: application/json');
if($responseKeys["success"]) {
echo json_encode(array('success' => 'true'));
} else {
echo json_encode(array('success' => 'false'));
}
}
?>
I've added the script for API on the form. Any ideas? Cheers!
Maybe you can try this in your newsletter form, no need to change anything in your form frontend code: https://github.com/AlexStack/Google-Recaptcha-to-any-form
Basic example codes:
Display Google Recaptcha v2 or v3 after a Form_Field_ID:
GoogleRecaptcha::show('SiteKey', 'Form_Field_ID');
Verify it in the backend php:
GoogleRecaptcha::verify('SecretKey');