Installation
composer require couss/recaptcha-bundle
Add to config/bundles.php:
return [
// ...
Couss\FrancisReCaptchaBundle\CoussFrancisReCaptchaBundle::class => ['all' => true],
];
Configuration Publish the default config:
php bin/console recaptcha:install
Update config/packages/couss_francis_recaptcha.yaml with your Google reCAPTCHA v2/v3 site key and secret key.
First Use Case Add the field to a form type:
use Couss\FrancisReCaptchaBundle\Form\Type\ReCaptchaType;
$builder->add('recaptcha', ReCaptchaType::class, [
'mapped' => false, // Always false (not stored in DB)
'type' => 'v2', // 'v2' or 'v3'
'theme' => 'light', // Optional: 'light' or 'dark'
]);
Form Validation The bundle auto-validates reCAPTCHA responses. Add the constraint to your entity:
use Couss\FrancisReCaptchaBundle\Validator\Constraints\ReCaptcha;
/**
* @Assert\Valid()
* @ReCaptcha(type="v2")
*/
private $recaptchaResponse;
Dynamic Field Rendering Use Twig to conditionally render reCAPTCHA:
{% if showRecaptcha %}
{{ form_widget(form.recaptcha) }}
{% endif %}
API/Non-Form Use Manually verify tokens in controllers:
use Couss\FrancisReCaptchaBundle\Service\ReCaptchaService;
$service = $this->container->get(ReCaptchaService::class);
$isValid = $service->verify($responseToken, 'v2');
config/validation.yaml:
Couss\FrancisReCaptchaBundle\Validator\Constraints\ReCaptcha:
message: "Invalid reCAPTCHA. Please try again."
%env(RECAPTCHA_SECRET)% in config for security.Secret Key Exposure
config/packages/couss_francis_recaptcha.yaml to version control.%env% syntax.Version Mismatch
0.5). Adjust in config:
recaptcha:
v3:
min_score: 0.7
Caching Issues
Form Submission Quirks
recaptcha field is hidden. Ensure your frontend sends the token via JavaScript:
grecaptcha.ready(() => {
grecaptcha.execute('SITE_KEY', { action: 'submit' }).then(token => {
document.getElementById('recaptcha_token').value = token;
});
});
Enable Debug Mode: Add to config:
recaptcha:
debug: true
Logs verification attempts to var/log/dev.log.
Test Locally: Use Google’s test keys:
6LeIxAcTAAAAAJcZVRqyHh71UMIEGNQ_MXjiZKhI6LeIxAcTAAAAAGG-vFI1TnRWxMZNFuojJ4WifJWeCustom Verifier
Implement Couss\FrancisReCaptchaBundle\Service\ReCaptchaVerifierInterface for enterprise APIs (e.g., proxy verification).
Twig Extensions Add custom filters to modify reCAPTCHA HTML:
{{ form_widget(form.recaptcha) | recaptcha_attr({'class': 'my-class'}) }}
Extend the bundle’s ReCaptchaType to add this filter.
Event Listeners
Subscribe to recaptcha.verify events to log failed attempts:
// src/EventListener/ReCaptchaListener.php
public function onVerify(ReCaptchaEvent $event) {
if (!$event->isValid()) {
// Log IP, user agent, etc.
}
}
How can I help you explore Laravel packages today?