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

Livewire V4 Recaptcha Laravel Package

elvisblanco1993/livewire-v4-recaptcha

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Install the package:
    composer require elvisblanco1993/livewire-v4-recaptcha
    
  2. Publish the config (optional, but recommended for customization):
    php artisan vendor:publish --provider="ElvisBlanco\LivewireRecaptcha\LivewireRecaptchaServiceProvider" --tag="config"
    
  3. Configure Google reCAPTCHA keys in .env or config/livewire-recaptcha.php:
    RECAPTCHA_V3_SITE_KEY=your_v3_site_key
    RECAPTCHA_V3_SECRET_KEY=your_v3_secret_key
    RECAPTCHA_V2_SITE_KEY=your_v2_site_key
    RECAPTCHA_V2_SECRET_KEY=your_v2_secret_key
    
  4. Register the Livewire directive in AppServiceProvider@boot():
    Livewire::component('recaptcha', \ElvisBlanco\LivewireRecaptcha\LivewireRecaptcha::class);
    

First Use Case: Protecting a Form

Add the directive to your Livewire component’s template:

<form wire:submit.prevent="submitForm">
    <!-- Your form fields -->
    <x-recaptcha type="v3" />
    <button type="submit">Submit</button>
</form>

Validate the response in your component:

use ElvisBlanco\LivewireRecaptcha\Traits\ValidatesRecaptcha;

class MyComponent extends Component
{
    use ValidatesRecaptcha;

    public function submitForm()
    {
        $this->validateRecaptcha('v3'); // Validates v3 score (default: 0.5)
        // Proceed with form logic...
    }
}

Implementation Patterns

1. Component Integration Workflow

  • For v3 (score-based):
    • Use the directive in your template (<x-recaptcha type="v3" />).
    • Validate with a threshold (default: 0.5):
      $this->validateRecaptcha('v3', 0.7); // Strict validation
      
  • For v2/v2 Invisible:
    • Render the directive with type="v2" or type="invisible".
    • Validate the token:
      $this->validateRecaptcha('v2', request('g-recaptcha-response'));
      

2. Dynamic Key Management

  • Override keys per environment or component:
    config(['livewire-recaptcha.keys.v3' => [
        'site_key' => env('RECAPTCHA_V3_SITE_KEY_STAGING'),
        'secret_key' => env('RECAPTCHA_V3_SECRET_KEY_STAGING'),
    ]]);
    
  • Use different keys for testing:
    $this->validateRecaptcha('v3', 0.0, ['test_key' => true]);
    

3. Conditional Validation

  • Skip validation in tests or specific contexts:
    if (!$this->isTestMode()) {
        $this->validateRecaptcha('v3');
    }
    

4. Custom Error Messages

  • Extend the trait to customize validation messages:
    use ElvisBlanco\LivewireRecaptcha\Traits\ValidatesRecaptcha as BaseValidatesRecaptcha;
    
    trait ValidatesRecaptcha extends BaseValidatesRecaptcha
    {
        protected function recaptchaFailed($version)
        {
            return "reCAPTCHA {$version} verification failed. Please try again.";
        }
    }
    

5. Integration with Livewire Rules

  • Combine with Livewire’s built-in validation:
    $this->validate([
        'email' => 'required|email',
        'recaptcha' => [$this, 'validateRecaptcha:v3'],
    ]);
    

Gotchas and Tips

Pitfalls

  1. Key Mismatch:

    • Ensure site_key and secret_key are correctly paired for each version (v2/v3). Mixing keys will fail silently.
    • Debug: Check config('livewire-recaptcha.keys') to verify loaded keys.
  2. CORS Issues:

    • If using v2/v2 Invisible, ensure your domain is whitelisted in Google’s admin console. CORS errors may break the token submission.
    • Fix: Test with type="v3" first (no CORS dependency).
  3. Livewire 4 Directive Scope:

    • The directive must be inside a Livewire component’s template. Placing it in a non-Livewire Blade file (e.g., layouts) will fail.
    • Workaround: Use a Livewire component as a wrapper for shared forms.
  4. Validation Timing:

    • validateRecaptcha() must be called after wire:submit.prevent or wire:submit to ensure the token is captured.
    • Anti-pattern:
      // ❌ Wrong: Token may not be submitted yet
      public function submitForm()
      {
          $this->validateRecaptcha('v3'); // Fails if token isn’t sent
          // ...
      }
      
  5. v3 Score Thresholds:

    • Google’s default passing score is 0.3, but this package defaults to 0.5 for stricter security.
    • Tip: Adjust thresholds based on risk (e.g., 0.9 for admin actions).

Debugging

  • Log Validation Errors:
    try {
        $this->validateRecaptcha('v3');
    } catch (\Exception $e) {
        \Log::error("reCAPTCHA validation failed: " . $e->getMessage());
        session()->flash('error', 'reCAPTCHA error. Please refresh and retry.');
    }
    
  • Test Locally:
    • Use Google’s test keys (6LeIxAcTAAAAAJcZVRqyHh71UMIEGNQ_MXjiZKhI) and pass g-recaptcha-response as 03AHJ_Rrh0... in tests.

Extension Points

  1. Custom Validation Logic:

    • Override validateRecaptcha() to add business rules:
      public function validateRecaptcha($version, $score = null, $options = [])
      {
          if ($version === 'v3' && $score > 0.9) {
              $this->addError('recaptcha', 'High-risk score detected. Manual review required.');
              return false;
          }
          return parent::validateRecaptcha($version, $score, $options);
      }
      
  2. Async Validation:

    • Use Livewire’s wire:ignore to load reCAPTCHA scripts asynchronously:
      <div wire:ignore>
          <x-recaptcha type="v3" />
      </div>
      
  3. Multi-Step Forms:

    • Store the token in a property and validate on the final step:
      public $recaptchaToken;
      
      public function stepOne()
      {
          $this->recaptchaToken = request('g-recaptcha-response');
      }
      
      public function stepTwo()
      {
          $this->validateRecaptcha('v2', $this->recaptchaToken);
      }
      

Configuration Quirks

  • Environment-Specific Keys:
    • The package merges keys from .env and config/livewire-recaptcha.php. Later values override earlier ones.
    • Example:
      // config/livewire-recaptcha.php
      'keys' => [
          'v3' => [
              'site_key' => env('RECAPTCHA_V3_SITE_KEY', 'fallback_key'),
              'secret_key' => env('RECAPTCHA_V3_SECRET_KEY', 'fallback_secret'),
          ],
      ],
      
  • Disable reCAPTCHA:
    • Set RECAPTCHA_ENABLED=false in .env to bypass validation entirely (useful for local/dev).
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.
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
mkwebdesign/filament-watchdog-v5
renatomarinho/laravel-page-speed
zedmagdy/filament-business-hours
renatovdemoura/blade-elements-ui
devgeek/beacon-admin
benjamin-rqt/data-watcher-bundle