dutchcodingcompany / livewire-recaptcha
为您的Laravel Livewire组件添加Google Recaptcha V3支持
Requires
- php: ^8.2
- livewire/livewire: ^3.0
Requires (Dev)
- friendsofphp/php-cs-fixer: ^3.8
- larastan/larastan: ^2.9
- orchestra/testbench: ^9.0
- phpunit/phpunit: ^11.1
This package is auto-updated.
Last update: 2024-09-08 03:46:25 UTC
README
本软件包提供了一种自定义Livewire指令,以使用Google reCAPTCHA (v2 + v2 invisible + v3)检查来保护您的Livewire函数。
安装
composer require dutchcodingcompany/livewire-recaptcha
配置
有关如何创建您自己的密钥对以实现即将实施的特定ReCaptcha版本的信息,请参阅https://developers.google.com/recaptcha/intro。
本软件包支持以下版本。请注意,每个版本都需要不同的sitekey/secretkey对
您的选项应位于config/services.php
文件中
// V3 config: 'google' => [ 'recaptcha' => [ 'site_key' => env('GOOGLE_RECAPTCHA_SITE_KEY'), 'secret_key' => env('GOOGLE_RECAPTCHA_SECRET_KEY'), 'version' => 'v3', 'score' => 0.5, // An integer between 0 and 1, that indicates the minimum score to pass the Captcha challenge. ], ], // V2 config: 'google' => [ 'recaptcha' => [ 'site_key' => env('GOOGLE_RECAPTCHA_SITE_KEY'), 'secret_key' => env('GOOGLE_RECAPTCHA_SECRET_KEY'), 'version' => 'v2', 'size' => 'normal', // 'normal', 'compact' or 'invisible'. 'theme' => 'light', // 'light' or 'dark'. ], ],
组件
在您的Livewire组件中,在表单提交方法中,添加#[ValidatesRecaptcha]
属性
use Livewire\Component; class SomeComponent extends Component { use DutchCodingCompany\LivewireRecaptcha\ValidatesRecaptcha; // (optional) Set a response property on your component. // If not given, the `gRecaptchaResponse` property is dynamically assigned. public string $gRecaptchaResponse; #[ValidatesRecaptcha] public function save(): mixed { // Your logic here will only be called if the captcha passes... } }
为了精细控制,您可以使用以下方式传递自定义密钥和最小分数(仅适用于V3)
#[ValidatesRecaptcha(secretKey: 'mysecretkey', score: 0.9)]
视图
在视图端,您必须包含Blade指令@livewireRecaptcha
。这将在页面中添加两个脚本,一个用于reCAPTCHA脚本,一个用于自定义Livewire指令,以便将其钩入表单提交。
最好只将这些脚本添加到具有受Captcha保护表单的页面(或者,您可以在更高层级添加@livewireRecaptcha
指令,例如在布局中)。
其次,将新的指令wire:recaptcha
添加到您想要保护的表单元素中。
<!-- some-livewire-component.blade.php --> <!-- (optional) Add error handling --> @if($errors->has('gRecaptchaResponse')) <div class="alert alert-danger">{{ $errors->first('gRecaptchaResponse') }}</div> @endif <!-- Add the `wire:recaptcha` Livewire directive --> <form wire:submit="save" wire:recaptcha> <!-- The rest of your form --> <button type="submit">Submit</button> </form> <!-- Add the `@livewireRecaptcha` Blade directive --> @livewireRecaptcha
您可以使用以下方式覆盖任何配置值
@livewireRecaptcha( version: 'v2', siteKey: 'abcd_efgh-hijk_LMNOP', theme: 'dark', size: 'compact', )
完成
在表单实际提交之前,Google ReCAPTCHA验证将自动发生。在执行save()
方法之前,将向Google发送服务器端请求以验证Captcha挑战。一旦reCAPTCHA响应成功,您的实际Livewire组件方法将被执行。
错误处理
当Captcha验证发生错误时,将抛出ValidationException
,键为gRecaptchaResponse
。在'livewire-recaptcha::recaptcha.invalid_response'
下有一个可翻译的错误消息。