Google reCAPTCHA with Laravel Simplified

Tuan Burah
8 min readMar 26, 2024

How to integrate Google reCAPTCHA into a Laravel 10 Project easily

Google reCAPTCHA Official Website as of March 2024

About Google reCAPTCHA ©

Google reCAPTCHA is a free service provided by Google that helps website owners protect their sites from spam and abuse. It uses advanced risk analysis techniques to distinguish humans from bots with high accuracy. reCAPTCHA offers different types of challenges, ranging from image recognition to checkbox validation, each designed to verify user authenticity effectively.

Register a reCAPTCHA Site

First and foremost, you will need to register a site in the google reCAPTCHA website here: www.google.com/recaptcha/about/ by heading over to “v3 Admin Console” on the top navigation bar. Once you have opened a new site, fill in the configurations as per your requirements and click save (for now I have selected “invisible” reCAPTCHA badge”).

Google reCAPTCHA Registration

Types of Google reCAPTCHA

You might have noticed the reCAPTCHA types shown in the registration form and be confused on what to be selected — worry no more for I have taken the time to elaborate each reCAPTCHA type as below.

Google reCAPTCHA Types

1. Score-based reCAPTCHA (reCAPTCHA v3)

Description: Score-based reCAPTCHA, also known as reCAPTCHA v3, operates behind the scenes, assessing the risk of each user interaction based on their behavior. Instead of presenting challenges to users, it assigns a risk score to each action, allowing website owners to make informed decisions about how to handle suspicious activity.

Features:

  • Invisibility: Users are not presented with any challenges, ensuring a seamless browsing experience.
  • Granular Control: Provides a risk score for each interaction, allowing website owners to customize security measures accordingly.
  • Seamless Integration: Easily integrates into existing web forms and applications with minimal user intervention.

Applications:

  • Form submissions.
  • User authentication.
  • Content moderation.
  • API requests.

2. Checkbox Challenge reCAPTCHA (reCAPTCHA v2)

Description: Checkbox Challenge reCAPTCHA, or reCAPTCHA v2, presents users with a checkbox accompanied by the prompt “I’m not a robot.” Upon clicking the checkbox, users may be asked to solve additional challenges, such as selecting specific objects from a set of images, to verify their humanity.

Features:

  • User Interaction: Requires users to actively engage with the reCAPTCHA widget by clicking the checkbox.
  • Enhanced Security: Offers additional challenges for suspicious interactions, improving security effectiveness.
  • Fallback Mechanism: Provides a fallback mechanism for users with JavaScript disabled, ensuring accessibility.

Applications:

  • Login pages.
  • Registration forms.
  • Contact forms.
  • Comment sections.

3. Invisible Challenge reCAPTCHA (Invisible reCAPTCHA)

Description: Invisible Challenge reCAPTCHA, an evolution of reCAPTCHA v2, operates similarly to Checkbox Challenge reCAPTCHA but works behind the scenes without requiring any user interaction. It analyzes user behavior and automatically verifies users without presenting visible challenges.

Features:

  • Seamless Verification: Works invisibly in the background, minimizing interruption to the user experience.
  • Automated Detection: Analyzes user behavior to determine authenticity and mitigate automated threats.
  • Easy Integration: Integrates seamlessly into web forms and applications without modifying the user interface.

Applications:

  • High-traffic websites.
  • E-commerce platforms.
  • Login pages where a friction-less experience is essential.

Choosing the Right reCAPTCHA Type

Selecting the appropriate reCAPTCHA type depends on factors such as the level of security required, user experience considerations, and the specific use case of your website or application. While Score-based reCAPTCHA prioritizes invisibility and granular control, Checkbox Challenge and Invisible Challenge reCAPTCHA offer a balance between user interaction and security effectiveness.

Understanding Google reCAPTCHA Keys

After the registration phase, you will be redirected to a new page displaying two configuration keys as the image displayed below.

Now, understanding the Google reCAPTCHA keys can make your programming much more easier — whilst you encompass the bigger picture of reCAPTCHA validation and its data flow, so pay attention clearly.

Google reCAPTCHA Keys

