Integrating Google reCAPTCHA into Laravel Livewire
Step 1: Obtain Your Google reCAPTCHA Keys
Visit https://www.google.com/recaptcha/admin/create to generate your site key and secret key for Google reCAPTCHA. Make sure to select version 3 (v3).
Step 2: Add the keys to Your .env file
Access your .env file and add the following lines to store your Google reCAPTCHA keys:
1GOOGLE_CAPTCHA_SITE_KEY=2GOOGLE_CAPTCHA_SECRET_KEY=
Step 3: Configure your config in the config\services.php file
In the config\services.php
file, add the following configuration for Google reCAPTCHA:
1'google_captcha' => [2 'site_key' => env('GOOGLE_CAPTCHA_SITE_KEY'),3 'secret_key' => env('GOOGLE_CAPTCHA_SECRET_KEY'),4],
Step 4: Add the necessary property to your Livewire component
Within your Livewire component, add the following property to store the token received from Google:
1public ?string $captchaToken = null;
Step 5: Implement the form submission
1public function submit(): void 2{ 3 //Other field validations 4 5 $query = http_build_query([ 6 'secret' => config('services.google_captcha.secret_key'), 7 'response' => $this->captchaToken, 8 ]); 9 10 $response = Http::post('https://www.google.com/recaptcha/api/siteverify?' . $query);11 $captchaLevel = $response->json('score');12 13 throw_if($captchaLevel <= 0.5, ValidationException::withMessages([14 'captchaToken' => __('Error on captcha verification. Please, refresh the page and try again.')15 ]));16 17 //You logic if captcha passes18}
Step 6: Update Your Blade File
In your Blade file, ensure the following elements are present:
- Your form inputs
- Error capture if the captcha is invalid
- The submit button with necessary classes and data attributes
1<div> 2 <form wire:submit.prevent="submit"> 3 4 {{-- Your inputs here --}} 5 6 @error('captchaToken') 7 {{-- Error capture if captcha is invalid --}} 8 {{ $message }} 9 @enderror10 11 <button type="submit"12 class="g-recaptcha your-other-classes-here"13 data-sitekey="{{ config('services.google_captcha.site_key') }}"14 data-callback='handle'15 data-action='submit'16 >17 Send18 </button>19 </form>20 21 <script src="https://www.google.com/recaptcha/api.js?render={{ config('services.google_captcha.site_key') }}"></script>22 <script>23 function handle(e) {24 grecaptcha.ready(function () {25 grecaptcha.execute('{{ config('services.google_captcha.site_key') }}', { action: 'submit' })26 .then(function (token) {27 @this.set('captchaToken', token);28 @this.submit()29 });30 })31 }32 </script>33</div>
To simplify the explanation, all the required logic and code examples in this guide are provided in a single file.
And that is it!