Google RECAPTCHA v3

13.06.2021 | 1016 | SQL

An example of using captcha from Google of the third version

You need to get the secret and public keys in the Google service here:
https://www.google.com/recaptcha/admin/

Server (backend) part:
$recaptcha_key = 'XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX';
$recaptcha_url = 'https://www.google.com/recaptcha/api/siteverify';
$recaptcha_params = [
'secret' => $recaptcha_key,
'response' => $_POST['recaptcha_response'],
'remoteip' => $_SERVER['REMOTE_ADDR'],
];
$ch = curl_init($recaptcha_url);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $recaptcha_params);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$response = curl_exec($ch);
if (!empty($response)) {
$decoded_response = json_decode($response);
}
$recaptcha_success = false;
if ($decoded_response && $decoded_response->score > 0) {
$recaptcha_success = $decoded_response->score;
$arResult["TYPE"] = "OK";
} else {
$arResult["TYPE"] = "ERROR";
}
Front (template part):
< input type="hidden" name="recaptcha_response" id="recaptchaResponse">
< script src="https://www.google.com/recaptcha/api.js?
onload=onloadCallbackRecap&render=XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX" async defer>
< script>
var onloadCallbackRecap = function () {
grecaptcha.ready(function () {
grecaptcha.execute('XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX', {
action: 'contact_callback'
}).then(function (token) {
var recaptchaResponse = document.getElementById('recaptchaResponse');
recaptchaResponse.value = token;
});
});
};
< /script>
Stylistics for hiding the label
.grecaptcha-badge{
display: none!important;
}



← Back

Comments (0)