Google reCAPTCHA keys are unique identifiers that enable websites to integrate reCAPTCHA functionality seamlessly. There are two primary types of reCAPTCHA keys:

  1. Site Key: The site key is a public key that is embedded into the HTML of a website’s pages. It is used to invoke reCAPTCHA services on the client-side (front-end), allowing the reCAPTCHA widget to be displayed and interacted with by users or the reCAPTCHA service to run in the background — as per the configuration selected on registering the reCAPTCHA.
  2. Secret Key (or Secret): The secret key is a private key that is kept confidential and used for server-side communication with Google’s reCAPTCHA service. It verifies the authenticity of requests sent from the website’s server to Google’s servers, helping to prevent abuse and ensure the integrity of reCAPTCHA responses.

Now, you must have understood the two purposes of the two keys. If you haven’t still got it, then hope the following helps you more.

A Simplified Explanation

The Site Key and Secret Key are configuration keys assigned to a particular website domain that will uniquely identify each other.

Client side (front-end)

The Site Key will be used in the form button to render a token from the Google reCAPTCHA servers that will also validate the state of the users behavior in the background or via a challenge — based on the reCAPTCHA type selected. This token will be automatically saved in the form.

Once the form is submitted, the form request will also carry another request name called the “g-recaptcha-response” which will be declared by reCAPTCHA.

Server side (Back-end)

From the server side the Secret Key must be stored as a variable and be used to verify the “g-recaptcha-response” status from the Google reCAPTCHA servers. Based on the response received from the Google reCAPTCHA servers, we can determine the form submission is a bot or an authentic human.

Activity Diagram of Google reCAPTCHA

Integrating Google reCAPTCHA Into Laravel 10

Integrating Google reCAPTCHA into a website is a straightforward process, thanks to comprehensive documentation and easy-to-use APIs provided by Google. Website owners can choose the reCAPTCHA version that best suits their needs and implement it with minimal effort.

Furthermore, Google is committed to ensuring that reCAPTCHA remains accessible to all users, including those with disabilities. Alternative options, such as audio challenges for visually impaired users, ensure that everyone can participate in online activities securely.

Prerequisites

Here, I will be showing on how to integrate the Google reCAPTCHA into a Laravel project specifically with Laravel version 10. Additional languages that will be used are jQuery and AJAX script to manage the form submission.

Client Side — HTML Code

<form id="myForm" >
<div class="grid xl:grid-cols-3 grid-cols-2 gap-2 xl:gap-4 text-dark ">

<input type="hidden" name="ip_address" value="{{$ip_address}}">

<div class="border-b border-gray-500">
<input class="appearance-none bg-transparent border-none w-full mr-3 py-1 px-2 leading-tight focus:outline-none focus:border-white focus:ring-white" type="text" placeholder="{{__('frontend.formFullName')}}" name="name" aria-label="Full name" autocomplete="off" required>
</div>

<div class="border-b border-gray-500">
<input class="appearance-none bg-transparent border-none w-full mr-3 py-1 px-2 leading-tight focus:outline-none focus:border-white focus:ring-white" type="email" placeholder="{{__('frontend.formEmail')}}" name="email" aria-label="Email" required>
</div>

<div id="submitComplete">
<button id="submitButton" data-sitekey="xxxxxxx_xxxxxxxxx_xxxxxxxxxxx" data-callback='onSubmit' class="g-recaptcha w-full text-sm text-white px-2 py-2 border border-white rounded-0">
Subscribe
</button>

<button id="submitButtonDone" class="w-full text-sm text-white px-2 py-2 border border-white rounded-0" disabled hidden>
Submitted
</button>

<button id="submitVerifying" class="w-full text-sm text-white px-2 py-2 border border-white rounded-0" disabled hidden>
Verifying
</button>
</div>
</div>
</form>

Client Side — Java Script / jQuery / AJAX Code

You will additional pieces of java-script function codes as “setCookie” and “getCookie”. These are created to restrict the server load from the client-side by creating a time-delay after a submission.

<script defer>
// Function to create a cookie
function setCookie(name, value, daysToExpire) {
var expires = "";
if (daysToExpire) {
var date = new Date();
date.setTime(date.getTime() + (daysToExpire * 5 * 60 * 1000));
expires = "; expires=" + date.toUTCString();
}
document.cookie = name + "=" + value + expires + "; path=/";
};

