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 Bundle Laravel Package

andanteproject/recaptcha-bundle

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Install the Bundle

    composer require andanteproject/recaptcha-bundle
    

    Symfony Flex will auto-register the bundle in config/bundles.php.

  2. Configure Keys Add your Google reCAPTCHA v2 keys to config/packages/andante_re_captcha.yaml:

    andante_re_captcha:
        secret: '%env(RECAPTCHA_SECRET)%'
        site_key: '%env(RECAPTCHA_SITE_KEY)%'
    

    Store keys in .env:

    RECAPTCHA_SECRET=your_secret_key
    RECAPTCHA_SITE_KEY=your_site_key
    
  3. Add to a Form Include ReCaptchaType in your form builder:

    use Andante\ReCaptchaBundle\Form\ReCaptchaType;
    
    $builder->add('recaptcha', ReCaptchaType::class);
    
  4. Test in Dev Disable validation in andante_re_captcha.yaml for testing:

    andante_re_captcha:
        enable_validation: false
    

Implementation Patterns

Common Workflows

  1. Basic Form Integration Add reCAPTCHA to any form (e.g., contact, registration):

    $builder->add('recaptcha', ReCaptchaType::class, [
        'mapped' => false, // Typically not mapped to an entity
        'label' => 'Verify you are human',
    ]);
    
  2. Theming & Styling Customize appearance via options:

    $builder->add('recaptcha', ReCaptchaType::class, [
        'theme' => 'dark', // 'light' (default) or 'dark'
        'size' => 'compact', // 'normal' (default) or 'compact'
    ]);
    
  3. Conditional Validation Disable validation for specific forms (e.g., API submissions):

    $builder->add('recaptcha', ReCaptchaType::class, [
        'constraints' => [new NotBlank()], // Only NotBlank, no reCAPTCHA
    ]);
    
  4. Dynamic Key Management Override keys per environment (e.g., config/packages/dev/andante_re_captcha.yaml):

    andante_re_captcha:
        site_key: 'dev_site_key'
        secret: 'dev_secret_key'
    
  5. Event-Driven Customization Extend validation logic via events (e.g., pre-submit checks):

    // src/EventListener/RecaptchaListener.php
    public function onKernelRequest(GetResponseEvent $event) {
        if ($event->isMainRequest() && $event->getRequest()->isXmlHttpRequest()) {
            $this->container->get('andante_re_captcha.manager')->disableValidation();
        }
    }
    

Gotchas and Tips

Pitfalls

  1. Validation Timing

    • The validator runs after the form is submitted, not client-side. Ensure your form includes the reCAPTCHA HTML snippet (auto-generated by the bundle) before the submit button.
  2. Environment-Specific Keys

    • Forgetting to update keys in .env or config files will cause silent failures. Test with enable_validation: false first.
  3. Constraint Overrides

    • Clearing constraints entirely removes all validation (including NotBlank). Explicitly define alternatives:
      'constraints' => [new NotBlank(), new Assert\Callback([$this, 'customValidation'])]
      
  4. Caching Issues

    • ReCAPTCHA responses may fail if the server’s IP is rate-limited. Use google/recaptcha package’s verify() method directly for debugging:
      $response = $this->container->get('andante_re_captcha.manager')->verify($token);
      
  5. Dark Mode Quirks

    • The dark theme may clash with custom CSS. Inspect the generated HTML (<div class="g-recaptcha">) to override styles.

Debugging Tips

  1. Log Validation Errors Extend the validator to log failed tokens:

    // src/Validator/Constraint/RecaptchaValidator.php
    public function validate($value, Constraint $constraint) {
        try {
            $response = $this->recaptchaManager->verify($value);
        } catch (\Exception $e) {
            $this->logger->error('reCAPTCHA failed: ' . $e->getMessage());
            $this->context->buildViolation($constraint->message)
                ->atPath('recaptcha')
                ->addViolation();
        }
    }
    
  2. Test Tokens Use Google’s test tokens (0x3...) in dev to bypass validation:

    andante_re_captcha:
        secret: '6LeIxAcTAAAAAJcZVRqyHh71UMIEGNQ_MXjiZKhI' # Test secret
    
  3. Symfony Profiler Check the AndanteReCaptchaBundle tab in the profiler for validation stats and errors.

Extension Points

  1. Custom Validation Logic Replace the default validator by binding your own service:

    services:
        App\Validator\CustomRecaptchaValidator:
            tags: [validator.constraint_validator]
            arguments: ['@andante_re_captcha.manager']
    

    Then override the form type’s constraints:

    $builder->add('recaptcha', ReCaptchaType::class, [
        'constraints' => [new CustomRecaptchaConstraint()],
    ]);
    
  2. Async Verification Offload verification to a queue (e.g., Symfony Messenger) for performance:

    // src/Message/VerifyRecaptchaMessage.php
    class VerifyRecaptchaMessage {
        public function __construct(public string $token) {}
    }
    
    // In your form handler
    $this->messageBus->dispatch(new VerifyRecaptchaMessage($form->get('recaptcha')->getData()));
    
  3. Multi-Language Support Localize error messages by extending the constraint:

    class LocalizedRecaptchaConstraint extends Constraint {
        public $message = 'recaptcha.error'; // Translatable key
    }
    
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.
amashukov/lnd-client-php
althinect/enum-permission
andydefer/laravel-actions
mintobit/jobqueue
a4sex/maintenance-bundle
a4sex/entity-date-update
a4sex/client-identifier
a4sex/base-utilites
a4sex/key-value-storage
a4sex/micro-status
chilldev/dependency-injection-extra
datinglibre/datinglibre-app-api
biberltd/corebundle
bricre/symfony-bundle-test
biberltd/logbundle
dominium/http-adapter-bundle
dominium/google-analytics
a4sex/auto-clean-entity
christhompsontldr/laravel-inky
spatie/mailcoach-vapor