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

be-soft/recaptcha-bundle

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Install the Bundle

    composer require be-soft/recaptcha-bundle
    

    (Note: The package is forked from excelwebzone/recaptcha-bundle but may have updates. Verify the correct namespace in composer.json.)

  2. Enable the Bundle Add to config/bundles.php (Symfony 4+):

    return [
        // ...
        BE\Soft\RecaptchaBundle\EWZRecaptchaBundle::class => ['all' => true],
    ];
    
  3. Configure reCAPTCHA Create config/packages/ewz_recaptcha.yaml (or merge into existing):

    ewz_recaptcha:
        version: 3  # or 2, depending on your Google setup
        site_key: "YOUR_SITE_KEY"
        secret: "YOUR_SECRET_KEY"
        verify_url: "https://www.google.com/recaptcha/api/siteverify"  # Default, usually no need to change
    
  4. First Use Case: Protect a Form Add the Twig extension to your template:

    {{ render(ewz_recaptcha_form('contact_form', {'theme': 'light'})) }}
    

    (Replace 'contact_form' with your form type name.)

    Validate in your form type:

    use BE\Soft\RecaptchaBundle\Form\Type\RecaptchaType;
    
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder->add('recaptcha', RecaptchaType::class, [
            'mapped' => false,
            'constraints' => [
                new \BE\Soft\RecaptchaBundle\Validator\Constraints\IsTrue(),
            ],
        ]);
    }
    

Implementation Patterns

Common Workflows

1. Dynamic reCAPTCHA Integration

  • Use Case: Conditionally enable reCAPTCHA (e.g., for high-risk forms).
  • Pattern:
    // In your form type
    $builder->add('recaptcha', RecaptchaType::class, [
        'mapped' => false,
        'required' => $this->isHighRiskForm(), // Custom logic
    ]);
    
  • Twig:
    {% if isHighRiskForm %}
        {{ render(ewz_recaptcha_form('form_name')) }}
    {% endif %}
    

2. Custom Themes and Attributes

  • Override default reCAPTCHA styling:
    # config/packages/ewz_recaptcha.yaml
    ewz_recaptcha:
        theme: 'dark'  # or 'light'
        size: 'compact'  # or 'normal'
        tabindex: 0
    
  • Add custom HTML attributes:
    {{ render(ewz_recaptcha_form('form_name', {'attr': {'class': 'custom-class'}})) }}
    

3. Version-Specific Configuration

  • Version 2:
    ewz_recaptcha:
        version: 2
        public_key: "YOUR_V2_SITE_KEY"
        private_key: "YOUR_V2_SECRET_KEY"
        type: "image"  # or "invisible"
    
  • Version 3:
    ewz_recaptcha:
        version: 3
        score_threshold: 0.5  # Minimum score to pass
    

4. API-Based Verification

  • Manually verify reCAPTCHA responses (e.g., in a controller):
    use BE\Soft\RecaptchaBundle\Validator\RecaptchaValidator;
    
    $validator = new RecaptchaValidator($this->getParameter('ewz_recaptcha.secret'));
    $isValid = $validator->validate($request->request->get('recaptcha_response'));
    

5. Event Listeners for Custom Logic

  • Subscribe to reCAPTCHA events (e.g., to log failed attempts):
    // src/EventListener/RecaptchaListener.php
    public function onRecaptchaFail(RecaptchaEvent $event)
    {
        $this->logger->warning('reCAPTCHA failed for IP: ' . $event->getRequest()->getClientIp());
    }
    
  • Register in services.yaml:
    services:
        App\EventListener\RecaptchaListener:
            tags:
                - { name: 'kernel.event_listener', event: 'ewz_recaptcha.fail', method: 'onRecaptchaFail' }
    

Integration Tips