// Function to get a specific cookie by name
function getCookie(cookieName) {
var name = cookieName + "=";
var decodedCookie = decodeURIComponent(document.cookie);
var cookieArray = decodedCookie.split(';');
for (var i = 0; i < cookieArray.length; i++) {
var cookie = cookieArray[i].trim();
if (cookie.indexOf(name) === 0) {
return cookie.substring(name.length, cookie.length);
}
}
return null; // Return null if the cookie is not found
};

$(document).ready(function () {
if (getCookie('_ivqLdoulWNJqMw')) {
$('#submitButtonDone').show();
$('#submitButton').hide();
$('#subscriptionForm').hide();
} else {
$('#submitButtonDone').hide();
$('#submitButton').show();
$('#subscriptionForm').show();
};
});

function onSubmit(token) {
setCookie("_ivqLdoulWNJqMw", true, 1); //--Set a new cookie---
var formData = new FormData(document.getElementById("myForm"));
document.getElementById("submitButton").disabled = true;
document.getElementById('submitButton').style.display = 'none';
document.getElementById('submitVerifying').style.display = 'inline-block';
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content'),
'authkey': 'YOUR_SECRET_KEY',
}
});
$.ajax({
type:'POST',
headers: //---set the headers for cross-origin policies between domains
{
'X-CSRF-TOKEN': $('meta[name="XSRF-TOKEN"]').attr('content'),
'Access-Control-Allow-Origin': 'en/subscription-form'
},
url: "{{ URL('en/subscription-form') }}",
data: formData,
processData: false,
contentType: false,
success:function(response)
{
if (response.success) {
$('#submitComplete').show();
$('#submitIncomplete').hide();
$('#submitButtonDone').show();
$('#submitButton').hide();
$('#subscriptionForm').hide();
document.location.href = '/en/subscription/thanks';
} else {
document.location.href = '/en/subscription/thanks';
}
}
});
}
</script>

Server Side — PHP Code

 public function subscription_form($lang='', Request $request) {
$RECAPTCHA_SECRET_KEY = "xxxxxxxxxx_xxxxxxxxxx_xxxxxxxxxxxx";
$json_response = function($data = []) {
header('Content-Type: application/json; charset=utf-8');
exit(json_encode($data));
};


//--------verify-recaptcha-response--------
$response = file_get_contents(
'https://www.google.com/recaptcha/api/siteverify?'.http_build_query([
'secret' => $RECAPTCHA_SECRET_KEY,
'response' => $request['g-recaptcha-response'],
'remoteip' => $_SERVER['REMOTE_ADDR'],
])
);
$response = json_decode($response, true);


//-------------handle-status-and-respond-with-json-------------
if (intval($response["success"]) !== 1) {
$json_response(['errors' => ['recaptcha' => 'Captcha failed.']]);
} else {
try{
$data = [
'name' => $request->name,
'email' => $request->email,
'ip' => $request->ip_address
];
$data2 = ['message' => "
Thanks for subscribing to our news letter! We're excited to welcome you to our community and share valuable content, updates, and special offers with you."
];
Mail::mailer('noreply')->to('sendemail@testmail.com')->send(new SubscriptionInquiry($data));
} catch (\Exception $e) {
dd($e->getMessage());
}
$json_response(['success' => true]);
}
}

The Future of reCAPTCHA

As technology continues to evolve, so too will Google reCAPTCHA. With advancements in machine learning and artificial intelligence, reCAPTCHA will become even more adept at identifying and thwarting malicious activity while maintaining a seamless user experience.

Conclusion

In a digital landscape fraught with security threats, Google reCAPTCHA stands as a beacon of innovation, offering robust protection against bots while enhancing the user experience. Through its evolution from text-based challenges to seamless background analysis, reCAPTCHA exemplifies the power of technology to adapt and combat emerging threats.

Additionally, Google is likely to explore new ways to leverage reCAPTCHA technology beyond website security. Whether it’s improving data quality through crowdsourcing or enhancing user verification processes, the potential applications of reCAPTCHA are vast and continually expanding.

If you have any questions regarding the process, comment below. Note that this method is functional on Laravel v10, v9 and v8 where the PHP language is stable as PHP v8. There may be small changes needed to be made for other versions due to the complexity or deprecated libraries of Laravel helpers and PHP versions.

References

--

--

Tuan Burah

M.Sc. in IT (reading) | Pg.D. in IT | Student Member of British Computer Society — Royal Charter | Member of LivePhysics Science Community