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.
To begin using arcaptcha/arcaptcha-laravel, follow these minimal steps:
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,
],
Publish Configuration
php artisan vendor:publish --provider="Mohammadv184\ArCaptcha\Laravel\ArCaptchaServiceProvider"
This generates config/arcaptcha.php.
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
First Use Case: Basic Form Protection
<!DOCTYPE html>
<html>
<head>
@arcaptchaScript
</head>
<body>
<form method="POST" action="/submit">
@csrf
@arcaptchaWidget
<button type="submit">Submit</button>
</form>
</body>
</html>
use Illuminate\Support\Facades\Validator;
$validator = Validator::make(request()->all(), [
'arcaptcha-token' => 'arcaptcha',
]);
if ($validator->fails()) {
return back()->withErrors($validator)->onlyInput();
}
Frontend Integration
@arcaptchaScript in <head> and @arcaptchaWidget inside forms for minimal setup.@arcaptchaWidget(['lang' => 'en', 'theme' => 'dark'])
or via facade:
ArCaptcha::getWidget(['size' => 'invisible', 'callback' => 'handleToken']);
{!! ArCaptcha::getWidget(['size' => 'invisible', 'callback' => 'submitForm']) !!}
<script>
function submitForm(token) {
document.getElementById('form').submit();
}
</script>
Backend Validation
arcaptcha rule to your form requests or controllers:
public function rules()
{
return [
'arcaptcha-token' => 'required|arcaptcha',
];
}
resources/lang/[LANG]/validation.php:
'arcaptcha' => 'The CAPTCHA verification failed. Please try again.',
API Interaction
ArCaptcha facade for direct API calls:
$token = request()->input('arcaptcha-token');
$result = ArCaptcha::verify($token);
if (!ArCaptcha::verify($token)) {
return back()->withErrors(['arcaptcha' => 'Invalid CAPTCHA']);
}
Conditional CAPTCHA Dynamically enable CAPTCHA based on user risk (e.g., IP reputation):
if ($user->isHighRisk()) {
$rules['arcaptcha-token'] = 'required|arcaptcha';
}
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');
}
Testing
$this->mock(ArCaptcha::class, function ($mock) {
$mock->shouldReceive('verify')
->once()
->andReturn(true);
});
$this->blade('@arcaptchaScript')->assertSee('arcaptcha.js');
Localization
lang option to getWidget():
@arcaptchaWidget(['lang' => 'fa']) <!-- Persian -->
validation.php.API Dependency
Invisible Mode Quirks
callback function must be globally scoped (pollutes global namespace).(function(callback) {
function handleToken(token) { callback(token); }
ArCaptcha.getWidget({ callback: 'handleToken' });
})(submitForm);
Validation Rule Assumptions
arcaptcha rule assumes ArCaptcha returns a boolean. Custom responses may break validation.$response = ArCaptcha::verify($token);
if ($response !== true) {
throw new \InvalidArgumentException('CAPTCHA verification failed');
}
Blade Directive Conflicts
@arcaptchaScript may conflict with existing JS bundles (e.g., Vite/Webpack).<script src="https://arcaptcha.ir/js/arcaptcha.js"></script>
Rate Limiting
ARCAPTCHA_VERIFY_EXCEPTION_VALUE config to handle failures gracefully.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',
],
],
Inspect Widget Output Check the rendered HTML for errors:
{!! ArCaptcha::getWidget() !!}
Look for missing attributes or JavaScript errors in the browser console.
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"
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;
});
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.
Event Listeners Listen for CAPTCHA events (e.g., verification failures):
ArCaptcha::failed(function ($token) {
Log::warning("CAPTCHA failed for token: {$token}");
});
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.
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
How can I help you explore Laravel packages today?