Google reCaptcha with Laravel

Laravel 8 Google Captcha without any third party package.

First add below keys in .env file

GOOGLE_CAPTCHA_SITE_KEY=6LeIxAcTAAAAAJcZVRqyHh71UMIEGNQ_MXjiZKhI
GOOGLE_CAPTCHA_SECRET_KEY=6LeIxAcTAAAAAGG-vFI1TnRWxMZNFuojJ4WifJWe
GOOGLE_CAPTCHA_VERIFICATION_URL=https://www.google.com/recaptcha/api/siteverify

Note:these are test keys from google document.

then in config folder create a file called google_captcha.php

<?php

return [
    'site_key' => env('GOOGLE_CAPTCHA_SITE_KEY'),
    'secret_key' => env('GOOGLE_CAPTCHA_SECRET_KEY'),
    'gc_verification_url' => env('GOOGLE_CAPTCHA_VERIFICATION_URL'),
    'error_codes' => [
        "missing-input-secret" => "The secret parameter is missing.",
        "invalid-input-secret" => "The secret parameter is invalid or malformed.",
        "missing-input-response" => "The response parameter is missing.",
        "invalid-input-response" => "The response parameter is invalid or malformed.",
        "bad-request" => "The request is invalid or malformed.",
        "timeout-or-duplicate" => "The response is no longer valid: either is too old or has been used previously.",
    ],

];

and for the purpose of validation of google captcha in server side first we create validation rule.We can do multiple ways but i choose two ways

1.creating custom rule in AppServiceProvider like below

<?php

namespace App\Providers;

use Illuminate\Support\Facades\Http;
use Illuminate\Support\Facades\Validator;
use Illuminate\Support\ServiceProvider;

class AppServiceProvider extends ServiceProvider
{
    /**
     * Register any application services.
     *
     * @return void
     */
    public function register()
    {
        //
    }

    /**
     * Bootstrap any application services.
     *
     * @return void
     */
    public function boot()
    {
        
        Validator::extend('google_captcha', function ($attribute, $value, $parameters, $validator){

            $http=Http::asForm()->post(config('google_captcha.gc_verification_url'),[
                'secret' => config('google_captcha.secret_key'),
                'response' =>$value,
            ]);

            if(!$http->object()->success){

                $errorMessage=null;
                collect($http->object()->{"error-codes"})->each(function ($item)use(&$errorMessage){
                    $errorMessage.=config('google_captcha.error_codes')[$item];

                });

                $validator->addReplacer('google_captcha',
                    function($message, $attribute, $rule, $parameters) use ($errorMessage) {
                        return \str_replace(':message', $errorMessage, $message);
                    }
                );
            }

            return $http->object()->success;
        },":message");
    }
}

validation rule look like below

  $validator=Validator::make($request->all(),[
            'g-recaptcha-response'=>'required|google_captcha'
        ]);

html form will be

<!DOCTYPE html>
<html >
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">

    <title>Laravel</title>

    <!-- Fonts -->
    <link href="https://fonts.googleapis.com/css?family=Nunito:200,600" rel="stylesheet">

    <!-- Styles -->

    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css">
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.16.0/umd/popper.min.js"></script>
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js"></script>

</head>
<body>



<form method="POST" action="{{ route('test') }}">
    @csrf

    <div class="g-recaptcha"  data-sitekey="{{config('google_captcha.site_key')}}"></div>

    <button type="submit" class="btn btn-primary pull-right"
            style="margin-right: 15px;">Submit</button>
</form>

<script src="https://www.google.com/recaptcha/api.js"></script>

</body>
</html>

Suppose if you don’t want to write custom validation rule in app service provider then you can use inline validation like below

$validator=Validator::make($request->all(),[
            'g-recaptcha-response'=>['required', function ($attribute, $value, $fail) {
                $http=Http::asForm()->post(config('google_captcha.gc_verification_url'),[
                    'secret' => config('google_captcha.secret_key'),
                    'response' =>$value,
                ]);

                if(!$http->object()->success){
                    $errorMessage=null;
                    collect($http->object()->{"error-codes"})->each(function ($item)use(&$errorMessage){
                        $errorMessage.=config('google_captcha.error_codes')[$item];

                    });
                    $fail($errorMessage);
                }
            }]
        ]);

Documentation Reference Link

1.Captcha Verification :
https://developers.google.com/recaptcha/docs/verify

2.Test Keys : https://developers.google.com/recaptcha/docs/faq

3.Custom Validation Rule : https://laravel.com/docs/8.x/validation#custom-validation-rules

4.Laravel Http Client : https://laravel.com/docs/8.x/http-client#introduction

5.Google Captcha Admin Link : https://www.google.com/recaptcha/about/

Leave a Comment