Tích hợp Google reCAPTCHA Enterprise trong Laravel 9 mới nhất

I Captcha là gì ? Tại sao chọn Google reCaptcha

Captcha (Completely Automated Public Turing test to tell Computers and Humans Apart) tạm dịch là Phép thử Turing công cộng hoàn toàn tự động để phân biệt máy tính với người được Đại học Carnegie Mellon công bố. Captcha là một quá trình máy tính yêu cầu người dùng hoàn thành một kiểm tra đơn giản để đánh giá, bất kỳ người nào nhập vào lời giải đúng được xem là con người.

Có rất nhiều bên tích hợp captcha nhưng mà tại sao mình lại chọn Google reCaptcha

Google reCaptcha là 1 hệ thống mà giúp người dùng sử dụng không thấy khó chịu khi phải nhập các kí tự loằng ngoằng mà vẫn giúp chúng ta phân biệt được robot hay người dùng chính xác đến 99%

II Tích hợp Google reCAPTCHA vào Laravel 9

1: Đăng kí tài khoản google : 

Bạn truy cập vào https://www.google.com/recaptcha/admin/ để tạo 1 tài khoản theo các bước sau :

2 : Tạo project demo cho google reCAPTCHA

Khởi tạo project tên recaptcha với command sau :

composer create-project laravel/laravel  recaptcha

Tiếp theo chúng ta tạo 1 Controller tên là ContactController với command sau :

php artisan make:model Contact -all

File ContactController.php chúng ta chỉnh sửa như sau :

namespace App\Http\Controllers;
use App\Models\Contact;
use App\Http\Requests\StoreContactRequest;
use App\Http\Requests\UpdateContactRequest;

class ContactController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        return view('contact.index');
    }
     /**
     * Store a newly created resource in storage.
     *
     * @param  \App\Http\Requests\StoreContactRequest  $request
     * @return \Illuminate\Http\Response
     */
    public function store(StoreContactRequest $request)
    {
        //dd($request);
        return view('contact.store');
    }
}

 File StoreContactRequest như sau :

namespace App\Http\Requests;
use App\Rules\Captcha;
use Illuminate\Foundation\Http\FormRequest;
class StoreContactRequest extends FormRequest
{
    /**
     * Determine if the user is authorized to make this request.
     *
     * @return bool
     */
    public function authorize()
    {
        return true;
    }

    /**
     * Get the validation rules that apply to the request.
     *
     * @return array
     */
    public function rules()
    {
        return [
            'email'=>['required','email'],
            'g-recaptcha-response'=>[new Captcha()],
        ];
    }
}

Tạo Rule để xử lý Recaptcha kết nối server với lệnh sau :

php artisan make:rule Captcha

File Captcha ta code như sau :

namespace App\Rules;

use GuzzleHttp\Client;
use Illuminate\Contracts\Validation\Rule;

class Captcha implements Rule
{
    /**
     * Create a new rule instance.
     *
     * @return void
     */
    public function __construct()
    {
        //
    }

    /**
     * Determine if the validation rule passes.
     *
     * @param  string  $attribute
     * @param  mixed  $value
     * @return bool
     */
    public function passes($attribute, $value)
    {
        $client = new Client();
        $response = $client->post(
            'https://www.google.com/recaptcha/api/siteverify',
            ['form_params'=>
                [
                    'secret'=>env('SITE_KEY_SECRET'),
                    'response'=>$value
                ]
            ]
        );
        $body = json_decode((string)$response->getBody());
        return $body->success;
    }

    /**
     * Get the validation error message.
     *
     * @return string
     */
    public function message()
    {
        return 'Captcha không đúng';
    }
}

Xử lý vấn đề giao diện khi nhập vào ta code 2 file blade như sau :

resources/views/contact/index.blade.php

<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.min.js" integrity="sha384-JjSmVgyd0p3pXB1rRibZUAYoIIy6OrQ6VrjIEaFf/nJGzIxFDsf4x0xIM+B07jRM" crossorigin="anonymous"></script>
<script src="https://www.google.com/recaptcha/api.js" async defer></script>
<script>
    function onSubmit(token) {
        document.getElementById("form").submit();
    }
</script>
<h3 style="text-align: center;text-transform: uppercase;">Demo Google reCaptcha của <a target="_blank" href="https://lashare.info"> LASHARE.info</a></h3>
@if ($errors->any())
    @foreach ($errors->all() as $error)
        <div class="alert alert-primary" role="alert" style="text-align: center;">
            {{$error}}
        </div>
    @endforeach
@endif
<div class="main">
    <div class="container">
        <form action="{{route('contact_post')}}" method="post" id="form">
            @csrf
            <!-- Email input -->
            <div class="form-outline mb-4">
                <label class="form-label" for="form1Example1">Email</label>
                <input name="email" type="email" id="form1Example1" class="form-control" />

            </div>

            <!-- Password input -->
            <div class="form-outline mb-4">
                <label class="form-label" for="form1Example2">Nội dung</label>
                <input name="content" type="text" id="form1Example2" class="form-control" />

            </div>

            <!-- Submit button -->
            <button class="btn btn-primary btn-block g-recaptcha" data-sitekey="{{env('site_key')}}" data-callback="onSubmit" type="submit">Submit</button>
        </form>
    </div>
</div>

Tiếp theo chúng ta config file .env

SITE_KEY=6Lf2AYchAAAAAP0WqVchb-95yPnb-wNNAyxP7Ipv
SITE_KEY_SECRET=6Lf2AYchAAAAANSXaC6WTxv-Zi2Zqc84ueLwmAxI

Vậy là xong ,Bạn có thể download source code để xem