This goes in the form page within the header with the public site key where the X's are.
<script src="https://www.google.com/recaptcha/api.js?render=XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX"></script>
<script>
grecaptcha.ready(function() {
document.getElementById('contactform').addEventListener("submit", function(event) {
event.preventDefault();
grecaptcha.execute('XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX', {action: 'contactform'}).then(function(token) {
document.getElementById("recaptchaResponse").value= token;
document.getElementById('contactform').submit();
});
}, false);
});
</script>
This is the form
<form action="send.php" method=post id=contactform> Name: <input type="text" name="name" value=""><br /> Email: <input type="text" name="email" value=""><br /> <input type="hidden" name="recaptcha_response" id="recaptchaResponse"> <input type=submit value=" Send "> </form>
Then within the send.php file is where we are doing the checking of the captcha submission. The secret key gets placed where the X's are.
<?php
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['recaptcha_response'])) {
$recaptcha_response = $_POST['recaptcha_response'];
define("RECAPTCHA_V3_SECRET_KEY", 'XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX');
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL,"https://www.google.com/recaptcha/api/siteverify");
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query(array('secret' => RECAPTCHA_V3_SECRET_KEY, 'response' => $recaptcha_response)));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($ch);
curl_close($ch);
$arrResponse = json_decode($response, true);
// verify the response
if($arrResponse["success"] == '1' && $arrResponse["score"] >= 0.5) {
// valid submission
// go ahead and do necessary stuff
} else {
// spam submission
// show error message
}
}