由於之前使用的套件尚未支援 Laravel 10.x 版,這次換個方式做。 (參考這篇)

至 Google reCaptcha 取得 site key 及 secret key,然後將 site key 及 secret key 寫入 .env 檔案中:

NOCAPTCHA_HIDE = false
NOCAPTCHA_SITEKEY = your site key
NOCAPTCHA_SECRET = your secret key
RECAPTCHA_URL=https://www.google.com/recaptcha/api/siteverify

建立一個 Google reCaptcha Rule,建立好後會在 app/Rules 產生 GoogleRecaptcha.php 檔案:

php artisan make:rule GoogleReCaptcha

編輯 app/Rules/GoogleRecaptcha.php

<?php

namespace App\Rules;

use Closure;
use Illuminate\Contracts\Validation\ValidationRule;
use Illuminate\Support\Facades\Http;

class GoogleRecaptcha 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(env('RECAPTCHA_URL'),[
            'secret' => env('NOCAPTCHA_SECRET'),
            'response' => $value
        ]);

        if (!($response->json()["success"] ?? false)) {
              $fail('The google recaptcha is required.');
        }
    }
}

在需要使用檢查的前端頁面 (login.blade.php) 加入相關的 script

    {{-- Google reCAPTCHA v3 --}}
    <script src="https://www.google.com/recaptcha/api.js?render={{ env('NOCAPTCHA_SITEKEY') }}"></script>
    <script>
        $('#loginForm').submit(function(event) {
            event.preventDefault();
            grecaptcha.ready(function() {
                grecaptcha.execute("{{ env('NOCAPTCHA_SITEKEY') }}", {action: 'submit'}).then(function(token) {
                    $('#loginForm').prepend('<input type="hidden" name="g-recaptcha-response" value="' + token + '">');
                    $('#loginForm').unbind('submit').submit();
                });;
            });
        });
    </script>

在檢查的控制器中加入驗證

use App\Rules\GoogleRecaptcha;

// 驗證表單資料
$this->validate($request, [
    'account'   => 'required',
    'password' => 'required|min:6',
    'g-recaptcha-response' => ['required', new GoogleRecaptcha],
]);

若需要隱藏圖案則在前端頁面或者共用的css中加入,這時候只需要在 .env 中控制隱藏或顯示:

@if(env('NOCAPTCHA_HIDE'))
<style>
    .grecaptcha-badge {
        visibility: hidden;
    }
</style>
@endif
最後修改日期: 2023 年 7 月 13 日