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

dmishh/recaptcha-bundle

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Steps

  1. Installation:

    composer require dmishh/recaptcha-bundle
    

    Register the bundle in AppKernel.php:

    new Dmishh\Bundle\RecaptchaBundle\RecaptchaBundle(),
    
  2. Configuration: Add your reCAPTCHA keys to config/packages/dmishh_recaptcha.yaml:

    dmishh_recaptcha:
        public_key:  'YOUR_PUBLIC_KEY'
        private_key: 'YOUR_PRIVATE_KEY'
        use_https:   true
    
  3. First Use Case: Add reCAPTCHA to a form in a controller:

    use Dmishh\Bundle\RecaptchaBundle\Form\Type\RecaptchaType;
    
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder->add('recaptcha', RecaptchaType::class);
    }
    

    Render the form in Twig:

    {{ form_widget(form.recaptcha) }}
    

Implementation Patterns

Service-Oriented Architecture

  • Dependency Injection: The bundle provides a recaptcha.client service for direct API calls:

    $client = $this->get('recaptcha.client');
    $response = $client->verify($token);
    
  • Custom Validation: Extend the default validation logic by creating a custom validator:

    use Symfony\Component\Validator\Constraint;
    use Symfony\Component\Validator\ConstraintValidator;
    
    class CustomRecaptchaValidator extends ConstraintValidator
    {
        public function validate($value, Constraint $constraint)
        {
            $client = $this->container->get('recaptcha.client');
            $result = $client->verify($value);
            if (!$result->isSuccess()) {
                $this->context->buildViolation($constraint->message)
                    ->addViolation();
            }
        }
    }
    

Integration with Forms

  • Form Integration:

    $builder->add('recaptcha', RecaptchaType::class, [
        'mapped' => false,
        'constraints' => [
            new RecaptchaIsTrue(),
        ],
    ]);
    
  • Dynamic Keys: Override keys per form or environment:

    # config/packages/dmishh_recaptcha.yaml
    dmishh_recaptcha:
        public_key:  '%env(RECAPTCHA_PUBLIC_KEY)%'
        private_key: '%env(RECAPTCHA_PRIVATE_KEY)%'
    

Security Component Integration

  • Protect Login Form:
    // src/Security/LoginFormAuthenticator.php
    use Dmishh\Bundle\RecaptchaBundle\Validator\Constraints\RecaptchaIsTrue;
    
    public function getCredentials(Request $request)
    {
        $form = $this->createFormBuilder()
            ->add('username')
            ->add('password')
            ->add('recaptcha', RecaptchaType::class, [
                'constraints' => [new RecaptchaIsTrue()],
            ])
            ->getForm();
    
        $form->handleRequest($request);
        if (!$form->isValid()) {
            throw new AuthenticationException('Invalid credentials or reCAPTCHA.');
        }
        return $form->getData();
    }
    

Gotchas and Tips

Pitfalls

  • Key Mismatch: Ensure public_key and private_key match your reCAPTCHA admin settings. A mismatch will cause silent failures.
  • HTTPS Requirement: If use_https is set to false, reCAPTCHA may fail in production. Always enable HTTPS in production:
    dmishh_recaptcha:
        use_https: true
    
  • Caching Issues: Clear your cache after changing configuration:
    php bin/console cache:clear
    

Debugging

  • API Errors: Check the raw response from the reCAPTCHA API:
    $response = $client->verify($token);
    dump($response->getErrors());
    
  • Form Errors: Validate the form manually to debug:
    $form->submit($data);
    if (!$form->isValid()) {
        foreach ($form->getErrors(true) as $error) {
            dump($error->getMessage());
        }
    }
    

Extension Points

  • Custom Recaptcher: Replace the default Recaptcher implementation by configuring a custom service:
    services:
        recaptcha.client:
            class: App\Service\CustomRecaptchaClient
            arguments: ['@dmishh_recaptcha.options']
    
  • Twig Extensions: Extend Twig templates by adding custom filters or functions:
    // src/Twig/AppExtension.php
    public function getFunctions()
    {
        return [
            new \Twig\TwigFunction('recaptcha_html', [$this->recaptchaService, 'getHtml']),
        ];
    }
    
  • Event Listeners: Listen to reCAPTCHA verification events:
    // src/EventListener/RecaptchaListener.php
    public function onRecaptchaVerify(RecaptchaEvent $event)
    {
        if (!$event->getResponse()->isSuccess()) {
            // Custom logic
        }
    }
    

Performance Tips

  • Lazy Loading: Defer reCAPTCHA verification until absolutely necessary (e.g., after form submission).
  • Rate Limiting: Monitor API calls to avoid hitting reCAPTCHA’s rate limits (typically 1000 requests per minute).
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.
sentix/ai-chatbot
terminal42/code-quality-tools
codifyo/ts-generator-bundle
testo/fiber
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