google/recaptcha
PHP client library for Google reCAPTCHA v2 and v3. Provides server-side verification of reCAPTCHA responses with simple APIs, Composer install, and PSR-4 autoloading to help protect sites from spam and abuse.
## Getting Started
### Minimal Setup
1. **Installation**
```bash
composer require google/recaptcha:^1.5
Add the service provider to config/app.php (Laravel 5.5+ auto-discovers it):
Google\Recaptcha\ServiceProvider::class,
Publish Config
php artisan vendor:publish --provider="Google\Recaptcha\ServiceProvider" --tag=config
Configure .env with your Site Key and Secret Key from reCAPTCHA Admin:
RECAPTCHA_SECRET=your_secret_key
RECAPTCHA_SITE_KEY=your_site_key
First Use Case: Verify a Form Submission
use Google\Recaptcha\Recaptcha;
$recaptcha = new Recaptcha(config('recaptcha.secret'));
$response = $recaptcha->verify($_POST['g-recaptcha-response'], $_SERVER['REMOTE_ADDR']);
if (!$response->success()) {
// Handle failure (e.g., show error message)
}
Frontend Integration
<script src="https://www.google.com/recaptcha/api.js" async defer></script>
{!! \Google\Recaptcha\NoCaptcha::render() !!}
(Note: Use Google\Recaptcha\NoCaptcha for v2/v3, or ReCaptcha for v1.)Backend Validation
use Google\Recaptcha\Laravel\ValidatesRecaptcha;
class StorePostRequest extends FormRequest {
use ValidatesRecaptcha;
public function authorize() { ... }
public function rules() {
return [
'g-recaptcha-response' => 'required|captcha',
];
}
}
$recaptcha = app(\Google\Recaptcha\Recaptcha::class);
$response = $recaptcha->verify($request->input('g-recaptcha-response'), $request->ip());
if (!$response->isSuccess()) {
return back()->withErrors(['captcha' => 'Invalid verification.']);
}
reCAPTCHA v3 (Score-Based)
config/recaptcha.php:
'version' => 'v3',
'score_threshold' => 0.9, // Adjust based on risk tolerance
$response = $recaptcha->verify($request->input('g-recaptcha-response'), $request->ip());
if ($response->score() < config('recaptcha.score_threshold')) {
// Reject
}
API Integration
$client = new \Google\Recaptcha\Client(config('recaptcha.secret'));
$response = $client->verify($token, $ip);
Customizing SocketPost (Advanced)
$recaptcha = new \Google\Recaptcha\Recaptcha(config('recaptcha.secret'));
$recaptcha->setSiteVerifyUrl('https://www.google.com/recaptcha/api/siteverify'); // Optional override
$response = $recaptcha->verify($token, $ip);
IP Address Handling
$_SERVER['REMOTE_ADDR'] or $request->ip()). Incorrect IPs (e.g., 127.0.0.1) will fail verification.CF-Connecting-IP header if available. Note: Version 1.5 now supports HTTP/1.1 responses, improving proxy compatibility.Version Mismatches
NoCaptcha (v2) with v3 config will break verification.ReCaptcha::verify() (v1) in new projects.Rate Limits and Timeouts
Testing
RECAPTCHA_SECRET=6LeIxAcTAAAAAJcZVRqyHh71UMIEGNQ_MXjiZKhI
RECAPTCHA_SITE_KEY=6LeIxAcTAAAAAGG-vFI1TnRWxMZNFuojJ4WifJWe
g-recaptcha-response=03AHJ_R... (pre-filled in test mode).challenge_ts, string error codes) are now explicitly tested.Laravel Caching
ValidatesRecaptcha in Form Requests, as tokens are single-use:
public function rules() {
return [
'g-recaptcha-response' => ['required', 'captcha', 'skip_when_cached:false'],
];
}
Security Hardening
var_export() output to prevent XSS in debug contexts.Dynamic Score Thresholds
score_threshold in config/recaptcha.php based on form sensitivity (e.g., 0.5 for contact forms, 0.9 for admin actions).Error Handling
$response->errorCodes() for specific failures (e.g., ['timeout-or-duplicate'] for expired tokens or ['invalid-domain'] for mismatched domains).Logging
if (!$response->success()) {
\Log::warning('reCAPTCHA failed', [
'error_codes' => $response->errorCodes(),
'ip' => $request->ip(),
]);
}
Extension Points
\Google\Recaptcha\Recaptcha or override methods like verify().RECAPTCHA_SECRET_STAGING) and conditionally load them.$recaptcha->setSiteVerifyUrl('https://your-custom-endpoint.com/verify');
Performance
stream_get_contents reduces memory usage.PHP 8.4+ Compatibility
Case-Insensitive Hostname Matching
---
How can I help you explore Laravel packages today?