Google reCaptcha V3 Laravel Using Invisible reCaptcha For A Better User Experience


Google ReCaptcha in Laravel PHP
larrydev
Author: The don
ยท2 min read

In the world of web development, security is paramount. One of the most common security measures is Google's reCAPTCHA, a tool designed to prevent bots and spam from infiltrating your website. In this article, we will dive into a PHP class that integrates Google reCAPTCHA into a Laravel application. This code snippet provides an essential layer of protection by verifying whether a user is human or a bot.

ReCaptcha.php
<?php
namespace App\Services\Google;

use Illuminate\Support\Facades\Http;

class ReCaptcha
{
    public function __construct(private string $gRecaptchaResponseToken)
    {
        $this->gRecaptchaResponseToken = $gRecaptchaResponseToken;
    }

    public function response(): bool
    {
        $response = Http::asForm()->post(config('app.google_captcha_url'), [
            'secret' => config('app.google_captcha_secret'),
            'response' => $this->gRecaptchaResponseToken,
            'remoteid' => request()->getClientIp(),
        ])->json();

        return !empty($response['score']) && $response['score'] > 0.5 && $response['success'] === true;
    }
}
SomeOtherClass.php
// Use it!
(new GoogleReCaptcha($gRecaptchaResponseToken))->response()

The PHP Class:

Understanding the Code: Let's dissect the PHP code that incorporates Google reCAPTCHA step by step: The code is placed within the App\Services\Google namespace. It uses Laravel's Http facade to make HTTP requests.

Constructor:

Constructor: The code checks the reCAPTCHA response: It verifies that the score in the response is greater than 0.5, indicating a likely human interaction. It ensures that success is true, indicating a successful verification.

The response Method:

The response Method: This method is responsible for verifying the reCAPTCHA response token. It sends a POST request to Google's reCAPTCHA verification endpoint. The POST data includes: secret: Your website's reCAPTCHA secret key (configured in Laravel's environment). response: The user's response token. remoteid: The users's IP address. The response from Google is JSON, so it's decoded into an associative array.

Verification Logic:

Verification Logic: The code checks the reCAPTCHA response: It verifies that the score in the response is greater than 0.5, indicating a likely human interaction. It ensures that success is true, indicating a successful verification.

Conclusion

By integrating Google reCAPTCHA using this PHP class in your Laravel application, you add a robust layer of security to your forms. It helps protect your website from automated bots and ensures a safer user experience. This code snippet exemplifies how to implement reCAPTCHA verification efficiently, contributing to a more secure and reliable web application.

Back to Posts...