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

Arcaptcha Laravel Laravel Package

arcaptcha/arcaptcha-laravel

Laravel integration for ArCaptcha (PHP 7.3+). Install via Composer, publish config, set ARCAPTCHA site/secret keys in .env, embed the widget in Blade forms, and verify the submitted token server-side using the provided service/facade.

View on GitHub
Deep Wiki
Context7

Getting Started

To begin using arcaptcha/arcaptcha-laravel, follow these minimal steps:

  1. Install the Package

    composer require arcaptcha/arcaptcha-laravel
    

    Laravel 5.5+ auto-discovers the package, but manually register the service provider if needed:

    // config/app.php
    'providers' => [
        Mohammadv184\ArCaptcha\Laravel\ArCaptchaServiceProvider::class,
    ],
    'aliases' => [
        'ArCaptcha' => Mohammadv184\ArCaptcha\Laravel\Facade\ArCaptcha::class,
    ],
    
  2. Publish Configuration

    php artisan vendor:publish --provider="Mohammadv184\ArCaptcha\Laravel\ArCaptchaServiceProvider"
    

    This generates config/arcaptcha.php.

  3. Configure .env Add your ArCaptcha credentials:

    ARCAPTCHA_SITE_KEY=your_site_key
    ARCAPTCHA_SECRET_KEY=your_secret_key
    ARCAPTCHA_VERIFY_EXCEPTION_VALUE=true  # Optional fallback
    
  4. First Use Case: Basic Form Protection

    • Blade Template:
      <!DOCTYPE html>
      <html>
        <head>
          @arcaptchaScript
        </head>
        <body>
          <form method="POST" action="/submit">
            @csrf
            @arcaptchaWidget
            <button type="submit">Submit</button>
          </form>
        </body>
      </html>
      
    • Validation:
      use Illuminate\Support\Facades\Validator;
      
      $validator = Validator::make(request()->all(), [
          'arcaptcha-token' => 'arcaptcha',
      ]);
      
      if ($validator->fails()) {
          return back()->withErrors($validator)->onlyInput();
      }
      

Implementation Patterns

Core Workflows

  1. Frontend Integration

    • Blade Directives: Use @arcaptchaScript in <head> and @arcaptchaWidget inside forms for minimal setup.
    • Dynamic Widgets: Pass options to customize appearance/behavior:
      @arcaptchaWidget(['lang' => 'en', 'theme' => 'dark'])
      
      or via facade:
      ArCaptcha::getWidget(['size' => 'invisible', 'callback' => 'handleToken']);
      
    • Invisible Mode: Ideal for frictionless UX (e.g., checkout flows):
      {!! ArCaptcha::getWidget(['size' => 'invisible', 'callback' => 'submitForm']) !!}
      <script>
        function submitForm(token) {
          document.getElementById('form').submit();
        }
      </script>
      
  2. Backend Validation

    • Leverage Laravel Validation: Add the arcaptcha rule to your form requests or controllers:
      public function rules()
      {
          return [
              'arcaptcha-token' => 'required|arcaptcha',
          ];
      }
      
    • Custom Error Messages: Extend resources/lang/[LANG]/validation.php:
      'arcaptcha' => 'The CAPTCHA verification failed. Please try again.',
      
  3. API Interaction

    • Facade Methods: Use ArCaptcha facade for direct API calls:
      $token = request()->input('arcaptcha-token');
      $result = ArCaptcha::verify($token);
      
    • Manual Verification: For custom logic, bypass the validator:
      if (!ArCaptcha::verify($token)) {
          return back()->withErrors(['arcaptcha' => 'Invalid CAPTCHA']);
      }
      

