hedii/laravel-recaptcha

Google reCAPTCHA v3 for Laravel

3.0.1 2022-03-05 19:37 UTC

This package is auto-updated.

Last update: 2024-09-06 01:14:18 UTC


README

Build Status Total Downloads License Latest Stable Version

Laravel Recaptcha

Google reCAPTCHA v3 for Laravel 7.0+

目录

安装

通过 composer 安装

composer require hedii/laravel-recaptcha

发布配置

php artisan vendor:publish --provider="Hedii\LaravelRecaptcha\RecaptchaServiceProvider"

位于 config/recaptcha.php 的配置文件如下所示

return [
    /**
     * The recaptcha site key.
     */
    'site_key' => env('RECAPTCHA_SITE_KEY', ''),

    /**
     * The recaptcha site secret.
     */
    'secret_key' => env('RECAPTCHA_SECRET_KEY', ''),

    /**
     * The minimum score (from 0.0 to 1.0) a recaptcha response must have to be
     * valid. 1.0 is very likely a good interaction, 0.0 is very likely a bot.
     */
    'minimum_score' => env('RECAPTCHA_MINIMUM_SCORE', 0.7),
];

Google Recaptcha 管理员 上注册一个新的网站,并选择 reCAPTCHA v3

编辑 .env 文件以添加所需的环境变量

RECAPTCHA_SITE_KEY=xxxxxxxxxxxxxxxxxxx
RECAPTCHA_SECRET_KEY=xxxxxxxxxxxxxxxxxxx
RECAPTCHA_MINIMUM_SCORE=0.7

用法

使用以下方法在 HTML 表单中插入所需的 JavaScript。您可以设置一个操作名称作为第一个参数,并将 reCAPTCHA 隐藏 HTML 字段的 ID 作为第二个参数。

<form method="post">
    <!-- ...the rest of the form... -->

    {!! Recaptcha::script('contact_form', 'recaptchaResponse') !!}

    <!-- make sure you place a hidden input nammed recaptcha_response  -->
    <input type="hidden" name="recaptcha_response" id="recaptchaResponse">

    <input type="submit">
</form>

在您的控制器中,您可以像这样验证 recaptcha 分数

public function store(\Hedii\LaravelRecaptcha\Recaptcha $recaptcha)
{
    if (! $recaptcha->isValid()) {
        // the recaptcha score is lower than the configured minimal score, you
        // can throw a validation exception or do anything else 
        throw ValidationException::withMessages([
            'recaptcha' => 'Recaptcha validation failed...'
        ]);
    }

    // here the score is valid
}

如果您更喜欢使用 Facade

public function store()
{
    if (! Recaptcha::isValid()) {
        // the recaptcha score is lower than the configured minimal score, you
        // can throw a validation exception or do anything else 
        throw ValidationException::withMessages([
            'recaptcha' => 'Recaptcha validation failed...'
        ]);
    }

    // here the score is valid
}

许可证

laravel-recaptcha 在 MIT 许可证下发布。有关详细信息,请参阅捆绑的 LICENSE 文件。