Symfony Forms

  • Embed reCAPTCHA in a FormType:
    $builder->add('recaptcha', RecaptchaType::class, [
        'label' => 'Verify you are not a robot',
        'translation_domain' => 'messages',
    ]);
    
  • Disable CSRF for reCAPTCHA (if needed):
    # config/packages/security.yaml
    framework:
        form:
            csrf_protection:
                enabled: true
                ignore_routes:
                    - recaptcha_verify  # Custom route for API calls
    

Twig Templates

  • Inline reCAPTCHA (for non-form use cases):
    {{ ewz_recaptcha_widget('form_name') }}
    
  • Custom Error Messages:
    {% if form.recaptcha.errors|length > 0 %}
        <div class="error">{{ form.recaptcha.errors|trans({}, 'messages') }}</div>
    {% endif %}
    

API Routes

  • Verify reCAPTCHA via API (e.g., for AJAX forms):
    // src/Controller/RecaptchaController.php
    public function verify(RecaptchaValidator $validator, Request $request)
    {
        $response = $validator->validate($request->request->get('token'));
        return new JsonResponse(['valid' => $response]);
    }
    
    Add a route:
    # config/routes.yaml
    recaptcha_verify:
        path: /api/recaptcha/verify
        controller: App\Controller\RecaptchaController::verify
        methods: [POST]
    

Gotchas and Tips

Pitfalls

1. Version Mismatch

  • Issue: Using version: 3 config with v2 keys (or vice versa) will silently fail.
  • Fix: Double-check site_key/secret against your Google reCAPTCHA admin.
  • Debug Tip: Enable debug mode and check for EWZRecaptchaBundle logs:
    # config/packages/dev/ewz_recaptcha.yaml
    ewz_recaptcha:
        debug: true
    

2. Caching False Positives

  • Issue: reCAPTCHA v3 scores may be cached by Google, causing inconsistent validation.
  • Fix: Use a short-lived cache for responses (e.g., 5 minutes):
    $cache = $this->container->get('cache.app');
    $cachedResponse = $cache->get('recaptcha_' . $token);
    if (!$cachedResponse) {
        $response = $validator->validate($token);
        $cache->set('recaptcha_' . $token, $response, 300);
    }
    

3. Twig Extension Not Auto-Loaded

  • Issue: ewz_recaptcha_form or ewz_recaptcha_widget not found in Twig.
  • Fix: Ensure the bundle is enabled before TwigBundle in config/bundles.php.
  • Debug: Clear cache after enabling:
    php bin/console cache:clear
    

4. CSRF Token Conflicts

  • Issue: Double CSRF tokens if reCAPTCHA is added to a form with csrf_protection: true.
  • Fix: Exclude reCAPTCHA from CSRF protection:
    $builder->add('recaptcha', RecaptchaType::class, [
        'mapped' => false,
        'csrf_protection' => false,
    ]);
    

5. Missing JavaScript for v2

  • Issue: reCAPTCHA v2 not rendering due to missing JS.
  • Fix: Include the Google script manually in your base template:
    <script src="https://www.google.com/recaptcha/api.js?render={{ ewz_recaptcha_config.site_key }}"></script>
    

Debugging Tips

1. Enable Verbose Logging

# config/packages/dev/ewz_recaptcha.yaml
ewz_recaptcha:
    debug: true
    logger:
        level: debug

Check logs for:

  • Recaptcha response: {"success": ...}
  • Recaptcha validation failed: ...

2. Test with Known Responses

  • Use Google’s test keys (`6LeIxAcTAAAAAJcZVRqyHh71UMIEGNQ_MXjiZ
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.
nexmo/api-specification
capell-app/block-library
axium/identity
cetria/laravel-dummy-models
cetria/reflection-helper
agropredict/sso-auth-bundle
evolvestudio/spam-protection
datacore/hub-sdk
develia/commons
cuci/prototurk-sdk
cuci/prototurk-sdk-symfony
develia/geo-bundle
dreamzy/livewire-charts
touchestate-sdk/php-sdk
22h/doctrine-garbage-collection-bundle
agtp/agtp-php
agtp/mod-php
splash/sonata-admin
splash/metadata
splash/openapi