Laravel 集成 Google reCAPTCHA
谷歌reCAPTCHA是最常用的验证码系统。它可以帮助您保护您的网站免受欺诈活动、垃圾邮件和滥用行为的侵害。下面将介绍如何在 Laravel 项目中快速集成 Google reCAPTCHA。
1. 注册
点击这个链接免费注册一个 reCAPTCHA 账号,可以添加一个 localhost
域名以供本地测试时使用。创建成功后将 “secret key” 和 “site key” 复制到 .env
文件中。
RECAPTCHA_SITE_KEY=
RECAPTCHA_SECRET_KEY=
2. 自定义 Rule
php artisan make:rule ReCaptcha
use GuzzleHttp\Client;
use Illuminate\Contracts\Validation\Rule;
class ReCaptcha implements Rule
{
public function passes($attribute, $value): bool
{
$client = new Client();
$response = $client->post(
'https://www.google.com/recaptcha/api/siteverify',
[
'form_params' => [
'secret' => config('services.recaptcha.secret_key'),
'remoteip' => request()->getClientIp(),
'response' => $value
]
]
);
$body = json_decode((string)$response->getBody());
return $body->success;
// 如果是 reCAPTCHA v3, 你可以根据分数自行决定是否放行请求。
// $body->score > .3
}
public function message()
{
return 'Google thinks you are a bot, please refresh and try again';
}
}
3. 前端
最简单的集成 reCAPTCHA 的方式就是,自动将检测绑定到某个按钮上。这种集成方式可以做到用户无感知的情况下完成检测。这样当按钮被点击时,reCAPTCHA 会在表单中增加 g-recaptcha-response
字段。
@if(config('services.recaptcha.site_key'))
<script type="text/javascript"
src="https://www.google.com/recaptcha/api.js?hl=en" async defer>
</script>
<script>
function onSubmit(token) {
document.getElementById("demo-form").submit();
}
</script>
@endif
<button
@if(config('services.recaptcha.site_key'))
class="g-recaptcha"
data-sitekey="{{config('services.recaptcha.site_key')}}"
data-size="invisible"
data-callback="onSubmit"
@endif
>提交</button>
4. 使用
'g-recaptcha-response' => ['required', new ReCaptcha]
Reference
- https://developers.google.com/recaptcha/docs/verify