dario_swain/ds-recaptcha-bundle
Installation Run:
composer require dario_swain/ds-recaptcha-bundle:dev-master
Add the bundle to config/bundles.php (Symfony 4+) or AppKernel.php (Symfony 2/3):
DS\ReCaptchaBundle\ReCaptchaBundle::class => ['all' => true],
Configuration
Add ReCAPTCHA keys to config/packages/ds_recaptcha.yaml (Symfony 4+):
ds_recaptcha:
public_key: "YOUR_SITE_KEY"
private_key: "YOUR_SECRET_KEY"
locale: "%locale%"
For Symfony 2/3, use config.yml as shown in the README.
First Form Integration
Add the ds_re_captcha field to your form type:
use Symfony\Component\Form\Extension\Core\Type\FormType;
class ContactType extends AbstractType {
public function buildForm(FormBuilderInterface $builder, array $options) {
$builder
->add('message', TextareaType::class)
->add('captcha', 'ds_re_captcha', ['mapped' => false]) // <-- Key line
->add('submit', SubmitType::class);
}
}
Validation Add validation to your controller:
use DS\ReCaptchaBundle\Validator\Constraints as ReCaptchaAssert;
/**
* @ReCaptchaAssert\ValidRecaptcha(message="Invalid CAPTCHA")
*/
public function contactAction(Request $request) {
$form = $this->createForm(ContactType::class);
// ...
}
Form-Based Validation
ds_re_captcha field in forms where user input is critical (e.g., contact forms, registration).mapped => false to avoid binding CAPTCHA to your entity.Dynamic Key Management
.env) for security:
ds_recaptcha:
public_key: "%env(RECAPTCHA_SITE_KEY)%"
private_key: "%env(RECAPTCHA_SECRET_KEY)%"
config/packages/dev/ds_recaptcha.yaml).Custom Templates
templates/ds_recaptcha/recaptcha.html.twig.{% extends 'ds_recaptcha/recaptcha.html.twig' %}
{% block recaptcha_label %}{{ 'Verify you are human'|trans }}{% endblock %}
API/Non-Form Usage
use DS\ReCaptchaBundle\ReCaptcha\ReCaptcha;
$recaptcha = $this->get('ds_recaptcha.recaptcha');
$response = $recaptcha->verify($request->request->get('g-recaptcha-response'));
if (!$response->isSuccess()) {
// Handle failure
}
Multi-Language Support
locale parameter in config to auto-switch CAPTCHA language:
ds_recaptcha:
locale: "%locale%" # e.g., 'en', 'es'
translations/messages.en.yaml:
ds_recaptcha:
captcha_error: "The CAPTCHA was incorrect."
Symfony 4+ Flex Compatibility
Ensure auto-config and auto-wiring are enabled in config/services.yaml for dependency injection to work seamlessly.
Twig Integration Render CAPTCHA directly in Twig templates:
{{ render(form.captcha.vars.widget) }}
Access errors via:
{% for error in form.captcha.errors %}
{{ error.message }}
{% endfor %}
Testing Mock the ReCAPTCHA service in PHPUnit:
$this->container->set('ds_recaptcha.recaptcha', $this->createMock(ReCaptcha::class));
$mock->method('verify')->willReturn(new Response(true));
Missing mapped => false
mapped => false in form fields.Incorrect Key Configuration
public_key/private_key are missing or invalid.Caching Static CAPTCHA Tokens
g-recaptcha-response token; render the widget fresh each time.Locale Mismatches
locale is not set or misconfigured.locale in config or use a request listener to dynamically update it.CSRF Token Conflicts
CSRF token with ReCAPTCHA, ensure both are included in forms.{{ form_widget(form._token) }} alongside the CAPTCHA widget.Enable Debug Mode
debug: true in config/packages/ds_recaptcha.yaml to log ReCAPTCHA responses:
ds_recaptcha:
debug: true
ds_recaptcha entries.Validate API Responses
curl -X POST "https://www.google.com/recaptcha/api/siteverify" \
-d "secret=YOUR_SECRET_KEY&response=USER_RESPONSE"
Common Error Messages
Custom Validation Logic
ValidRecaptcha constraint:
use DS\ReCaptchaBundle\Validator\Constraints\ValidRecaptcha as BaseValidRecaptcha;
class CustomValidRecaptcha extends BaseValidRecaptcha {
public function validatedBy() { return 'custom_recaptcha_validator'; }
}
services:
custom_recaptcha_validator:
class: App\Validator\CustomRecaptchaValidator
tags: [validator.constraint_validator]
Dynamic Key Switching
ReCaptcha service to fetch keys from an API or database:
$container->set('ds_recaptcha.recaptcha', $container->factory([ReCaptcha::class, 'create'])
->arg(0, $container->getParameter('dynamic_public_key'))
->arg(1, $container->getParameter('dynamic_private_key'))
);
Event Listeners
ds_recaptcha.verify events to log or modify responses:
use DS\ReCaptchaBundle\Event\VerifyEvent;
public function onVerify(VerifyEvent $event) {
if (!$event->getResponse()->isSuccess()) {
// Custom logic (e.g., ban IP)
}
}
Register the listener in services.yaml:
services:
App\EventListener\ReCaptchaListener:
tags:
- { name: kernel.event_listener, event: ds_recaptcha.verify, method: onVerify }
How can I help you explore Laravel packages today?