[Laravel 8.x] 使用 Google reCAPTCHA

一、申請 Google reCAPTCHA

https://www.google.com/recaptcha/admin/create?hl=zh-tw 註冊新網站。
  • 標籤:填網站名稱或方便以後辨識的內容。
  • reCAPTCHA 類型:以分數為依據 (v3)。
  • 網域:網站的網域,可以新增多筆,所以如果有測試站也可以一並加進來。
提交後會看到網站金鑰和密鑰。

二、設定

1. .env

...
GOOGLE_RECAPTCHA_URL="https://www.google.com/recaptcha/api/siteverify"
GOOGLE_RECAPTCHA_SITE_KEY="你的網站金鑰"
GOOGLE_RECAPTCHA_SECRET="你的密鑰"
...

2. config/services.php

...
'google_recaptcha' => [
    'url' => env('GOOGLE_RECAPTCHA_URL'),
    'site_key' => env('GOOGLE_RECAPTCHA_SITE_KEY'),
    'secret' => env('GOOGLE_RECAPTCHA_SECRET'),
],
...

三、用戶端整合

表單送出時會自動加上 g-recaptcha-response 參數。

1. 載入 JavaScript

<script src="https://www.google.com/recaptcha/api.js"></script>
<script>
    function onSubmit(token) {
        document.getElementById("demo-form").submit();
    }
</script>

2. 調整表單送出按鈕

<button 
    class="g-recaptcha" 
    data-sitekey="{{ config('services.google_recaptcha.site_key') }}"
    data-callback='onSubmit' 
    data-action='submit'
>
    送出
</button>

四、伺服器端整合

1. 自訂驗證規則

<?php

namespace App\Rules;

use Illuminate\Contracts\Validation\Rule;
use Illuminate\Support\Facades\Http;

class GoogleRecaptcha 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)
    {
        $response = Http::asForm()->post(config('services.google_recaptcha.url'), [
            'secret' => config('services.google_recaptcha.secret'),
            'response' => $value,
        ]);
        $result = $response->json();

        return $result['success'];
    }

    /**
     * Get the validation error message.
     *
     * @return string
     */
    public function message()
    {
        return 'Google reCAPTCHA 驗證失敗。';
    }
}

2. 驗證 reCAPTCHA

取表單中 g-recaptcha-response 參數做驗證。
use App\Rules\GoogleRecaptcha;

$request->validate([
    ...
    'g-recaptcha-response' => [new GoogleRecaptcha],
    ...
]);

留言