Laravel WordPress CMS vừa tích hợp xong reCAPTCHA v3
Mình chia sẽ lại cách cho anh em nào cần dùng để tránh trường hợp spam.
Đăng nhập trang googgle tạo 1 tài khoản https://www.google.com/recaptcha/about/
Ở đây mình đã đăng ký rồi việc này cũng dễ nên các bạn có thể làm nhanh.
LINK docs của nó khá chi tiết https://developers.google.com/recaptcha/docs/v3
Thêm vào file config/services.php
'recaptcha' => [
'enable' => env('GOOGLE_RECAPTCHA_ENABLED'),
'site_key' => env('GOOGLE_RECAPTCHA_KEY'),
'secret' => env('GOOGLE_RECAPTCHA_SECRET'),
],
(adsbygoogle = window.adsbygoogle || []).push({});
Ở đây mình có tạo 3 biến ở file .env
GOOGLE_RECAPTCHA_ENABLED=true
GOOGLE_RECAPTCHA_KEY=22222
GOOGLE_RECAPTCHA_SECRET=2222222
Tiếp tục tạo file app/Validators/ReCaptcha.php nội dung như sau
<?php
namespace App\Validators;
use GuzzleHttp\Client;
class ReCaptcha
{
public function validate($attribute, $value, $parameters, $validator){
$client = new Client();
$response = $client->post(
'https://www.google.com/recaptcha/api/siteverify',
['form_params'=>
[
'secret'=> config('services.recaptcha.secret'),
'response'=> $value
]
]
);
$body = json_decode((string)$response->getBody());
return $body->success;
}
}
Tiếp tục ở page view resources/views/admin/login/index.blade.php
Mình bổ sung thêm vào code google ở head
<script src="https://www.google.com/recaptcha/api.js?render={{ config('services.recaptcha.site_key') }}"></script>
<script>
function onSubmit(token) {
document.getElementsByClassName("recaptcha")[0].submit();
}
</script>
Chổ button submit mình thêm vào
<button class="g-recaptcha btn btn-primary px-4" data-sitekey="{{ config('services.recaptcha.site_key') }}" data-callback='onSubmit' data-action='submit'>
<i class="fa fa-sign-in"></i>
Login
</button>
Xem hình cho dễ hình dung
Ở phí controller mình sẽ xử lý như sau app/Http/Controllers/Admin/LoginController.php
$rules = [
'email' => 'required|min:5|max:255',
'password' => 'required|min:1|max:255',
];
if (config('services.recaptcha.enable')) {
$rules['g-recaptcha-response'] = 'required|min:5|recaptcha';
}
$request->validate($rules);
Như vậy khi submit form sẽ check validator cho mình luôn
Thử test hàng của mình xem nào.
Source Laravel WordPress CMS của mình đã tích hợp sẳn mọi người có thể download về tham khảo.
1 COMMENT
tinh.nguyen
Update ngày 03/06/2021
Frontend update:
Backend update: