<?php
namespace App\Service;
use Buzz\Browser;
use Buzz\Client\FileGetContents;
use Nyholm\Psr7\Factory\Psr17Factory;
use Psr\Log\LoggerInterface;
use Psr\Http\Message\ResponseInterface;
class RecaptchaService
{
public function __construct(
private LoggerInterface $logger,
private $recaptchaUrl,
private $recaptchaSecret,
private $recaptchaRetries
) {
$client = new FileGetContents(new Psr17Factory());
$this->browser = new Browser($client, new Psr17Factory());
}
// Login route
const ROUTE_VERIFY = '/recaptcha/api/siteverify';
public function verifyToken($token)
{
$this->logger->debug('***** Verifying token for recaptcha');
$response = null;
for ($i = 0; $response == null && $i < $this->recaptchaRetries; $i ++) {
try {
$url = sprintf('%s%s?secret=%s&response=%s', $this->recaptchaUrl, self::ROUTE_VERIFY, $this->recaptchaSecret, $token);
/** @var ResponseInterface $response **/
$response = $this->browser->get($url);
} catch (\Exception $ex) {
$this->logger->debug('***** Error verifying token: ' . $ex->getMessage());
$response = null;
}
}
if ($response == null) {
throw new \Exception("Could Not Verify Token");
}
$this->logger->debug('***** Token was verified');
$responseString = $response->getBody()->getContents();
$this->logger->debug('***** Full verification results: '. $responseString);
$responseObject = json_decode($responseString, true);
$result = (isset($responseObject['success']) && $responseObject['success']);
$this->logger->debug('***** Recaptcha pass results: ' . ($result ? 'Pass' : 'Fail'));
return $result;
}
}