En este tutorial detallado, aprenderás a integrar Google reCAPTCHA v2 en tu aplicación Laravel 12 utilizando Livewire 3. Esta implementación ayudará a proteger tus formularios contra bots y spam, mejorando la seguridad de tu aplicación.
Configuración Inicial
1. Configura las credenciales de reCAPTCHA
Primero, necesitas registrar tu sitio en Google reCAPTCHA para obtener tus credenciales. Luego, agrégalas a tu archivo .env
:
GOOGLE_RECAPTCHA2_KEY=TU_CLAVE_DE_SITIO
GOOGLE_RECAPTCHA2_SECRET=TU_CLAVE_SECRETA
2. Editar archivo config/services.php
'recaptcha' => [
'public_key' => env('GOOGLE_RECAPTCHA2_KEY'),
'secret_key' => env('GOOGLE_RECAPTCHA2_SECRET'),
],
Implementación en Livewire
3. Edita el componente de validación
En tu componente Livewire (app/Livewire/Auth/Login.php
):
use Illuminate\Support\Facades\Http;
#[Validate('required')]
public $captcha = null;
public function updatedCaptcha($token)
{
$response = Http::post(
'https://www.google.com/recaptcha/api/siteverify?secret=' .
config('services.recaptcha.secret_key') .
'&response=' . $token
);
$success = $response->json()['success'];
if (! $success) {
throw ValidationException::withMessages([
'captcha' => __('Google thinks, you are a bot, please refresh and try again!'),
]);
} else {
$this->captcha = true;
}
}
Vista Blade con reCAPTCHA
4. Implementa la vista con el widget
En tu archivo de vista (resources/views/livewire/auth/login.blade.php
):
<div id="captcha" class="mt-4" wire:ignore></div>
@error('captcha')
<p class="mt-3 text-sm text-red-600 text-left">
{{ $message }}
</p>
@enderror
</form>
<script src="https://www.google.com/recaptcha/api.js?onload=handle&render=explicit" async defer>
</script>
<script>
var handle = function(e) {
widget = grecaptcha.render('captcha', {
'sitekey': '{{ config('services.recaptcha.public_key') }}',
'theme': 'light', // you could switch between dark and light mode.
'callback': verify
});
}
var verify = function (response) {
@this.set('captcha', response)
}
</script>