recurloop / laravel-recaptcha
Laravel Recaptcha V3 扩展包。
dev-main
2023-12-11 13:13 UTC
Requires
- php: >=7.1.0
- guzzlehttp/guzzle: ^6.2|^7.0
- illuminate/container: ~5.7.0|~5.8.0|^6.0|^7.0|^8.0|^9.0|^10.0
- illuminate/http: ~5.7.0|~5.8.0|^6.0|^7.0|^8.0|^9.0|^10.0
- illuminate/support: ~5.7.0|~5.8.0|^6.0|^7.0|^8.0|^9.0|^10.0
This package is auto-updated.
Last update: 2024-09-11 14:53:40 UTC
README
Laravel Recaptcha V3 扩展包
本项目的主要动机是我无法找到一个满足以下两个条件的现有 recaptcha v3 扩展包:
- 请求分数的可读性(如果分数太低则不拒绝)
- recaptcha 令牌应在发送请求之前生成(而不是在生成页面时),这可能导致令牌过期。
安装
要开始使用,请使用 Composer 将扩展包添加到项目的依赖中。
composer require recurloop/laravel-recaptcha:dev-main
将 RECAPTCHA_SITE_KEY
和 RECAPTCHA_SECRET_KEY
添加到您的 .env
文件中。(您可以在以下链接获取它们:这里)
RECAPTCHA_SITE_KEY=sitekey
RECAPTCHA_SECRET_KEY=secret
可选,您可以选择发布配置文件。
php artisan vendor:publish --provider="RecurLoop\Recaptcha\Providers\RecaptchaServiceProvider"
使用方法
初始化 Recaptcha
recaptcha v3 应该加载在每个页面上以跟踪用户活动
<head> ... {!! Recaptcha::initJs() !!} </head>
表单
应将 recaptcha 令牌与执行的操作名称一起发送到每个表单中
<form method="post" action="/contact"> <button onclick="{!! Recaptcha::onClickSubmitJs('contact') !!}">Send message</button> </form>
或
<form method="post" action="/contact" onsubmit="{!! Recaptcha::addTokenJs('contact') !!}"> <button type="submit">Send message</button> </form>
请求验证
在您的 Kernel.php 文件中注册中间件。
protected $routeMiddleware = [ ... 'recaptcha' => \App\Http\Middleware\VerifyRecaptchaScore::class, ... ];
如果请求未达到配置中指定的最小值,您可以拒绝请求。
Route::post('contact', fn() => null)->middleware('recaptcha:contact');
或指定最小值
Route::post('contact', fn() => null)->middleware('recaptcha:contact,0.7');
检查分数
或者,您可以直接在代码中检查分数是否达到
use RecurLoop\Recaptcha\Exceptions\InvalidTokenException; use RecurLoop\Recaptcha\Facades\Recaptcha; try { // Regardless of the action Recaptcha::checkScore(request()); // Including a token (the token will be invalid if the action does not match) Recaptcha::checkScore(request(), 'contact'); // Taking into account the action and the minimum score Recaptcha::checkScore(request(), 'contact', 0.75); } catch (InvalidTokenException $exception) { ... }
检索分数
或者,您可以检索分数
use RecurLoop\Recaptcha\Exceptions\InvalidTokenException; use RecurLoop\Recaptcha\Facades\Recaptcha; try { // Regardless of the action $score = Recaptcha::retrieveScore(request()); // Including a token (the token will be invalid if the action does not match) $score = Recaptcha::retrieveScore(request(), 'contact'); } catch (InvalidTokenException $exception) { ... }
隐藏 ReCAPTCHA 徽章
将其添加到您的 CSS 文件中
.grecaptcha-badge { visibility: hidden !important; }
本地化
默认情况下,该扩展包遵循默认应用程序区域设置,该设置在 config/app.php
中定义。如果您想更改此行为,您可以添加一个新的环境变量来指定要使用的区域设置。
RECAPTCHA_LOCALE=en