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 Php Laravel Package

arcaptcha/arcaptcha-php

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation

    composer require arcaptcha/arcaptcha-php
    

    Add the service provider to config/app.php (if not auto-discovered):

    'providers' => [
        Arcaptcha\ArcaptchaServiceProvider::class,
    ],
    
  2. Configuration Publish the config file:

    php artisan vendor:publish --provider="Arcaptcha\ArcaptchaServiceProvider"
    

    Update config/arcaptcha.php with your ArCaptcha API keys:

    'api_key' => env('ARCAPTCHA_API_KEY'),
    'site_key' => env('ARCAPTCHA_SITE_KEY'),
    
  3. First Use Case: Verify a CAPTCHA

    use Arcaptcha\Arcaptcha;
    
    $response = Arcaptcha::verify($request->input('arcaptcha_token'));
    if ($response->success()) {
        // CAPTCHA is valid, proceed with form submission
    }
    
  4. Displaying the CAPTCHA Add this to your Blade template:

    {!! ArCaptcha::render() !!}
    

    Or use the JS snippet from ArCaptcha’s dashboard.


Implementation Patterns

Common Workflows

  1. Form Submission Validation Use Laravel’s validation rules with a custom rule:

    use Arcaptcha\ArcaptchaValidationRule;
    
    $request->validate([
        'arcaptcha_token' => new ArcaptchaValidationRule(),
    ]);
    
  2. Dynamic CAPTCHA Rendering Conditionally render CAPTCHA based on user roles or actions:

    @if(auth()->user()->is_vip)
        <!-- Skip CAPTCHA for VIPs -->
    @else
        {!! ArCaptcha::render() !!}
    @endif
    
  3. API Integration For API endpoints, verify CAPTCHA tokens in middleware:

    namespace App\Http\Middleware;
    
    use Arcaptcha\Arcaptcha;
    use Closure;
    
    class VerifyArcaptcha
    {
        public function handle($request, Closure $next)
        {
            $response = Arcaptcha::verify($request->arcaptcha_token);
            if (!$response->success()) {
                return response()->json(['error' => 'Invalid CAPTCHA'], 403);
            }
            return $next($request);
        }
    }
    
  4. Rate Limiting CAPTCHA Attempts Combine with Laravel’s throttle middleware to limit CAPTCHA verification attempts:

    Route::post('/submit', [Controller::class, 'submit'])
        ->middleware(['throttle:5,1', 'verified.arcaptcha']);
    

Integration Tips

  • Laravel Mix/Webpack If using ArCaptcha’s JS widget, ensure it’s loaded after jQuery:

    // resources/js/app.js
    window.$ = window.jQuery = require('jquery');
    require('arcaptcha-widget');
    
  • Caching Responses Cache CAPTCHA verification responses for a short duration (e.g., 5 minutes) to reduce API calls:

    $response = Cache::remember("arcaptcha_{$token}", 300, function() use ($token) {
        return Arcaptcha::verify($token);
    });
    
  • Multi-Language Support Use ArCaptcha’s lang parameter to support multiple languages:

    {!! ArCaptcha::render(['lang' => app()->getLocale()]) !!}
    

Gotchas and Tips

Pitfalls

  1. API Key Leaks

    • Risk: Exposing ARCAPTCHA_API_KEY or ARCAPTCHA_SITE_KEY in client-side code or logs.
    • Fix: Use environment variables and never hardcode keys. Validate server-side only.
  2. Token Expiry

    • ArCaptcha tokens expire after 1 hour. Ensure your form submission handles this gracefully (e.g., re-render CAPTCHA on expiry).
  3. IP-Based Rate Limits

    • ArCaptcha may block IPs with excessive verification failures. Implement client-side delays or exponential backoff in your frontend.
  4. Missing CSRF Protection

    • Always pair CAPTCHA verification with Laravel’s VerifyCsrfToken middleware to prevent CSRF attacks.
  5. False Positives/Negatives

    • ArCaptcha may incorrectly flag valid submissions or miss bots. Test thoroughly with edge cases (e.g., slow connections, ad-blockers).

Debugging

  • Enable Debug Mode Set debug to true in config/arcaptcha.php to log API responses:

    'debug' => env('APP_DEBUG', false),
    
  • Check API Response Codes ArCaptcha returns HTTP codes:

    • 200: Success.
    • 400: Invalid token.
    • 429: Rate limit exceeded.
    • 500: Server error. Log $response->getStatusCode() for troubleshooting.
  • Test with Known Tokens Use ArCaptcha’s test tokens (e.g., 03AHJ6_1234567890ABCDEF0123456789ABCDEF) to verify your setup:

    $response = Arcaptcha::verify('03AHJ6_1234567890ABCDEF0123456789ABCDEF');
    

Extension Points

  1. Custom Validation Messages Override default validation messages in app/Providers/AppServiceProvider.php:

    use Arcaptcha\ArcaptchaValidationRule;
    
    ArcaptchaValidationRule::extend(function ($message, $attribute, $rule, $parameters) {
        return 'custom CAPTCHA error message';
    });
    
  2. Extend the Response Object Add custom methods to the ArcaptchaResponse class by extending it:

    namespace App\Services;
    
    use Arcaptcha\ArcaptchaResponse;
    
    class CustomArcaptchaResponse extends ArcaptchaResponse
    {
        public function isHuman()
        {
            return $this->success() && $this->getScore() > 0.9;
        }
    }
    

    Bind it in AppServiceProvider:

    Arcaptcha::setResponseClass(CustomArcaptchaResponse::class);
    
  3. Webhook Integration Use ArCaptcha’s webhook API to log verification events. Set up a Laravel route to handle webhook payloads:

    Route::post('/arcaptcha-webhook', [WebhookController::class, 'handle']);
    
  4. Proxy Support If behind a proxy, configure ArCaptcha’s HTTP client to respect it:

    Arcaptcha::setClient(new \GuzzleHttp\Client([
        'proxy' => 'http://your-proxy:port',
    ]));
    

Configuration Quirks

  • HTTPS Requirement ArCaptcha’s API requires HTTPS. Ensure your Laravel app uses HTTPS in production (e.g., via APP_URL in .env):

    APP_URL=https://yourdomain.com
    
  • CORS Issues If using ArCaptcha’s JS widget, ensure your Laravel app’s CORS settings allow requests to ArCaptcha’s domain. Use the fruitcake/laravel-cors package if needed.

  • Locale Fallback ArCaptcha defaults to en if the specified language isn’t supported. Test with unsupported locales to avoid unexpected behavior.

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