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

Recaptcher Laravel Package

dmishh/recaptcher

Recaptcher is a lightweight PHP library for Google reCAPTCHA, based on the official phplib. It supports the “lang” option and is designed to integrate cleanly with Symfony2 RecaptchaBundle. Includes basic roadmap for timeouts and more translations.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation:

    composer require dmishh/recaptcher
    

    Add to composer.json if not using autoload:

    "autoload": {
        "psr-4": {
            "App\\": "app/",
            "Dmishh\\Recaptcher\\": "vendor/dmishh/recaptcher/src/"
        }
    }
    

    Run composer dump-autoload.

  2. First Use Case: Register the service in Laravel (e.g., in AppServiceProvider):

    public function register()
    {
        $this->app->singleton('recaptcher', function ($app) {
            return new \Dmishh\Recaptcher\Recaptcher(
                config('services.recaptcha.site_key'),
                config('services.recaptcha.secret_key')
            );
        });
    }
    
  3. Configuration: Add to config/services.php:

    'recaptcha' => [
        'site_key' => env('RECAPTCHA_SITE_KEY'),
        'secret_key' => env('RECAPTCHA_SECRET_KEY'),
        'lang' => env('RECAPTCHA_LANG', 'en'), // Optional
    ],
    
  4. Basic Usage in a Form Controller:

    use Dmishh\Recaptcher\Recaptcher;
    
    public function store(Request $request, Recaptcher $recaptcher)
    {
        $response = $recaptcher->verify($request->input('g-recaptcha-response'));
        if (!$response->success()) {
            return back()->withErrors(['recaptcha' => 'Invalid verification']);
        }
        // Proceed with form submission
    }
    
  5. Blade Integration:

    {!! Recaptcha::render() !!}
    

    (Ensure Recaptcha facade is registered in config/app.php.)


Implementation Patterns

Common Workflows

1. Form Validation

  • Manual Validation:
    $response = $recaptcher->verify($request->input('g-recaptcha-response'));
    if (!$response->success()) {
        return back()->withErrors(['recaptcha' => 'Invalid']);
    }
    
  • Laravel Validation Rule: Create a custom rule:
    use Dmishh\Recaptcher\Recaptcher;
    use Illuminate\Contracts\Validation\Rule;
    
    class RecaptchaRule implements Rule {
        protected $recaptcher;
    
        public function __construct(Recaptcher $recaptcher) {
            $this->recaptcher = $recaptcher;
        }
    
        public function passes($attribute, $value) {
            return $this->recaptcher->verify($value)->success();
        }
    
        public function message() {
            return 'The :attribute is invalid.';
        }
    }
    
    Use in validation:
    $validator = Validator::make($request->all(), [
        'g-recaptcha-response' => ['required', new RecaptchaRule($recaptcher)],
    ]);
    

2. Dynamic Language Support

Pass language dynamically:

$recaptcher = new \Dmishh\Recaptcher\Recaptcher($siteKey, $secretKey, ['lang' => $request->input('lang', 'en')]);

3. API Integration

For API endpoints, verify and return JSON:

public function apiSubmit(Request $request) {
    $response = $recaptcher->verify($request->input('token'));
    return response()->json(['valid' => $response->success()]);
}

4. Testing

Mock the Recaptcher class in tests:

$mock = Mockery::mock(\Dmishh\Recaptcher\Recaptcher::class);
$mock->shouldReceive('verify')->andReturn(new \Dmishh\Recaptcher\Response(true));
$this->app->instance(\Dmishh\Recaptcher\Recaptcher::class, $mock);

Integration Tips

1. Laravel Facade

Register a facade for cleaner usage:

// config/app.php
'aliases' => [
    'Recaptcha' => \App\Facades\Recaptcha::class,
],

Create facade:

namespace App\Facades;
use Illuminate\Support\Facades\Facade;

class Recaptcha extends Facade {
    protected static function getFacadeAccessor() {
        return 'recaptcher';
    }
}

Usage:

Recaptcha::verify($response)->success();

2. Environment-Specific Keys

Use Laravel's .env for keys:

RECAPTCHA_SITE_KEY=your_site_key
RECAPTCHA_SECRET_KEY=your_secret_key

3. Error Handling

Handle errors gracefully:

try {
    $response = $recaptcher->verify($token);
    if (!$response->success()) {
        throw new \Exception('Recaptcha failed: ' . $response->getError());
    }
} catch (\Exception $e) {
    Log::error($e->getMessage());
    return back()->withErrors(['recaptcha' => 'Service unavailable']);
}

4. Caching Responses

Cache responses to reduce API calls (e.g., for high-traffic forms):

$cacheKey = 'recaptcha_' . md5($responseToken);
$cached = Cache::get($cacheKey);
if (!$cached) {
    $response = $recaptcher->verify($responseToken);
    Cache::put($cacheKey, $response, now()->addMinutes(5));
} else {
    $response = $cached;
}

Gotchas and Tips

Pitfalls

1. Deprecated reCAPTCHA v2

  • The package supports reCAPTCHA v2 (checkbox/invisible). If using v3, this package will not work—migrate to a v3-compatible package like spatie/laravel-recaptcha.
  • Check the response format; v3 returns a score instead of a boolean.

2. Missing g-recaptcha-response

  • Ensure your form includes the hidden field:
    <input type="hidden" name="g-recaptcha-response" id="g-recaptcha-response">
    
  • If using JavaScript, verify the token is populated before submission.

3. Language Parameter

  • The lang parameter must be a valid reCAPTCHA language code (e.g., en, es). Invalid codes may return false negatives.
  • Defaults to en if not specified.

4. Rate Limiting

  • Google may temporarily block requests if you exceed their rate limits. Handle 503 errors gracefully.

5. No Built-in v3 Support

  • The package lacks support for reCAPTCHA v3’s score-based verification. If you need v3, avoid this package.

Debugging Tips

1. Enable Debug Mode

  • Check the raw response for debugging:
    $response = $recaptcher->verify($token);
    dd($response->getRawResponse()); // Inspect Google's JSON response
    
  • Common error codes:
    • missing-input-secret: Invalid secret key.
    • invalid-domain: Domain not registered in Google reCAPTCHA admin.
    • timeout-or-duplicate: Token used multiple times or expired.

2. Verify Domain in Google Admin

  • Ensure your site’s domain is whitelisted in the reCAPTCHA admin console.
  • For localhost testing, add localhost as an allowed domain.

3. Check for JavaScript Errors

  • If the reCAPTCHA widget fails to load, inspect browser console for errors (e.g., missing API key or blocked by ad-blockers).

4. Test with Known Valid/Invalid Tokens

  • Use Google’s test tokens:
    • Valid: 03AHJ_Vuu09... (from the console).
    • Invalid: invalid-token.

Extension Points

1. Custom Response Handling

Extend the Response class to add custom logic:

class CustomResponse extends \Dmishh\Recaptcher\Response {
    public function isScoreValid() {
        if ($this->success()) {
            $score = $this->getRawResponse()['score'] ?? 0;
            return $score >= 0.5; // Custom threshold
        }
        return false;
    }
}

Override the factory method in Recaptcher

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