File size: 1,424 Bytes
cf14c12 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 | <?php
declare(strict_types=1);
namespace User\Infrastructure\Services\Captcha;
use Easy\Container\Attributes\Inject;
use Psr\Http\Client\ClientInterface;
use Psr\Http\Message\RequestFactoryInterface;
class GoogleRecaptcha
{
private const BASE_URL = 'https://www.google.com/recaptcha/api/siteverify';
public function __construct(
private ClientInterface $client,
private RequestFactoryInterface $factory,
#[Inject('option.recaptcha.secret_key')]
private ?string $secretKey = null,
) {
}
public function verifyToken(string $token): void
{
$request = $this->factory->createRequest(
'POST',
self::BASE_URL,
);
$body = $request->getBody();
$body->write(
http_build_query([
'secret' => $this->secretKey,
'response' => $token,
])
);
$request = $request
->withHeader(
'Content-Type',
'application/x-www-form-urlencoded'
)->withBody($body);
$response = $this->client->sendRequest($request);
if ($response->getStatusCode() !== 200) {
throw new VerificationFailedException();
}
$body = json_decode($response->getBody()->getContents());
if (!$body->success) {
throw new VerificationFailedException();
}
}
}
|