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

Friendly Captcha Bundle Laravel Package

cors/friendly-captcha-bundle

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation:

    composer require cors/friendly-captcha-bundle
    

    Register the bundle in config/bundles.php (Symfony 4.3+):

    return [
        // ...
        CORS\Bundle\FriendlyCaptchaBundle\CORSFriendlyCaptchaBundle::class => ['all' => true],
    ];
    
  2. Configuration (.env or config/packages/cors_friendly_captcha.yaml):

    cors_friendly_captcha:
        sitekey: "YOUR_SITEKEY"
        secret: "YOUR_SECRET"
        use_eu_endpoints: true
    
  3. First Use Case: Add the Twig field to a form (e.g., resources/views/contact.html.twig):

    {{ render(controller('CORS\Bundle\FriendlyCaptchaBundle\Controller\FriendlyCaptchaController::renderCaptcha')) }}
    

    Validate the response in a controller:

    use CORS\Bundle\FriendlyCaptchaBundle\Validator\Constraints\FriendlyCaptcha;
    
    #[Route('/contact', name: 'contact')]
    public function contact(Request $request): Response
    {
        $form = $this->createFormBuilder()
            ->add('name', TextType::class)
            ->add('email', EmailType::class)
            ->add('captcha', FriendlyCaptchaType::class) // Auto-injected by bundle
            ->getForm();
    
        $form->handleRequest($request);
    
        if ($form->isSubmitted() && $form->isValid()) {
            // Handle submission
        }
        // ...
    }
    

Implementation Patterns

Common Workflows

  1. Form Integration:

    • Use FriendlyCaptchaType in Symfony forms (auto-validates via FriendlyCaptcha constraint).
    • Example:
      $builder->add('captcha', FriendlyCaptchaType::class, [
          'mapped' => false, // Captcha is not a form field (hidden)
          'label' => 'Verify you are human',
      ]);
      
  2. Dynamic Rendering:

    • Render the captcha in Twig/Blade via the controller:
      {{ render(controller('CORS\Bundle\FriendlyCaptchaBundle\Controller\FriendlyCaptchaController::renderCaptcha', {
          'theme': 'dark', // Optional: 'light'|'dark'
          'size': 'normal' // Optional: 'normal'|'compact'
      })) }}
      
  3. API Validation:

    • Validate captcha responses in API endpoints:
      use Symfony\Component\Validator\Constraints as Assert;
      
      #[Assert\FriendlyCaptcha(
          message: 'Captcha validation failed.',
          siteSecret: '%env(FRIENDLY_CAPTCHA_SECRET)%'
      )]
      public $captchaResponse;
      
  4. Custom Themes/Endpoints:

    • Override endpoints in config (e.g., for GDPR compliance):
      cors_friendly_captcha:
          puzzle:
              eu_endpoint: "https://your-custom-endpoint.com/puzzle"
      
  5. Laravel-Specific Adaptation (Symfony bundle in Laravel):

    • Use spatie/symfony-bundle to integrate Symfony bundles in Laravel.
    • Register the bundle in config/app.php:
      'providers' => [
          // ...
          CORS\Bundle\FriendlyCaptchaBundle\CORSFriendlyCaptchaBundle::class,
      ],
      
    • Publish config:
      php artisan vendor:publish --provider="CORS\Bundle\FriendlyCaptchaBundle\CORSFriendlyCaptchaBundle"
      

Gotchas and Tips

Pitfalls

  1. Missing .env Configuration:

    • Ensure sitekey and secret are set in .env or config. The bundle throws InvalidArgumentException if missing.
    • Fix: Add to .env:
      FRIENDLY_CAPTCHA_SITEKEY=your_sitekey
      FRIENDLY_CAPTCHA_SECRET=your_secret
      
  2. CORS Issues:

    • If using EU endpoints, ensure your server allows requests to eu-api.friendlycaptcha.eu.
    • Debug: Check browser console for blocked requests or use curl to test:
      curl -X POST https://eu-api.friendlycaptcha.eu/api/v1/siteverify -d "secret=YOUR_SECRET&response=TOKEN"
      
  3. Validation Failures:

    • The FriendlyCaptcha constraint fails silently if the response is invalid. Add custom error messages:
      #[Assert\FriendlyCaptcha(
          message: 'The captcha response is invalid. Please try again.',
          siteSecret: '%env(FRIENDLY_CAPTCHA_SECRET)%'
      )]
      
  4. Laravel-Specific:

    • Symfony bundles in Laravel may require manual service registration. Use spatie/symfony-bundle or manually bind services in AppServiceProvider:
      public function register()
      {
          $this->app->register(CORSFriendlyCaptchaBundle::class);
      }
      

Debugging Tips

  1. Log Responses:

    • Enable debug mode in config/packages/cors_friendly_captcha.yaml:
      cors_friendly_captcha:
          debug: true
      
    • Check storage/logs/laravel.log for API response details.
  2. Manual API Testing:

    • Test the validation endpoint directly:
      curl -X POST https://api.friendlycaptcha.com/api/v1/siteverify \
           -d "secret=YOUR_SECRET" \
           -d "response=TOKEN_FROM_FRONTEND"
      
    • Expected success response:
      {"success":true,"error-codes":[],"challenge_ts":"2025-06-17T12:00:00Z"}
      
  3. Theme/Size Issues:

    • If the captcha doesn’t render, verify the theme and size parameters are supported (see FriendlyCaptcha docs).

Extension Points

  1. Custom Validation Logic:

    • Extend the FriendlyCaptchaValidator service:
      // config/services.yaml
      CORS\Bundle\FriendlyCaptchaBundle\Validator\FriendlyCaptchaValidator:
          arguments:
              $customLogic: '@app.custom_captcha_validator'
      
    • Create a custom validator:
      class CustomCaptchaValidator
      {
          public function validate(string $response, string $secret): bool
          {
              // Add custom logic (e.g., IP whitelisting)
              return true;
          }
      }
      
  2. Override Templates:

    • Publish and override Twig templates:
      php artisan vendor:publish --tag=cors_friendly_captcha.templates
      
    • Modify templates/captcha.html.twig to customize rendering.
  3. Event Listeners:

    • Listen to captcha events (e.g., captcha.validated):
      use CORS\Bundle\FriendlyCaptchaBundle\Event\CaptchaEvent;
      
      public function onCaptchaValidated(CaptchaEvent $event)
      {
          if (!$event->isValid()) {
              // Log failed attempts
          }
      }
      
    • Register in config/services.yaml:
      listeners:
          CORS\Bundle\FriendlyCaptchaBundle\Event\CaptchaEvent::CAPTCHA_VALIDATED:
              - [App\Listener\CaptchaListener, onCaptchaValidated]
      
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