reCAPTURE V3 IMPLEMENTATION IN LARAVEL PROJECT
Add in config/services.php
'recaptcha' => [
'site_key' => env('RECAPTCHA_SITE_KEY'),
'secret_key' => env('RECAPTCHA_SECRET_KEY'),
],
Add in .env file
# local developer credential
RECAPTCHA_SITE_KEY=value
RECAPTCHA_SECRET_KEY=value
Add validation in controller function
$validator = $request->validate(
[
"name"=>"required",
"contact_no"=>"required|numeric",
"email_id"=>"required",
"message"=>"required",
// "g_recaptcha_response"=> "required",
"g_recaptcha_response"=> ["required", function ($attribute, $value, $fail) {
$url = 'https://www.google.com/recaptcha/api/siteverify?secret='
. config('services.recaptcha.secret_key') . '&response=' . $value;
$response = file_get_contents($url);
$response = json_decode($response);
// $g_response = Http::asForm()->post("https://www.google.com/recaptcha/api/siteverify", [
// 'secret' => config('services.recaptcha.secret_key'),
// 'response' => $value,
// 'remoteip' => \request()->ip()
// ]);
if (! $response->success ) {
$fail("The reCaptcha is invalid.");
}
},
],
]);
In form blade page
<script src="https://www.google.com/recaptcha/api.js?render={{config('services.recaptcha.site_key')}}"></script>
<form method="post" action="{{ url('contact-us') }}" id="registerForm">
..
..
..
<button type="submit" class="btn btn-submit" onclick="onClick(event)" >Submit</button>
</form>
<script>
function onClick(e) {
e.preventDefault();
grecaptcha.ready(function() {
grecaptcha.execute("{{config('services.recaptcha.site_key')}}", {action: 'submit'}).then(function(token) {
// Add your logic to submit to your backend server here. ACTION REGISTER
document.getElementById('g-recaptcha-response').value = token;
document.getElementById("registerForm").submit();
});
});
}
</script>
Comments
Post a Comment