I do not know what class you're using for this, so I'll recreate this using CURL, although there are other ways to do this.
I created a very simple function to do the service, without using official or existing libraries.
function isCaptchaValid(string $ChaveSecreta, $ClienteCaptcha, $ClienteIP) : bool {
$ClienteCaptcha = filter_var($ClienteCaptcha, FILTER_DEFAULT);
$ClienteIP = filter_var($ClienteIP, FILTER_VALIDATE_IP);
if($ClienteCaptcha && $ClienteIP){
$valoresPost = [
'secret' => $ChaveSecreta,
'response' => $ClienteCaptcha,
'remoteip' => $ClienteIP
];
$ch = curl_init('https://www.google.com/recaptcha/api/siteverify');
curl_setopt_array($ch, [
CURLOPT_POST => 1,
CURLOPT_POSTFIELDS => $valoresPost,
CURLOPT_RETURNTRANSFER => 1,
CURLOPT_SSL_VERIFYHOST => 2,
CURLOPT_SSL_VERIFYPEER => 1,
CURLOPT_FAILONERROR => 1
]);
$resposta = json_decode(curl_exec($ch), true);
curl_close($ch);
if(isset($resposta['success'])){
return $resposta['success'];
}
}
return false;
}
In this way you just have to do, in HTML:
<form action="SuaPagina.php" method="post">
<div class="g-recaptcha" data-sitekey="SuaChavePublica"></div>
<input type="submit">
</form>
<script src='https://www.google.com/recaptcha/api.js'></script>
While in PHP:
if(isset($_POST['g-recaptcha-response'])) {
//...
if(isCaptchaValid('SuaChavePrivada', $_POST['g-recaptcha-response'], $_SERVER['REMOTE_ADDR'])){
echo 'Você preencheu o captcha corretamente :D';
exit;
}
}
echo 'Você errou o captcha! :(';
Remember if you are using CloudFlare, Sucuri, Incapsula (...) you should not use REMOTE_ADDR
!
I tried to leave the function as simple as possible, logically could do all the processing creating other functions ...