Skip to content

GoogleRecaptcha

Viames Marino edited this page Oct 19, 2026 · 1 revision

Pair framework: GoogleRecaptcha

Pair\Services\GoogleRecaptcha renders Google reCAPTCHA widgets and verifies tokens on the server without a provider SDK. For forms that can switch between providers, prefer HumanChallenge.

Configuration

Key Default
GOOGLE_RECAPTCHA_SITE_KEY Empty; required for widget rendering.
GOOGLE_RECAPTCHA_SECRET_KEY Empty; required for verification.
GOOGLE_RECAPTCHA_VERIFY_URL https://www.google.com/recaptcha/api/siteverify
GOOGLE_RECAPTCHA_RESPONSE_FIELD g-recaptcha-response
GOOGLE_RECAPTCHA_TIMEOUT 10 seconds
GOOGLE_RECAPTCHA_CONNECT_TIMEOUT 3 seconds

Constructor arguments can override these settings. Keep the secret key on the server.

Render the widget

use Pair\Services\GoogleRecaptcha;

$captcha = new GoogleRecaptcha();

// Include the provider script once on the page.
print $captcha->scriptTag(['hl' => 'it']);
print $captcha->widgetHtml();

scriptUrl() returns the URL instead of a script tag and accepts onload, render, and hl. widgetHtml() returns a g-recaptcha container and requires a site key.

Verify before writing

use Pair\Services\GoogleRecaptcha;

$captcha = new GoogleRecaptcha();
$verification = $captcha->assertPost($_POST, $_SERVER['REMOTE_ADDR'] ?? null);

// Perform the application write only after successful verification.
Method Behavior
tokenFromPost(array $post): string Reads and trims the configured response field.
verifyToken(string $token, ?string $remoteIp = null): array Calls Siteverify and returns its normalized result.
verifyPost(array $post, ?string $remoteIp = null): array Extracts the token and calls verifyToken().
assertToken(string $token, ?string $remoteIp = null): array Verifies and throws GOOGLE_RECAPTCHA_ERROR when success is false.
assertPost(array $post, ?string $remoteIp = null): array Extracts the token and calls assertToken().
siteKeySet(): bool / secretKeySet(): bool Checks whether the corresponding key is configured.

Verification requires a secret key and a token of valid local format. Invalid configuration, token format, or transport failures can throw even when using verifyToken() or verifyPost(). A returned array alone is not proof of success: check success or use an assertion method. Application-specific hostname/action checks belong in the application or the higher-level HumanChallenge helper.

See also: HumanChallenge, CloudflareTurnstile, Configuration file, Form.

Clone this wiki locally