Weave 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

Captcha Bundle Laravel Package

ady/captcha-bundle

Laravel bundle providing CAPTCHA integration to protect forms from bots. Includes configurable drivers, easy validation rules, and middleware-friendly setup. Helps reduce spam on logins, registrations, contact forms, and other public endpoints.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation

    composer require ady/captcha-bundle
    

    Add to config/bundles.php (Symfony):

    return [
        // ...
        Ady\CaptchaBundle\AdyCaptchaBundle::class => ['all' => true],
    ];
    
  2. Configuration Publish the default config:

    php bin/console ady:captcha:install
    

    Edit config/packages/ady_captcha.yaml to adjust:

    • provider (e.g., hcaptcha, recaptcha_v3)
    • API keys (e.g., hcaptcha.site_key, hcaptcha.secret_key)
  3. First Use Case Add the Twig extension to your template:

    {{ ady_captcha('hcaptcha', {
        'theme': 'light',
        'size': 'compact'
    }) }}
    

    Validate in a controller:

    use Ady\CaptchaBundle\Validator\Constraints as CaptchaAssert;
    
    /**
     * @CaptchaAssert\ValidCaptcha(
     *     provider="hcaptcha",
     *     message="Invalid CAPTCHA."
     * )
     */
    public function submitForm(Request $request)
    {
        // ...
    }
    

Implementation Patterns

Common Workflows

  1. Form Integration

    • Use the CaptchaAssert\ValidCaptcha constraint on form handlers or DTOs.
    • Example with Symfony Forms:
      $builder->add('captcha', CaptchaType::class, [
          'provider' => 'recaptcha_v3',
          'score_threshold' => 0.9,
      ]);
      
  2. Dynamic Provider Selection

    • Switch providers via config or runtime:
      # config/packages/ady_captcha.yaml
      ady_captcha:
          provider: '%env(ADY_CAPTCHA_PROVIDER)%'
      
    • Runtime override:
      $validator->enableConstraint(new ValidCaptcha('hcaptcha'));
      
  3. API/Non-Twig Usage

    • Generate tokens manually:
      $token = $this->container->get('ady_captcha.token_generator')->generate('hcaptcha');
      
    • Validate tokens:
      $validator = $this->container->get('ady_captcha.validator');
      $isValid = $validator->validate($token, $request->request->get('captcha_response'));
      
  4. Custom Providers

    • Extend Ady\CaptchaBundle\Provider\AbstractProvider:
      class MyProvider extends AbstractProvider
      {
          public function getName(): string { return 'my_provider'; }
          public function verify(string $token, string $response): bool { /* ... */ }
      }
      
    • Register in services.yaml:
      services:
          Ady\CaptchaBundle\Provider\MyProvider:
              tags: ['ady_captcha.provider']
      
  5. Rate Limiting

    • Use the Ady\CaptchaBundle\EventListener\RateLimitListener to throttle requests:
      ady_captcha:
          rate_limiter:
              enabled: true
              max_attempts: 5
              window_size: 3600
      

Gotchas and Tips

Pitfalls

  1. Token Expiry

    • Tokens expire after 1 minute by default. Regenerate if validation fails due to timeout.
    • Adjust in config:
      ady_captcha:
          token_ttl: 300  # 5 minutes
      
  2. Provider-Specific Quirks

    • hCaptcha: Requires data-sitekey attribute in HTML (not data-captcha).
    • reCAPTCHA v3: Score threshold must be between 0.0 and 1.0.
    • Custom Providers: Ensure verify() returns bool and handles exceptions.
  3. CSRF Token Conflicts

    • If using Symfony’s CSRFTokenManager, ensure CAPTCHA tokens don’t collide:
      ady_captcha:
          token_name: 'captcha_token'  # Default is '_captcha'
      
  4. Debugging Failures

    • Enable verbose logging:
      ady_captcha:
          debug: true
      
    • Check raw responses:
      $validator->validate($token, $response, true); // Returns raw provider response
      
  5. Caching Issues

    • Clear cache after changing providers or config:
      php bin/console cache:clear
      

Tips

  1. Environment-Specific Keys Use Symfony’s %env% for keys:

    ady_captcha:
        hcaptcha:
            site_key: '%env(HCAPTCHA_SITE_KEY)%'
            secret_key: '%env(HCAPTCHA_SECRET_KEY)%'
    
  2. Testing

    • Mock providers in tests:
      $validator = $this->createMock(ValidatorInterface::class);
      $validator->method('validate')->willReturn(true);
      $this->container->set('ady_captcha.validator', $validator);
      
    • Use the TestProvider for unit tests:
      ady_captcha:
          provider: 'test'
      
  3. Performance

    • Lazy-load providers:
      services:
          Ady\CaptchaBundle\Provider\HcaptchaProvider:
              lazy: true
      
  4. Accessibility

    • Ensure CAPTCHA is ARIA-compliant:
      {{ ady_captcha('hcaptcha', {
          'aria-label': 'Prove you are not a robot'
      }) }}
      
  5. Fallback Mechanisms

    • Combine with other validation (e.g., IP checks):
      if (!$validator->validate($token, $response) && $this->isTrustedIP($request->getClientIp())) {
          // Bypass CAPTCHA for trusted users
      }
      
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.
andydefer/laravel-notification
adachsoft/cli-process-tester
jhaskell13/laraflow
sebastienheyd/boilerplate-media-manager
ccast/tagixo-primix
pretendtrue/laravel-builder
sawmainek/laravel-scout-tntsearch-driver
tomshaw/laravel-calendar-table
dibakar/laravel-ownership
steadrun/laravel-monitor
labyrinthe/connect-laravel
elmogy/layan
drewdan/sentinel-client
dskripchenko/laravel-llm
fatryst/nuonuo
stevenay/myanfont
gmostafa/php-graphql-client
xeviant/paystack
snowsoft/faker
meditationsteps/blogetc