Weave Code
Code Weaver
Helps Laravel developers discover, compare, and choose open-source packages. See popularity, security, maintainers, and scores at a glance to make better decisions.
Feedback
Share your thoughts, report bugs, or suggest improvements.
Subject
Message

Recaptcha Laravel Package

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.

View on GitHub
Deep Wiki
Context7
## 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,
  1. 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
    
  2. 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)
    }
    

Implementation Patterns

Workflows

  1. Frontend Integration

    • Include the reCAPTCHA script in your Blade template:
      <script src="https://www.google.com/recaptcha/api.js" async defer></script>
      
    • Render the widget:
      {!! \Google\Recaptcha\NoCaptcha::render() !!}
      
      (Note: Use Google\Recaptcha\NoCaptcha for v2/v3, or ReCaptcha for v1.)
  2. Backend Validation

    • Laravel Form Request Validation:
      use Google\Recaptcha\Laravel\ValidatesRecaptcha;
      
      class StorePostRequest extends FormRequest {
          use ValidatesRecaptcha;
      
          public function authorize() { ... }
          public function rules() {
              return [
                  'g-recaptcha-response' => 'required|captcha',
              ];
          }
      }
      
    • Manual Verification:
      $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.']);
      }
      
  3. reCAPTCHA v3 (Score-Based)

    • Configure in config/recaptcha.php:
      'version' => 'v3',
      'score_threshold' => 0.9, // Adjust based on risk tolerance
      
    • Verify in Laravel:
      $response = $recaptcha->verify($request->input('g-recaptcha-response'), $request->ip());
      if ($response->score() < config('recaptcha.score_threshold')) {
          // Reject
      }
      
  4. API Integration

    • For non-web contexts (e.g., CLI, APIs), use the low-level client:
      $client = new \Google\Recaptcha\Client(config('recaptcha.secret'));
      $response = $client->verify($token, $ip);
      
  5. Customizing SocketPost (Advanced)

    • Override the verification URL or configure TLS settings:
      $recaptcha = new \Google\Recaptcha\Recaptcha(config('recaptcha.secret'));
      $recaptcha->setSiteVerifyUrl('https://www.google.com/recaptcha/api/siteverify'); // Optional override
      $response = $recaptcha->verify($token, $ip);
      

Gotchas and Tips

Pitfalls

  1. IP Address Handling

    • Always pass the client’s IP ($_SERVER['REMOTE_ADDR'] or $request->ip()). Incorrect IPs (e.g., 127.0.0.1) will fail verification.
    • For proxies (e.g., Cloudflare), use CF-Connecting-IP header if available. Note: Version 1.5 now supports HTTP/1.1 responses, improving proxy compatibility.
  2. Version Mismatches

    • v2 vs. v3: Ensure frontend/backend versions align. Mixing NoCaptcha (v2) with v3 config will break verification.
    • Deprecated Methods: Avoid ReCaptcha::verify() (v1) in new projects.
  3. Rate Limits and Timeouts

    • Google enforces quota limits. Version 1.5 adds timeout handling for external API calls to prevent hanging.
    • Monitor usage in the reCAPTCHA admin dashboard.
  4. Testing

    • Use Google’s test keys in development:
      RECAPTCHA_SECRET=6LeIxAcTAAAAAJcZVRqyHh71UMIEGNQ_MXjiZKhI
      RECAPTCHA_SITE_KEY=6LeIxAcTAAAAAGG-vFI1TnRWxMZNFuojJ4WifJWe
      
    • Test responses with g-recaptcha-response=03AHJ_R... (pre-filled in test mode).
    • New in 1.5: Edge cases (e.g., invalid challenge_ts, string error codes) are now explicitly tested.
  5. Laravel Caching

    • Disable caching for reCAPTCHA responses if using ValidatesRecaptcha in Form Requests, as tokens are single-use:
      public function rules() {
          return [
              'g-recaptcha-response' => ['required', 'captcha', 'skip_when_cached:false'],
          ];
      }
      
  6. Security Hardening

    • Reflected XSS: Version 1.5 encodes var_export() output to prevent XSS in debug contexts.
    • TLS Verification: SocketPost connections now use hardened TLS verification by default.

Tips

  1. Dynamic Score Thresholds

    • Adjust score_threshold in config/recaptcha.php based on form sensitivity (e.g., 0.5 for contact forms, 0.9 for admin actions).
  2. Error Handling

    • Check $response->errorCodes() for specific failures (e.g., ['timeout-or-duplicate'] for expired tokens or ['invalid-domain'] for mismatched domains).
    • New in 1.5: Error codes are now strictly typed and validated.
  3. Logging

    • Log failed attempts for security audits:
      if (!$response->success()) {
          \Log::warning('reCAPTCHA failed', [
              'error_codes' => $response->errorCodes(),
              'ip' => $request->ip(),
          ]);
      }
      
  4. Extension Points

    • Custom Verification Logic: Extend \Google\Recaptcha\Recaptcha or override methods like verify().
    • Multi-Site Keys: Use environment-specific keys (e.g., RECAPTCHA_SECRET_STAGING) and conditionally load them.
    • Override SiteVerify URL: Useful for testing or custom endpoints:
      $recaptcha->setSiteVerifyUrl('https://your-custom-endpoint.com/verify');
      
  5. Performance

    • For high-traffic sites, consider asynchronous verification (e.g., queue the check after form submission).
    • New in 1.5: Optimized stream reading with stream_get_contents reduces memory usage.
  6. PHP 8.4+ Compatibility

    • Version 1.5 includes modernization for PHP 8.4+, such as:
      • Strict null checks.
      • Readonly classes with promoted constructors for DTOs.
      • Explicit property initialization.
  7. Case-Insensitive Hostname Matching

    • The package now handles hostname matching in a case-insensitive manner, improving reliability in multi-environment setups.

---
Weaver

How can I help you explore Laravel packages today?

Conversation history is not saved when not logged in.
Prompt
Add packages to context
No packages found.
codeflextech/permission-manager
karnoweb/livewire-datepicker
sayedenam/sayed-dashboard
milito/query-filter
apiboxsym/user-bundle
apiboxsym/health-check-bundle
jayeshmepani/jpl-moshier-ephemeris-php
elnasnato/laraliveui
labrodev/rest-sdk
sampaui/sampaui
babelqueue/php-sdk
facebook/capi-param-builder-php
babelqueue/symfony
hamzi/corewatch
minionfactory/raw-hydrator
hexters/coinpayment
rjcodes/rjcms
act-training/laravel-permissions-manager
alimarchal/laravel-chart-of-accounts
babenkoivan/elastic-scout-driver