Advanced Patterns

  1. Conditional CAPTCHA Dynamically enable CAPTCHA based on user risk (e.g., IP reputation):

    if ($user->isHighRisk()) {
        $rules['arcaptcha-token'] = 'required|arcaptcha';
    }
    
  2. Fallback Mechanisms Handle API failures gracefully:

    try {
        $valid = ArCaptcha::verify($token);
    } catch (\Exception $e) {
        // Fallback: Use a static token or disable CAPTCHA
        $valid = config('arcaptcha.verify_exception_value');
    }
    
  3. Testing

    • Mock API Responses: Use Laravel’s HTTP client to mock ArCaptcha:
      $this->mock(ArCaptcha::class, function ($mock) {
          $mock->shouldReceive('verify')
               ->once()
               ->andReturn(true);
      });
      
    • Blade Testing: Test directives in feature tests:
      $this->blade('@arcaptchaScript')->assertSee('arcaptcha.js');
      
  4. Localization

    • Language Support: Pass lang option to getWidget():
      @arcaptchaWidget(['lang' => 'fa'])  <!-- Persian -->
      
    • Validation Messages: Override per locale in validation.php.

Gotchas and Tips

Pitfalls

  1. API Dependency

    • Issue: ArCaptcha’s API may change without notice, breaking validation.
    • Fix: Monitor the ArCaptcha API docs and update the package or fork it if needed.
  2. Invisible Mode Quirks

    • Issue: The callback function must be globally scoped (pollutes global namespace).
    • Fix: Use a namespace wrapper or IIFE:
      (function(callback) {
          function handleToken(token) { callback(token); }
          ArCaptcha.getWidget({ callback: 'handleToken' });
      })(submitForm);
      
  3. Validation Rule Assumptions

    • Issue: The arcaptcha rule assumes ArCaptcha returns a boolean. Custom responses may break validation.
    • Fix: Extend the validator or use manual verification:
      $response = ArCaptcha::verify($token);
      if ($response !== true) {
          throw new \InvalidArgumentException('CAPTCHA verification failed');
      }
      
  4. Blade Directive Conflicts

    • Issue: @arcaptchaScript may conflict with existing JS bundles (e.g., Vite/Webpack).
    • Fix: Manually include the script:
      <script src="https://arcaptcha.ir/js/arcaptcha.js"></script>
      
  5. Rate Limiting

    • Issue: ArCaptcha may throttle requests during testing.
    • Fix: Use the ARCAPTCHA_VERIFY_EXCEPTION_VALUE config to handle failures gracefully.

Debugging Tips

  1. Verify API Calls Enable Laravel’s logging for HTTP clients:

    // config/logging.php
    'channels' => [
        'single' => [
            'driver' => 'single',
            'path' => storage_path('logs/arcaptcha.log'),
            'level' => 'debug',
        ],
    ],
    
  2. Inspect Widget Output Check the rendered HTML for errors:

    {!! ArCaptcha::getWidget() !!}
    

    Look for missing attributes or JavaScript errors in the browser console.

  3. Token Validation Manually test tokens using ArCaptcha’s API:

    curl -X POST https://arcaptcha.ir/api/verify \
         -d "token=YOUR_TOKEN" \
         -d "secret=YOUR_SECRET_KEY"
    

Extension Points

  1. Custom Validator Extend the arcaptcha rule for additional logic:

    Validator::extend('arcaptcha', function ($attribute, $value, $parameters, $validator) {
        $result = ArCaptcha::verify($value);
        if ($result !== true) {
            $validator->addReplacer('arcaptcha', function ($message, $attribute, $rule, $parameters) {
                return str_replace(':attribute', 'CAPTCHA', $message);
            });
        }
        return $result;
    });
    
  2. Widget Customization Override the widget template by publishing views:

    php artisan vendor:publish --tag=arcaptcha-views
    

    Then modify resources/views/vendor/arcaptcha/widget.blade.php.

  3. Event Listeners Listen for CAPTCHA events (e.g., verification failures):

    ArCaptcha::failed(function ($token) {
        Log::warning("CAPTCHA failed for token: {$token}");
    });
    

Configuration Quirks

  1. Environment Variables Ensure ARCAPTCHA_SITE_KEY and ARCAPTCHA_SECRET_KEY are set in .env. The package does not fall back to config/arcaptcha.php for these values.

  2. Default Values The ARCAPTCHA_VERIFY_EXCEPTION_VALUE config defaults to true. Set it to false to fail validation on API errors:

    ARCAPTCHA_VERIFY_EXCEPTION_VALUE=false
    
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.
terminal42/code-quality-tools
codifyo/ts-generator-bundle
andydefer/laravel-cluster
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