Created
November 18, 2025 16:40
-
-
Save Lelectrolux/b782c9eb41d8c49de5b79fe953946f7f to your computer and use it in GitHub Desktop.
Laravel Rule for Google Recaptcha v3
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| <?php | |
| declare(strict_types=1); | |
| namespace App\Rules; | |
| use Closure; | |
| use Illuminate\Contracts\Validation\ValidationRule; | |
| use Illuminate\Support\Facades\Http; | |
| use Throwable; | |
| /** | |
| * @link https://developers.google.com/recaptcha/docs/v3 | |
| */ | |
| class RecaptchaRule implements ValidationRule | |
| { | |
| public bool $implicit = true; | |
| public function __construct( | |
| private string $hostname, | |
| private string $action, | |
| private ?string $ip, | |
| ) {} | |
| /** | |
| * Run the validation rule. | |
| * | |
| * @param Closure(string, ?string=): \Illuminate\Translation\PotentiallyTranslatedString $fail | |
| */ | |
| public function validate(string $attribute, mixed $value, Closure $fail): void | |
| { | |
| if (config('services.recaptcha.disabled')) { | |
| return; | |
| } | |
| if (empty($value)) { | |
| $fail(__('validation.recaptcha')); | |
| return; | |
| } | |
| try { | |
| $response = Http::createPendingRequest() | |
| ->asForm() | |
| ->post( | |
| 'https://www.google.com/recaptcha/api/siteverify', | |
| [ | |
| 'secret' => config('services.recaptcha.secret_key'), | |
| 'response' => $value, | |
| 'remoteip' => $this->ip, | |
| ] | |
| ); | |
| $response->throwUnlessStatus(200); | |
| if ($response->json('success') !== true | |
| || $response->json('hostname') !== $this->hostname | |
| || $response->json('action') !== $this->action | |
| || $response->json('score') <= config('services.recaptcha.threshold') | |
| ) { | |
| $fail(__('validation.recaptcha')); | |
| } | |
| } catch (Throwable $e) { | |
| report($e); | |
| $fail(__('validation.recaptcha')); | |
| } | |
| } | |
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| <?php | |
| declare(strict_types=1); | |
| return [ | |
| //... | |
| 'recaptcha' => [ | |
| 'site_key' => env('RECAPTCHA_SITE_KEY'), | |
| 'secret_key' => env('RECAPTCHA_SECRET_KEY'), | |
| 'threshold' => env('RECAPTCHA_THRESHOLD', 0.5), | |
| 'disabled' => (bool) env('RECAPTCHA_DISABLED', false), | |
| ], | |
| ]; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment