How to Use ReCAPTCHA in Multiple Processes with Laravel
Thank you for your continued support.
This article contains advertisements that help fund our operations.
⇨ Table of Contents for Laravel Articles
This article summarizes how to use ReCAPTCHA with multiple processes in Laravel using Ajax or Axios.
For example, it can be used when you want to handle process 1 asynchronously:
- A process that simply checks whether an email address is unique (i.e., not already registered).
- User registration.
This became necessary to avoid bot verification during the uniqueness check.
How to Use ReCAPTCHA
ReCAPTCHA tokens cannot be reused, so you need to regenerate them after use.
Thus, if you execute the code to "regenerate after use," it will work whether you are using Vue or jQuery.
The method introduced here is implemented using Blade, but it can be adapted easily by managing the site key variable in the View file.
First, Obtain Your Site Key and Secret Key
Register with GCP and obtain your site key and secret key.
This time, we obtained them for V3.
Add to .env and config
.env
RECAPTCHA_SITEKEY=6LdfKoMfAAAAAL*********
RECAPTCHA_SECRET=6LdfKoMfAAAAAPd********
config/services.php
<?php
return [
// ~~omitted
'recaptcha' => [
'sitekey' => env('RECAPTCHA_SITEKEY'),
'secret' => env('RECAPTCHA_SECRET'),
],
];
Create a Rule
Create a custom validation rule.
php artisan make:rule ReCaptcha
app/Rules/ReCaptcha.php
<?php
namespace App\Rules;
use Closure;
use Illuminate\Contracts\Validation\ValidationRule;
use Illuminate\Support\Facades\Http; // Added
class ReCaptcha implements ValidationRule
{
/**
* Run the validation rule.
*
* @param \Closure(string): \Illuminate\Translation\PotentiallyTranslatedString $fail
*/
public function validate(string $attribute, mixed $value, Closure $fail): void
{
$response = Http::get("https://www.google.com/recaptcha/api/siteverify",[
'secret' => config('services.recaptcha.secret'),
'response' => $value
]);
if (!($response->json()["success"] ?? false)) {
$fail('Google Recaptcha is required');
}
}
}
Load on the Page
Load the Script from CDN.
<script src="https://www.google.com/recaptcha/api.js?render={{ config('services.recaptcha.sitekey') }}"></script>
Add an input tag with any id you want inside the form you wish to use.
<form>
<!-- omitted -->
<input id="g-recaptcha-response" type="hidden" name="g-recaptcha-response" />
</form>
Initialization
<script>
// Initialization
grecaptcha.ready(function () {
reloadRecaptchaToken()
})
// Get token and set it to the value of the hidden input tag
function reloadRecaptchaToken() {
grecaptcha.execute({{ config('services.recaptcha.sitekey') }}, { action: "login" }).then(token => {
$("#g-recaptcha-response").val(token)
})
}
</script>
Add Validation
In your FormRequest
or LoginController
, specify validation using the Rule you created earlier.
use App\Rules\ReCaptcha;
//~~omitted
public function rules()
{
return [
'email' => 'required|string|email|max:100',
'g-recaptcha-response' => ['required', new ReCaptcha]
];
}
With this, ReCAPTCHA is set up and ready to use.
How to Use ReCAPTCHA in Multiple Processes
Once you have implemented the above, there's not much left to do.
You just need to regenerate the token.
The token regeneration looks like this:
function reloadRecaptchaToken() {
grecaptcha.execute({{ config('services.recaptcha.sitekey') }}, { action: "login" }).then(token => {
$("#g-recaptcha-response").val(token)
})
}
Since a function is created here, simply running this function again will suffice.
If you’re using Axios, you can regenerate it like this:
axios
.post("/api/check-email", {
email: "sample@example.com",
"g-recaptcha-response": document.getElementById("g-recaptcha-response")
.value,
})
.then()
.catch()
.finally(() => {
reloadRecaptchaToken() // Regenerate
})
For Ajax, it would be:
$.ajax({
url: "/api/check-email",
method: "POST",
data: {
email: 'sample@example.com',
'g-recaptcha-response': document.getElementById('g-recaptcha-response').value
}
success: function (response) {},
error: function (jqXHR, textStatus, errorThrown) {},
complete: function () {
reloadRecaptchaToken() // Regenerate
},
})
Regardless of success or failure, you should regenerate the token.
Conclusion
That’s it.
I hope this helps someone.