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

Ds Recaptcha Bundle Laravel Package

dario_swain/ds-recaptcha-bundle

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Steps to First Use

  1. Installation Run:

    composer require dario_swain/ds-recaptcha-bundle:dev-master
    

    Add the bundle to config/bundles.php (Symfony 4+) or AppKernel.php (Symfony 2/3):

    DS\ReCaptchaBundle\ReCaptchaBundle::class => ['all' => true],
    
  2. Configuration Add ReCAPTCHA keys to config/packages/ds_recaptcha.yaml (Symfony 4+):

    ds_recaptcha:
        public_key:  "YOUR_SITE_KEY"
        private_key: "YOUR_SECRET_KEY"
        locale:      "%locale%"
    

    For Symfony 2/3, use config.yml as shown in the README.

  3. First Form Integration Add the ds_re_captcha field to your form type:

    use Symfony\Component\Form\Extension\Core\Type\FormType;
    
    class ContactType extends AbstractType {
        public function buildForm(FormBuilderInterface $builder, array $options) {
            $builder
                ->add('message', TextareaType::class)
                ->add('captcha', 'ds_re_captcha', ['mapped' => false]) // <-- Key line
                ->add('submit', SubmitType::class);
        }
    }
    
  4. Validation Add validation to your controller:

    use DS\ReCaptchaBundle\Validator\Constraints as ReCaptchaAssert;
    
    /**
     * @ReCaptchaAssert\ValidRecaptcha(message="Invalid CAPTCHA")
     */
    public function contactAction(Request $request) {
        $form = $this->createForm(ContactType::class);
        // ...
    }
    

Implementation Patterns

Common Workflows

  1. Form-Based Validation

    • Use the ds_re_captcha field in forms where user input is critical (e.g., contact forms, registration).
    • Always set mapped => false to avoid binding CAPTCHA to your entity.
  2. Dynamic Key Management

    • Store keys in environment variables (e.g., .env) for security:
      ds_recaptcha:
          public_key:  "%env(RECAPTCHA_SITE_KEY)%"
          private_key: "%env(RECAPTCHA_SECRET_KEY)%"
      
    • Override keys per environment (e.g., config/packages/dev/ds_recaptcha.yaml).
  3. Custom Templates

    • Override the default CAPTCHA template by creating: templates/ds_recaptcha/recaptcha.html.twig.
    • Extend the base template to modify labels, error messages, or styling:
      {% extends 'ds_recaptcha/recaptcha.html.twig' %}
      {% block recaptcha_label %}{{ 'Verify you are human'|trans }}{% endblock %}
      
  4. API/Non-Form Usage

    • Manually validate CAPTCHA responses in controllers:
      use DS\ReCaptchaBundle\ReCaptcha\ReCaptcha;
      
      $recaptcha = $this->get('ds_recaptcha.recaptcha');
      $response = $recaptcha->verify($request->request->get('g-recaptcha-response'));
      if (!$response->isSuccess()) {
          // Handle failure
      }
      
  5. Multi-Language Support

    • Use the locale parameter in config to auto-switch CAPTCHA language:
      ds_recaptcha:
          locale: "%locale%"  # e.g., 'en', 'es'
      
    • Override translations in translations/messages.en.yaml:
      ds_recaptcha:
          captcha_error: "The CAPTCHA was incorrect."
      

Integration Tips

  • Symfony 4+ Flex Compatibility Ensure auto-config and auto-wiring are enabled in config/services.yaml for dependency injection to work seamlessly.

  • Twig Integration Render CAPTCHA directly in Twig templates:

    {{ render(form.captcha.vars.widget) }}
    

    Access errors via:

    {% for error in form.captcha.errors %}
        {{ error.message }}
    {% endfor %}
    
  • Testing Mock the ReCAPTCHA service in PHPUnit:

    $this->container->set('ds_recaptcha.recaptcha', $this->createMock(ReCaptcha::class));
    $mock->method('verify')->willReturn(new Response(true));
    

Gotchas and Tips

Pitfalls

  1. Missing mapped => false

    • Issue: CAPTCHA data binds to your entity, causing validation errors.
    • Fix: Always set mapped => false in form fields.
  2. Incorrect Key Configuration

    • Issue: Silent failures if public_key/private_key are missing or invalid.
    • Fix: Validate keys early (e.g., in a kernel event listener) and log errors.
  3. Caching Static CAPTCHA Tokens

    • Issue: Google ReCAPTCHA v2 requires dynamic tokens per page load.
    • Fix: Avoid caching the g-recaptcha-response token; render the widget fresh each time.
  4. Locale Mismatches

    • Issue: CAPTCHA appears in the wrong language if locale is not set or misconfigured.
    • Fix: Explicitly set locale in config or use a request listener to dynamically update it.
  5. CSRF Token Conflicts

    • Issue: If using Symfony’s CSRF token with ReCAPTCHA, ensure both are included in forms.
    • Fix: Add {{ form_widget(form._token) }} alongside the CAPTCHA widget.

Debugging Tips

  1. Enable Debug Mode

    • Set debug: true in config/packages/ds_recaptcha.yaml to log ReCAPTCHA responses:
      ds_recaptcha:
          debug: true
      
    • Check logs for ds_recaptcha entries.
  2. Validate API Responses

    • Use Google’s test keys to test during development.
    • Manually verify responses via:
      curl -X POST "https://www.google.com/recaptcha/api/siteverify" \
           -d "secret=YOUR_SECRET_KEY&response=USER_RESPONSE"
      
  3. Common Error Messages

    • "Invalid domain": Ensure your site domain matches Google’s registered domains.
    • "Timeout or user input": ReCAPTCHA may fail if the user interacts with the page too slowly. Retry logic may be needed.

Extension Points

  1. Custom Validation Logic

    • Extend the ValidRecaptcha constraint:
      use DS\ReCaptchaBundle\Validator\Constraints\ValidRecaptcha as BaseValidRecaptcha;
      
      class CustomValidRecaptcha extends BaseValidRecaptcha {
          public function validatedBy() { return 'custom_recaptcha_validator'; }
      }
      
    • Register a custom validator service:
      services:
          custom_recaptcha_validator:
              class: App\Validator\CustomRecaptchaValidator
              tags: [validator.constraint_validator]
      
  2. Dynamic Key Switching

    • Override the ReCaptcha service to fetch keys from an API or database:
      $container->set('ds_recaptcha.recaptcha', $container->factory([ReCaptcha::class, 'create'])
          ->arg(0, $container->getParameter('dynamic_public_key'))
          ->arg(1, $container->getParameter('dynamic_private_key'))
      );
      
  3. Event Listeners

    • Listen for ds_recaptcha.verify events to log or modify responses:
      use DS\ReCaptchaBundle\Event\VerifyEvent;
      
      public function onVerify(VerifyEvent $event) {
          if (!$event->getResponse()->isSuccess()) {
              // Custom logic (e.g., ban IP)
          }
      }
      
      Register the listener in services.yaml:
      services:
          App\EventListener\ReCaptchaListener:
              tags:
                  - { name: kernel.event_listener, event: ds_recaptcha.verify, method: onVerify }
      
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.
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
mkwebdesign/filament-watchdog-v5
renatomarinho/laravel-page-speed
zedmagdy/filament-business-hours