### Usage Example Source: https://github.com/josiasmontag/laravel-recaptchav3/blob/master/_autodocs/api-reference/Facade.md Demonstrates how to use the RecaptchaV3 facade in a Laravel application to verify tokens, get the site key, initialize JavaScript, and generate form fields. ```APIDOC ## Usage Example ### Description Illustrates common use cases for the RecaptchaV3 facade. ### Code ```php use Lunaweb\RecaptchaV3\Facades\RecaptchaV3; // Verify a reCAPTCHA token $score = RecaptchaV3::verify($token, 'register'); // Get the site key $siteKey = RecaptchaV3::sitekey(); // Initialize the reCAPTCHA JavaScript $js = RecaptchaV3::initJs(); // Generate a hidden input field for the reCAPTCHA response $field = RecaptchaV3::field('login'); ``` ``` -------------------------------- ### Install Laravel reCAPTCHA v3 Source: https://github.com/josiasmontag/laravel-recaptchav3/blob/master/_autodocs/README.md Install the package using Composer. This command adds the package to your project's dependencies. ```bash composer require josiasmontag/laravel-recaptchav3 ``` -------------------------------- ### Get Site Key with Facade Source: https://github.com/josiasmontag/laravel-recaptchav3/blob/master/_autodocs/README.md Retrieve the configured site key using the RecaptchaV3 facade. This is useful for frontend initialization. ```php use Lunaweb\RecaptchaV3\Facades\RecaptchaV3; RecaptchaV3::sitekey(); // Returns string ``` -------------------------------- ### Basic Facade Usage Source: https://github.com/josiasmontag/laravel-recaptchav3/blob/master/_autodocs/api-reference/Facade.md Demonstrates how to use the RecaptchaV3 facade for common tasks like verifying tokens, getting the site key, initializing JavaScript, and generating form fields. ```php use Lunaweb\RecaptchaV3\Facades\RecaptchaV3; // Use like a static class $score = RecaptchaV3::verify($token, 'register'); $siteKey = RecaptchaV3::sitekey(); $js = RecaptchaV3::initJs(); $field = RecaptchaV3::field('login'); ``` -------------------------------- ### Verify Method Usage Example Source: https://github.com/josiasmontag/laravel-recaptchav3/blob/master/_autodocs/types.md Demonstrates correct and incorrect ways to check the return value of the verify() method. Always use strict comparison to differentiate between a failed verification (false) and a successful verification with a score of 0.0. ```php $score = RecaptchaV3::verify($token); // Wrong: 0.0 is falsy, would execute error path if (!$score) { return error('Failed'); } // Correct: explicit false check if ($score === false) { return error('Failed'); } // Correct: strict inequality if ($score !== false && $score > 0.5) { return success(); } ``` -------------------------------- ### Example reCAPTCHA Siteverify Request Source: https://github.com/josiasmontag/laravel-recaptchav3/blob/master/_autodocs/endpoints.md An example of a raw HTTP POST request to the Google reCAPTCHA siteverify endpoint, demonstrating the expected format for form-encoded parameters. ```http POST /recaptcha/api/siteverify HTTP/1.1 Host: www.google.com Content-Type: application/x-www-form-urlencoded secret=your_secret_key&response=token_from_frontend&remoteip=203.0.113.45 ``` -------------------------------- ### Install Laravel Recaptcha V3 Source: https://github.com/josiasmontag/laravel-recaptchav3/blob/master/README.md Use Composer to add the package to your project's dependencies. Ensure RECAPTCHAV3_SITEKEY and RECAPTCHAV3_SECRET are added to your .env file. ```bash composer require josiasmontag/laravel-recaptchav3 ``` ```dotenv RECAPTCHAV3_SITEKEY=sitekey RECAPTCHAV3_SECRET=secret ``` -------------------------------- ### Example Validator Usage Source: https://github.com/josiasmontag/laravel-recaptchav3/blob/master/_autodocs/api-reference/ServiceProvider.md Demonstrates how to use the 'recaptchav3' validation rule in Laravel. This rule requires a reCAPTCHA token and an expected action, with an optional minimum score. ```php use Illuminate\Support\Facades\Validator; $validator = Validator::make($data, [ 'g-recaptcha-response' => 'required|recaptchav3:register,0.5' ]); if ($validator->fails()) { // Validation failed - either token is invalid or score is below 0.5 } ``` -------------------------------- ### Catching Token Validation Failures Source: https://github.com/josiasmontag/laravel-recaptchav3/blob/master/_autodocs/errors.md Demonstrates how to use the 'recaptchav3' validator in a Laravel application. This example specifically shows how to catch validation failures, which include token validation issues. ```php $validator = Validator::make($data, [ 'g-recaptcha-response' => 'required|recaptchav3:register,0.5' ]); if ($validator->fails()) { // Includes token validation failures $errors = $validator->errors(); } ``` -------------------------------- ### Get reCAPTCHA Site Key Source: https://github.com/josiasmontag/laravel-recaptchav3/blob/master/_autodocs/api-reference/RecaptchaV3.md Retrieves the configured reCAPTCHA site key. This key is used to initialize the reCAPTCHA script on the frontend. ```php use Lunaweb\RecaptchaV3\Facades\RecaptchaV3; $siteKey = RecaptchaV3::sitekey(); echo $siteKey; ``` -------------------------------- ### Get Recaptcha Score and Verify Source: https://github.com/josiasmontag/laravel-recaptchav3/blob/master/README.md Alternatively, you can manually get the score using RecaptchaV3::verify() and implement custom logic based on the score. Remember to import the facade. ```php // Import the facade class use Lunaweb\RecaptchaV3\Facades\RecaptchaV3; // RecaptchaV3::verify($token, $action) $score = RecaptchaV3::verify($request->get('g-recaptcha-response'), 'register') if($score > 0.7) { // go } elseif($score > 0.3) { // require additional email verification } else { return abort(400, 'You are most likely a bot'); } ``` -------------------------------- ### reCAPTCHA Siteverify Error Response Source: https://github.com/josiasmontag/laravel-recaptchav3/blob/master/_autodocs/endpoints.md An example JSON response when reCAPTCHA verification fails. The 'success' field is false, and 'error-codes' provides details about the failure. ```json { "success": false, "error-codes": ["invalid-input-secret"] } ``` -------------------------------- ### Catching Score Below Minimum Validation Failure Source: https://github.com/josiasmontag/laravel-recaptchav3/blob/master/_autodocs/errors.md This example shows how to set a higher minimum score requirement for the 'recaptchav3' validator. If the reCAPTCHA score is below this threshold, the validation will fail. ```php $validator = Validator::make($data, [ 'g-recaptcha-response' => 'required|recaptchav3:register,0.7' ]); if ($validator->fails()) { $errors = $validator->errors(); // $errors->get('g-recaptcha-response') contains the validation message } ``` -------------------------------- ### Validate reCAPTCHA using Laravel's Validator Rule Source: https://github.com/josiasmontag/laravel-recaptchav3/blob/master/_autodocs/00_START_HERE.md This example shows how to integrate reCAPTCHA verification directly into Laravel's validation system using the 'recaptchav3' rule. It requires the 'g-recaptcha-response' field and specifies the expected action and minimum score. ```php $request->validate([ 'g-recaptcha-response' => 'required|recaptchav3:register,0.5' ]); ``` -------------------------------- ### Mocking the Facade for Testing Source: https://github.com/josiasmontag/laravel-recaptchav3/blob/master/_autodocs/api-reference/Facade.md Shows how to mock the RecaptchaV3 facade using Mockery for unit testing purposes. This allows you to control the return values of facade methods. ```php RecaptchaV3::shouldReceive('verify') ->with('test_token', 'register') ->andReturn(0.95); // Now calls to RecaptchaV3::verify() will return 0.95 $score = RecaptchaV3::verify('test_token', 'register'); ``` -------------------------------- ### Configuration Type Annotations Source: https://github.com/josiasmontag/laravel-recaptchav3/blob/master/_autodocs/types.md Illustrates the expected string types for configuration values in the recaptchav3.php configuration file. ```php // From config/recaptchav3.php $origin = 'https://www.google.com/recaptcha'; // string $sitekey = ''; // string (empty by default) $secret = ''; // string (empty by default) $locale = ''; // string (empty by default) ``` -------------------------------- ### Testing with Mockery Source: https://github.com/josiasmontag/laravel-recaptchav3/blob/master/_autodocs/api-reference/Facade.md Shows how to mock the RecaptchaV3 facade using Mockery for testing purposes. ```APIDOC ## Testing with Mockery ### Description Provides an example of how to mock the RecaptchaV3 facade for unit testing. ### Code ```php use Lunaweb\RecaptchaV3\Facades\RecaptchaV3; // Mock the 'verify' method RecaptchaV3::shouldReceive('verify') ->with('test_token', 'register') ->andReturn(0.95); // Example of a call after mocking $score = RecaptchaV3::verify('test_token', 'register'); // $score will be 0.95 ``` ``` -------------------------------- ### Verify Token and Action Directly with Service Source: https://github.com/josiasmontag/laravel-recaptchav3/blob/master/_autodocs/README.md Instantiate and use the RecaptchaV3 service class directly to verify a reCAPTCHA token and action. This provides an alternative to using the facade. ```php use Lunaweb\RecaptchaV3\RecaptchaV3; app(RecaptchaV3::class)->verify($token, $action); ``` -------------------------------- ### Customized Configuration Source: https://github.com/josiasmontag/laravel-recaptchav3/blob/master/_autodocs/configuration.md This snippet illustrates a customized configuration, overriding the default locale to 'de' (German) and ensuring sitekey and secret are set. ```php 'https://www.google.com/recaptcha', 'sitekey' => env('RECAPTCHAV3_SITEKEY'), 'secret' => env('RECAPTCHAV3_SECRET'), 'locale' => 'de', // Always use German for reCAPTCHA UI ]; ``` -------------------------------- ### Initialize JavaScript, Generate Token Field, and Verify Token Source: https://github.com/josiasmontag/laravel-recaptchav3/blob/master/_autodocs/00_START_HERE.md This snippet demonstrates the core usage of the RecaptchaV3 facade. It shows how to initialize the JavaScript, generate a hidden token field for a form, and verify a submitted token on the backend. The verification logic includes handling different confidence scores. ```php use Lunaweb\RecaptchaV3\Facades\RecaptchaV3; // Initialize JavaScript in template {!! RecaptchaV3::initJs() !!} // Generate hidden token field {!! RecaptchaV3::field('register') !!} // Verify token (returns score 0.0-1.0 or false) $score = RecaptchaV3::verify($token, 'register'); if ($score === false) { // Token is invalid or action didn't match } elseif ($score > 0.7) { // High confidence human } elseif ($score > 0.3) { // Medium confidence, may need additional verification } else { // Low confidence, likely bot } ``` -------------------------------- ### initJs() Source: https://github.com/josiasmontag/laravel-recaptchav3/blob/master/_autodocs/api-reference/RecaptchaV3.md Generates a script tag to initialize the reCAPTCHA v3 JavaScript library. This script sources from the configured origin and uses the configured site key and locale. ```APIDOC ## initJs() ### Description Generates a script tag to initialize the reCAPTCHA v3 JavaScript library. ### Method ```php public function initJs(): string ``` ### Return Type `string` — HTML script tag for loading the reCAPTCHA JavaScript library. ### Example ```php use Lunaweb\RecaptchaV3\Facades\RecaptchaV3; // In a Blade template footer or header {!! RecaptchaV3::initJs() !!} // Output (example): // ``` ``` -------------------------------- ### Service Direct Usage Source: https://github.com/josiasmontag/laravel-recaptchav3/blob/master/_autodocs/README.md Allows direct instantiation and usage of the `RecaptchaV3` service class. ```APIDOC ## Service Direct Usage ### `app(RecaptchaV3::class)->verify($token, $action)` #### Description Verifies the provided reCAPTCHA token using the `RecaptchaV3` service instance. #### Method `POST` (Internal) #### Parameters - **token** (string) - Required - The reCAPTCHA token from the client-side. - **action** (string) - Optional - The action associated with the reCAPTCHA challenge. #### Return Type `float|bool` - Returns the score (float) if verification is successful, otherwise `false`. ### `app(RecaptchaV3::class)->sitekey()` #### Description Retrieves the configured reCAPTCHA site key using the `RecaptchaV3` service instance. #### Method `GET` (Internal) #### Return Type `string` - The reCAPTCHA site key. ### `app(RecaptchaV3::class)->initJs()` #### Description Generates the necessary HTML script tag for reCAPTCHA JavaScript initialization using the `RecaptchaV3` service instance. #### Method `GET` (Internal) #### Return Type `string` - An HTML script tag. ### `app(RecaptchaV3::class)->field($action, $name = 'g-recaptcha-response')` #### Description Generates an HTML hidden input field for the reCAPTCHA token and the necessary JavaScript using the `RecaptchaV3` service instance. #### Method `GET` (Internal) #### Parameters - **action** (string) - Required - The action associated with the reCAPTCHA challenge. - **name** (string) - Optional - The name attribute for the input field. Defaults to 'g-recaptcha-response'. #### Return Type `string` - HTML input field and script tag. ``` -------------------------------- ### sitekey() Source: https://github.com/josiasmontag/laravel-recaptchav3/blob/master/_autodocs/api-reference/RecaptchaV3.md Returns the configured reCAPTCHA site key. This key is used by the `initJs()` method to initialize the reCAPTCHA script on the frontend. ```APIDOC ## sitekey() ### Description Returns the configured reCAPTCHA site key. ### Method ```php public function sitekey(): string ``` ### Return Type `string` — The public reCAPTCHA site key configured via `RECAPTCHAV3_SITEKEY` environment variable or config. ### Example ```php use Lunaweb\RecaptchaV3\Facades\RecaptchaV3; $siteKey = RecaptchaV3::sitekey(); echo $siteKey; // outputs: your_site_key_here ``` ``` -------------------------------- ### Initialize Recaptcha Javascript Source: https://github.com/josiasmontag/laravel-recaptchav3/blob/master/README.md Add this to your header or footer template to initialize Recaptcha v3, which works best when loaded on every page. ```php {!! RecaptchaV3::initJs() !!} ``` -------------------------------- ### Facade Methods Source: https://github.com/josiasmontag/laravel-recaptchav3/blob/master/_autodocs/README.md Provides convenient static access to reCAPTCHA v3 functionalities. Recommended for most use cases. ```APIDOC ## Facade Methods ### `RecaptchaV3::verify($token, $action)` #### Description Verifies the provided reCAPTCHA token against Google's API. #### Method `POST` (Internal) #### Parameters - **token** (string) - Required - The reCAPTCHA token from the client-side. - **action** (string) - Optional - The action associated with the reCAPTCHA challenge. #### Return Type `float|bool` - Returns the score (float) if verification is successful, otherwise `false`. ### `RecaptchaV3::sitekey()` #### Description Retrieves the configured reCAPTCHA site key. #### Method `GET` (Internal) #### Return Type `string` - The reCAPTCHA site key. ### `RecaptchaV3::initJs()` #### Description Generates the necessary HTML script tag for reCAPTCHA JavaScript initialization. #### Method `GET` (Internal) #### Return Type `string` - An HTML script tag. ### `RecaptchaV3::field($action, $name = 'g-recaptcha-response')` #### Description Generates an HTML hidden input field for the reCAPTCHA token and the necessary JavaScript. #### Method `GET` (Internal) #### Parameters - **action** (string) - Required - The action associated with the reCAPTCHA challenge. - **name** (string) - Optional - The name attribute for the input field. Defaults to 'g-recaptcha-response'. #### Return Type `string` - HTML input field and script tag. ``` -------------------------------- ### Initialize reCAPTCHA v3 JavaScript Source: https://github.com/josiasmontag/laravel-recaptchav3/blob/master/_autodocs/endpoints.md Use this method in your Blade templates to load the reCAPTCHA v3 JavaScript library. This makes the `grecaptcha` object available in the browser for further interactions. ```php // In Blade template {!! RecaptchaV3::initJs() !!} // Output: // ``` -------------------------------- ### Configuration Publishing Command Source: https://github.com/josiasmontag/laravel-recaptchav3/blob/master/_autodocs/api-reference/ServiceProvider.md Shows the Artisan command to publish the reCAPTCHA v3 configuration file to your Laravel application. ```bash php artisan vendor:publish --provider="Lunaweb\RecaptchaV3\Providers\RecaptchaV3ServiceProvider" ``` -------------------------------- ### Laravel reCAPTCHA v3 Package File Structure Source: https://github.com/josiasmontag/laravel-recaptchav3/blob/master/_autodocs/00_START_HERE.md This illustrates the directory structure of the `josiasmontag/laravel-recaptchav3` package, showing the location of the main documentation files and the API reference directory. ```text output/ ├── 00_START_HERE.md (this file) ├── INDEX.md (navigation guide) ├── README.md (overview & quick start) ├── SUMMARY.txt (generation summary) ├── configuration.md ├── types.md ├── endpoints.md ├── errors.md └── api-reference/ ├── RecaptchaV3.md (main class) ├── ServiceProvider.md (registration) └── Facade.md (static access) ``` -------------------------------- ### Configure reCAPTCHA v3 Site Key and Secret Source: https://github.com/josiasmontag/laravel-recaptchav3/blob/master/_autodocs/README.md Add your Google reCAPTCHA v3 site key and secret key to your .env file for authentication. ```env RECAPTCHAV3_SITEKEY=your_site_key RECAPTCHAV3_SECRET=your_secret_key ``` -------------------------------- ### RecaptchaV3 Constructor Parameters Source: https://github.com/josiasmontag/laravel-recaptchav3/blob/master/_autodocs/api-reference/RecaptchaV3.md The constructor requires instances of Laravel's config repository, Guzzle HTTP client, request object, and application instance. These are automatically resolved by Laravel's service container. ```php public function __construct( Illuminate\Contracts\Config\Repository $config, GuzzleHttp\Client $client, Illuminate\Http\Request $request, Illuminate\Contracts\Foundation\Application $app ): void ``` -------------------------------- ### Verify Token and Action with Facade Source: https://github.com/josiasmontag/laravel-recaptchav3/blob/master/_autodocs/README.md Use the RecaptchaV3 facade to verify a reCAPTCHA token and action. This method returns the score as a float or false if verification fails. ```php use Lunaweb\RecaptchaV3\Facades\RecaptchaV3; RecaptchaV3::verify($token, $action); // Returns score (float) or false ``` -------------------------------- ### RecaptchaV3 Facade Methods Source: https://github.com/josiasmontag/laravel-recaptchav3/blob/master/_autodocs/api-reference/Facade.md The RecaptchaV3 facade provides static methods for interacting with the reCAPTCHA v3 service. These methods mirror the public methods of the underlying RecaptchaV3 class. ```APIDOC ## RecaptchaV3 Facade Methods ### Description Provides static access to reCAPTCHA v3 verification and form generation functionalities. ### Methods - **verify(string $token, ?string $action = null): bool|float** Verifies the reCAPTCHA token against the Google API and returns the score. - **sitekey(): string** Retrieves the reCAPTCHA site key configured for the application. - **initJs(): string** Generates the necessary JavaScript snippet to load the reCAPTCHA API. - **field(string $action, string $name = 'g-recaptcha-response'): string** Generates an HTML input field for the reCAPTCHA response token. ``` -------------------------------- ### Service Constructor Dependencies Source: https://github.com/josiasmontag/laravel-recaptchav3/blob/master/_autodocs/types.md Shows the types of dependencies automatically injected by the Laravel service container into the RecaptchaV3 service. ```php // Automatically injected by Laravel service container function __construct( Repository $config, // Config repository Client $client, // Guzzle HTTP client Request $request, // Current HTTP request Application $app // Laravel application ): void ``` -------------------------------- ### Initialize reCAPTCHA JavaScript Source: https://github.com/josiasmontag/laravel-recaptchav3/blob/master/_autodocs/api-reference/RecaptchaV3.md Generates an HTML script tag to load the reCAPTCHA v3 JavaScript library. Ensure this is called before using the field() method. ```php use Lunaweb\RecaptchaV3\Facades\RecaptchaV3; // In a Blade template footer or header {!! RecaptchaV3::initJs() !!} // Output (example): // ``` -------------------------------- ### RecaptchaV3 Class Methods Source: https://github.com/josiasmontag/laravel-recaptchav3/blob/master/_autodocs/SUMMARY.txt The main service class provides methods for interacting with Google reCAPTCHA v3. These include verifying user submissions, retrieving the site key, initializing JavaScript, and managing form fields. ```APIDOC ## RecaptchaV3 Methods ### Description Provides the core functionality for integrating Google reCAPTCHA v3 into a Laravel application. This class handles verification requests and provides helper methods for frontend integration. ### Methods - **verify(string $token, string $action = null): Verifies a reCAPTCHA token against the Google API. Returns a boolean indicating success or failure, or a score if configured. - **sitekey(): Retrieves the configured reCAPTCHA site key. - **initJs(array $options = []): Generates the necessary JavaScript snippet to initialize reCAPTCHA v3 on the frontend. - **field(array $options = []): Generates an HTML input field for the reCAPTCHA token, typically used within forms. ``` -------------------------------- ### Composer Extra Configuration for Auto-Registration Source: https://github.com/josiasmontag/laravel-recaptchav3/blob/master/_autodocs/api-reference/ServiceProvider.md Illustrates the 'extra' configuration in composer.json that enables Laravel to automatically register the RecaptchaV3ServiceProvider and its facade. ```json { "extra": { "laravel": { "providers": [ "Lunaweb\\RecaptchaV3\\Providers\\RecaptchaV3ServiceProvider" ], "aliases": { "RecaptchaV3": "Lunaweb\\RecaptchaV3\\Facades\\RecaptchaV3" } } } } ``` -------------------------------- ### Testing with Mocked Responses Source: https://github.com/josiasmontag/laravel-recaptchav3/blob/master/_autodocs/README.md Use this snippet for testing reCAPTCHA verification logic by mocking the 'verify' method. This allows you to simulate different reCAPTCHA scores without actual API calls. ```php use Lunaweb\RecaptchaV3\Facades\RecaptchaV3; // In tests RecaptchaV3::shouldReceive('verify') ->with('test_token', 'register') ->andReturn(0.95); $score = RecaptchaV3::verify('test_token', 'register'); // Returns 0.95 ``` -------------------------------- ### Mock Recaptcha Facade for Testing Source: https://github.com/josiasmontag/laravel-recaptchav3/blob/master/README.md For testing purposes, you can mock the RecaptchaV3 facade to control its behavior, such as simulating a successful verification. ```php RecaptchaV3::shouldReceive('verify') ->once() ->andReturn(1.0); ``` -------------------------------- ### Required Environment Variables Source: https://github.com/josiasmontag/laravel-recaptchav3/blob/master/_autodocs/configuration.md Set these environment variables in your .env file to provide your reCAPTCHA site key and secret key. These are essential for the package to function. ```env RECAPTCHAV3_SITEKEY=your_site_key_here RECAPTCHAV3_SECRET=your_secret_key_here ``` -------------------------------- ### Facade Accessor Method Source: https://github.com/josiasmontag/laravel-recaptchav3/blob/master/_autodocs/api-reference/Facade.md This method returns the fully-qualified class name of the underlying service for the facade. ```php protected static function getFacadeAccessor(): string ``` -------------------------------- ### POST Request to Google Siteverify Endpoint Source: https://github.com/josiasmontag/laravel-recaptchav3/blob/master/_autodocs/endpoints.md This snippet shows the internal HTTP POST request made by the package to Google's siteverify API. It includes the necessary form parameters for verification. ```php $response = $this->http->request('POST', $this->origin . '/api/siteverify', [ 'form_params' => [ 'secret' => $this->secret, 'response' => $token, 'remoteip' => $this->request->getClientIp(), ], ]); ``` -------------------------------- ### RecaptchaV3Facade Source: https://github.com/josiasmontag/laravel-recaptchav3/blob/master/_autodocs/SUMMARY.txt The Laravel Facade provides static access to the RecaptchaV3 service, simplifying its usage throughout the application. ```APIDOC ## RecaptchaV3Facade ### Description Allows for static method calls to the `RecaptchaV3` service, mirroring the instance methods. This is the primary way to interact with the package in most Laravel applications. ### Methods All public methods of the `RecaptchaV3` class are available via the facade, including: - **verify(string $token, string $action = null): - **sitekey(): - **initJs(array $options = []): - **field(array $options = []): ### Example Usage ```php use ReCaptchaV3Facade; $isHuman = ReCaptchaV3Facade::verify($token); ``` ``` -------------------------------- ### field() Source: https://github.com/josiasmontag/laravel-recaptchav3/blob/master/_autodocs/api-reference/RecaptchaV3.md Generates an invisible input field and script to execute reCAPTCHA and populate the field with a token. This method requires `initJs()` to have been called previously. ```APIDOC ## field() ### Description Generates an invisible input field and script to execute reCAPTCHA and populate the field with a token. ### Method ```php public function field(string $action, string $name = 'g-recaptcha-response'): string ``` ### Parameters #### Parameters - **`$action`** (string) - Required - The reCAPTCHA action name for this field (e.g., 'register', 'login') - **`$name`** (string) - Optional - The HTML input name and ID prefix (default: `'g-recaptcha-response'`) ### Return Type `string` — HTML containing a hidden input field and inline JavaScript to populate it with a reCAPTCHA token. ### Example ```php use Lunaweb\RecaptchaV3\Facades\RecaptchaV3; // In a Blade form template
@csrf {!! RecaptchaV3::field('register') !!}
// For custom field names {!! RecaptchaV3::field('purchase', 'captcha-token') !!} ``` ``` -------------------------------- ### Testing reCAPTCHA Verification Failures Source: https://github.com/josiasmontag/laravel-recaptchav3/blob/master/_autodocs/errors.md Mock the `verify` method to simulate different reCAPTCHA verification outcomes during testing. This is useful for ensuring your error handling logic works correctly. ```php RecaptchaV3::shouldReceive('verify') ->with('invalid_token', 'register') ->andReturn(false); $score = RecaptchaV3::verify('invalid_token', 'register'); // $score is false RecaptchaV3::shouldReceive('verify') ->with('valid_token', 'register') ->andReturn(0.4); $score = RecaptchaV3::verify('valid_token', 'register'); // $score is 0.4 ``` -------------------------------- ### Locale Resolution Logic Source: https://github.com/josiasmontag/laravel-recaptchav3/blob/master/_autodocs/configuration.md This code snippet shows how the locale is determined within the RecaptchaV3 constructor, prioritizing environment variables and configuration settings. ```php $this->locale = $config['recaptchav3']['locale'] ?? $app->getLocale(); ``` -------------------------------- ### Error Handling Pattern for Recaptcha Verification Source: https://github.com/josiasmontag/laravel-recaptchav3/blob/master/_autodocs/INDEX.md Demonstrates the correct way to check the result of RecaptchaV3::verify(). Avoid treating a score of 0.0 as false; instead, perform an explicit check for false or compare the score directly. ```php $score = RecaptchaV3::verify($token, 'action'); // Wrong: 0.0 is falsy if (!$score) { /* ... */ } // Correct: explicit false check if ($score === false) { /* handle error */ } if ($score !== false && $score > 0.5) { /* proceed */ } ``` -------------------------------- ### Score-Based Decision Endpoint with ReCAPTCHA v3 Verification Source: https://github.com/josiasmontag/laravel-recaptchav3/blob/master/_autodocs/endpoints.md Implement this in a POST route to verify a ReCAPTCHA v3 token and take actions based on the returned score. The 'login' action string should match the one used in the frontend. ```php Route::post('/login', function (Request $request) { use Lunaweb ecaptchaV3 acades ecaptchaV3; $email = $request->get('email'); $token = $request->get('g-recaptcha-response'); $score = recaptchaV3::verify($token, 'login'); if ($score === false) { return response('Verification failed', 400); } if ($score > 0.7) { // High confidence return response('Login successful', 200); } elseif ($score > 0.3) { // Medium confidence: require additional verification return response('Please verify your email', 202); } else { // Low confidence return response('Verification failed', 400); } }); ``` -------------------------------- ### Method Return Type Signatures Source: https://github.com/josiasmontag/laravel-recaptchav3/blob/master/_autodocs/types.md Lists the explicit return types for various methods within the RecaptchaV3 class. ```php RecaptchaV3::verify(string, ?string): bool|float RecaptchaV3::sitekey(): string RecaptchaV3::initJs(): string RecaptchaV3::field(string, string = '...'): string ``` -------------------------------- ### verify() Source: https://github.com/josiasmontag/laravel-recaptchav3/blob/master/_autodocs/api-reference/RecaptchaV3.md Verifies a reCAPTCHA v3 token against Google's API and optionally validates the action. It returns a confidence score or false on failure. ```APIDOC ## verify() ### Description Verifies a reCAPTCHA v3 token against Google's API and optionally validates the action. It returns a confidence score or false on failure. ### Method POST ### Endpoint /verify ### Parameters #### Query Parameters - **token** (string) - Required - The reCAPTCHA response token from the frontend - **action** (string) - Optional - Expected action name; verification fails if token action does not match ### Response #### Success Response - **score** (float) - A float between 0.0 and 1.0 representing the confidence score. #### Error Response - **false** - Verification fails due to invalid token, invalid action, or API errors. ### Example ```php use Lunaweb\RecaptchaV3\Facades\RecaptchaV3; // Verify token without action validation $score = RecaptchaV3::verify($token); if ($score !== false && $score > 0.7) { // Allow the action } // Verify token with specific action $score = RecaptchaV3::verify($token, 'register'); if ($score === false) { // Token validation failed } // Use score to make variable decisions if ($score > 0.7) { // High confidence: proceed directly } elseif ($score > 0.3) { // Medium confidence: require additional verification } else { // Low confidence: reject or challenge } ``` ``` -------------------------------- ### reCAPTCHA v3 Origin Configuration Source: https://github.com/josiasmontag/laravel-recaptchav3/blob/master/_autodocs/endpoints.md The package's origin URL for API calls is configurable via the `RECAPTCHAV3_ORIGIN` environment variable. This allows for proxying or testing against alternative endpoints. ```php // Default $origin = 'https://www.google.com/recaptcha' // Can be overridden via RECAPTCHAV3_ORIGIN environment variable $origin = env('RECAPTCHAV3_ORIGIN', 'https://www.google.com/recaptcha'); // Used to construct: // POST {$origin}/api/siteverify (verification) // GET {$origin}/api.js (frontend script) ``` -------------------------------- ### Explicitly Check for Verification Failure Source: https://github.com/josiasmontag/laravel-recaptchav3/blob/master/_autodocs/00_START_HERE.md This snippet highlights the importance of explicitly checking the return value of the `verify` method for `false` to handle verification failures. It demonstrates a common pattern for conditional logic based on the verification outcome. ```php if ($score === false) { /* error */ } if ($score !== false && $score > 0.5) { /* proceed */ } ``` -------------------------------- ### Environment Variables for reCAPTCHA Configuration Source: https://github.com/josiasmontag/laravel-recaptchav3/blob/master/_autodocs/00_START_HERE.md This shows the essential environment variables required to configure the Laravel reCAPTCHA v3 package. It includes the site key, secret key, and optional settings for the API origin and locale. ```env RECAPTCHAV3_SITEKEY=your_key RECAPTCHAV3_SECRET=your_secret RECAPTCHAV3_ORIGIN=https://www.google.com/recaptcha # optional RECAPTCHAV3_LOCALE=en # optional ``` -------------------------------- ### Generate reCAPTCHA Field with Token Source: https://github.com/josiasmontag/laravel-recaptchav3/blob/master/_autodocs/api-reference/RecaptchaV3.md Creates an invisible input field and JavaScript to execute reCAPTCHA and populate the field with a token. The reCAPTCHA library must be initialized first using initJs(). ```php use Lunaweb\RecaptchaV3\Facades\RecaptchaV3; // In a Blade form template
@csrf {!! RecaptchaV3::field('register') !!}
// For custom field names {!! RecaptchaV3::field('purchase', 'captcha-token') !!} ``` -------------------------------- ### Variable Actions Based on Score Source: https://github.com/josiasmontag/laravel-recaptchav3/blob/master/_autodocs/README.md This snippet demonstrates how to dynamically adjust application logic based on the reCAPTCHA score. It requires importing the RecaptchaV3 facade and handling different score ranges. ```php use Lunaweb\RecaptchaV3\Facades\RecaptchaV3; $score = RecaptchaV3::verify($request->get('token'), 'login'); if ($score === false) { abort(400, 'Verification failed'); } if ($score > 0.7) { // Proceed normally Auth::login($user); } elseif ($score > 0.3) { // Require additional verification (email, 2FA, etc.) Session::put('requires_2fa', true); } else { // Reject or block abort(429, 'Too many attempts'); } ``` -------------------------------- ### Successful reCAPTCHA Siteverify Response Source: https://github.com/josiasmontag/laravel-recaptchav3/blob/master/_autodocs/endpoints.md A sample JSON response from Google's siteverify endpoint indicating a successful verification. It includes a confidence score, action, and hostname. ```json { "success": true, "score": 0.9, "action": "register", "challenge_ts": "2023-06-15T10:30:45Z", "hostname": "example.com", "error-codes": [] } ``` -------------------------------- ### Accessing reCAPTCHA v3 Configuration Source: https://github.com/josiasmontag/laravel-recaptchav3/blob/master/_autodocs/configuration.md Retrieve the reCAPTCHA v3 site key and secret directly using Laravel's Config facade or through the RecaptchaV3 facade. ```php use Lunaweb.RecaptchaV3.Facades.RecaptchaV3; use Illuminate.Support.Facades.Config; // Access configuration directly $sitekey = Config::get('recaptchav3.sitekey'); $secret = Config::get('recaptchav3.secret'); // Or through the service $sitekey = RecaptchaV3::sitekey(); ``` -------------------------------- ### reCAPTCHA Verification with Variable Actions Source: https://github.com/josiasmontag/laravel-recaptchav3/blob/master/_autodocs/errors.md Handle verification results based on different confidence scores. This allows for tiered security measures, such as requiring additional verification for medium confidence scores. ```php $score = RecaptchaV3::verify($token, 'register'); if ($score === false) { // Handle invalid token or action mismatch return redirect()->back()->withErrors('reCAPTCHA verification failed'); } if ($score > 0.7) { // High confidence user } elseif ($score > 0.3) { // Medium confidence: require additional verification Session::put('needs_email_verification', true); } else { // Low confidence: reject return abort(400); } ``` -------------------------------- ### RecaptchaV3Facade Class Source: https://github.com/josiasmontag/laravel-recaptchav3/blob/master/_autodocs/_MANIFEST.txt The RecaptchaV3Facade provides a static interface to the RecaptchaV3 class, allowing for easier access to its methods without direct dependency injection. ```APIDOC ## RecaptchaV3Facade ### Description Provides a convenient static facade for the RecaptchaV3 service. Allows calling methods like `RecaptchaV3::verify()` directly. ### Methods - **`verify(string $token, string $action = null)`**: Verifies the reCAPTCHA token. - **`sitekey(): string`**: Gets the site key. - **`initJs(): string`**: Generates the JavaScript initialization snippet. - **`field(string $name, string $value = null, array $attributes = [])`**: Generates the hidden input field for the token. ``` -------------------------------- ### Check for Action Mismatch in reCAPTCHA Source: https://github.com/josiasmontag/laravel-recaptchav3/blob/master/_autodocs/errors.md This snippet shows how to handle cases where the reCAPTCHA token's action does not match the expected action parameter. This occurs when the frontend action differs from the backend validation. ```PHP if ($action && (!isset($body['action']) || $action != $body['action'])) { return false; } ``` ```PHP $score = RecaptchaV3::verify($token, 'register'); if ($score === false) { // Either token is invalid or action doesn't match return response('Verification failed', 400); } ``` -------------------------------- ### Generate reCAPTCHA JavaScript Tag with Facade Source: https://github.com/josiasmontag/laravel-recaptchav3/blob/master/_autodocs/README.md Generate the necessary HTML script tag for reCAPTCHA JavaScript using the RecaptchaV3 facade. This should be included in your HTML head. ```php use Lunaweb\RecaptchaV3\Facades\RecaptchaV3; RecaptchaV3::initJs(); // Returns HTML script tag ``` -------------------------------- ### Optional Environment Variables Source: https://github.com/josiasmontag/laravel-recaptchav3/blob/master/_autodocs/configuration.md These optional environment variables allow for customization of the reCAPTCHA API origin and locale. The origin is rarely needed and useful for testing or proxies, while the locale can override the application's default. ```env # Custom reCAPTCHA API origin (rarely needed, useful for testing or proxies) RECAPTCHAV3_ORIGIN=https://www.google.com/recaptcha # Override application locale specifically for reCAPTCHA RECAPTCHAV3_LOCALE=en ``` -------------------------------- ### Generate reCAPTCHA Input Field and Script with Facade Source: https://github.com/josiasmontag/laravel-recaptchav3/blob/master/_autodocs/README.md Generate both the hidden input field for the reCAPTCHA token and the necessary JavaScript to capture it using the RecaptchaV3 facade. This is a convenient way to add reCAPTCHA to your forms. ```php use Lunaweb\RecaptchaV3\Facades\RecaptchaV3; RecaptchaV3::field($action); // Returns HTML input + script ``` -------------------------------- ### Default Configuration Source: https://github.com/josiasmontag/laravel-recaptchav3/blob/master/_autodocs/configuration.md This snippet shows the default configuration array for Laravel reCAPTCHA v3, which reads values from environment variables. ```php env('RECAPTCHAV3_ORIGIN', 'https://www.google.com/recaptcha'), 'sitekey' => env('RECAPTCHAV3_SITEKEY', ''), 'secret' => env('RECAPTCHAV3_SECRET', ''), 'locale' => env('RECAPTCHAV3_LOCALE', '') ]; ``` -------------------------------- ### RecaptchaV3ServiceProvider Source: https://github.com/josiasmontag/laravel-recaptchav3/blob/master/_autodocs/SUMMARY.txt The Service Provider handles the registration of the reCAPTCHA v3 service within the Laravel application's service container and defines custom validation rules. ```APIDOC ## RecaptchaV3ServiceProvider ### Description Manages the bootstrapping of the reCAPTCHA v3 service in Laravel. It registers the `RecaptchaV3` class as a singleton and makes it available via the facade. It also defines a custom validation rule for reCAPTCHA verification. ### Key Responsibilities - **Service Registration**: Registers the `RecaptchaV3` service in the container. - **Facade Registration**: Binds the facade accessor. - **Custom Validator**: Provides a `recaptcha` validation rule for form requests. ``` -------------------------------- ### Google reCAPTCHA Siteverify Endpoint Source: https://github.com/josiasmontag/laravel-recaptchav3/blob/master/_autodocs/endpoints.md Verifies a reCAPTCHA token submitted from the client-side to the backend. This endpoint is called by the `RecaptchaV3::verify()` method. ```APIDOC ## POST https://www.google.com/recaptcha/api/siteverify ### Description Verifies a reCAPTCHA token submitted from the client-side to the backend. This endpoint is called by the `RecaptchaV3::verify()` method. ### Method POST ### Endpoint https://www.google.com/recaptcha/api/siteverify ### Parameters #### Request Body - **secret** (string) - Required - The reCAPTCHA secret key from configuration - **response** (string) - Required - The reCAPTCHA token from the frontend - **remoteip** (string) - Optional - Client IP address for additional verification context ### Request Example ``` POST /recaptcha/api/siteverify HTTP/1.1 Host: www.google.com Content-Type: application/x-www-form-urlencoded secret=your_secret_key&response=token_from_frontend&remoteip=203.0.113.45 ``` ### Response #### Success Response (200) - **success** (boolean) - Yes - Whether the verification was successful - **score** (number) - If success=true - Confidence score (0.0 to 1.0) - **action** (string) - If success=true - The action name from the token - **challenge_ts** (string) - Yes - ISO 8601 timestamp of the challenge - **hostname** (string) - Yes - The hostname of the site where the reCAPTCHA was rendered - **error-codes** (array) - If success=false - Array of error code strings #### Response Example ```json { "success": true, "score": 0.9, "action": "register", "challenge_ts": "2023-06-15T10:30:45Z", "hostname": "example.com", "error-codes": [] } ``` #### Error Handling - **200 OK**: Request was successful (check `success` field for verification result) - **400 Bad Request**: Malformed parameters - **500 Internal Server Error**: Server error at Google's API The endpoint returns HTTP 200 with `"success": false` and `error-codes` for verification failures: ```json { "success": false, "error-codes": ["invalid-input-secret"] } ``` ``` -------------------------------- ### Google Siteverify Endpoint Source: https://github.com/josiasmontag/laravel-recaptchav3/blob/master/_autodocs/_MANIFEST.txt Details about the Google siteverify API endpoint used for verifying reCAPTCHA responses. ```APIDOC ## Google Siteverify Endpoint ### Description This endpoint is used by the backend to verify the reCAPTCHA response token submitted by the client. ### Method POST ### Endpoint `https://www.google.com/recaptcha/api/siteverify` ### Parameters #### Request Body - **`secret`** (string) - Required - Your reCAPTCHA secret key. - **`response`** (string) - Required - The user response token provided by the reCAPTCHA client-side integration. - **`remoteip`** (string) - Optional - The user's IP address. ### Response #### Success Response (200) - **`success`** (boolean) - Whether the verification was successful. - **`score`** (float) - The score for the given user response (0.0 to 1.0). - **`action`** (string) - The action name provided in the verify method. - **`challenge_ts`** (string) - Timestamp of the challenge (date-time). - **`hostname`** (string) - The hostname of the site where the reCAPTCHA was solved. #### Error Response - **`success`** (boolean) - Always `false`. - **`error-codes`** (array) - An array of error codes. ### Error Codes - `missing-input-secret` - `invalid-input-secret` - `missing-input-response` - `invalid-input-response` - `bad-request` - `timeout-or-duplicate` ### Example Application Endpoints - **Verify form submission:** Check the reCAPTCHA score before processing sensitive form data. - **API endpoint protection:** Ensure requests to critical API endpoints are from legitimate users. ``` -------------------------------- ### Registering the recaptchav3 Validator Rule Source: https://github.com/josiasmontag/laravel-recaptchav3/blob/master/_autodocs/errors.md This snippet shows how the 'recaptchav3' validator rule is extended in the service provider. It verifies the reCAPTCHA token against a specified action and minimum score. ```php $this->app['validator']->extend('recaptchav3', function ($attribute, $value, $parameters) { $action = $parameters[0]; $minScore = isset($parameters[1]) ? (float)$parameters[1] : 0.5; $score = RecaptchaV3Facade::verify($value, $action); return $score && $score >= $minScore; }); ``` -------------------------------- ### Verify Method Return Type Signature Source: https://github.com/josiasmontag/laravel-recaptchav3/blob/master/_autodocs/types.md Defines the union return type for the verify() method, which can be a boolean or a float between 0.0 and 1.0. ```php public function verify($token, $action = null): bool|float ``` -------------------------------- ### Google reCAPTCHA API Siteverify Response Structure Source: https://github.com/josiasmontag/laravel-recaptchav3/blob/master/_autodocs/types.md This is the JSON structure returned by the Google reCAPTCHA verification API. The package utilizes 'success', 'score', and 'action' fields for verification. ```json { "success": boolean, "score": float (0.0 to 1.0), "action": string, "challenge_ts": string (ISO 8601 timestamp), "hostname": string, "error-codes": [string] } ``` -------------------------------- ### Set Recaptcha Locale Source: https://github.com/josiasmontag/laravel-recaptchav3/blob/master/README.md Specify a custom locale for the package by setting the RECAPTCHAV3_LOCALE environment variable. By default, it uses the application's default locale. ```dotenv RECAPTCHAV3_LOCALE=ar ``` -------------------------------- ### Create Recaptcha Field in Form Source: https://github.com/josiasmontag/laravel-recaptchav3/blob/master/README.md Use RecaptchaV3::field() to create an invisible input field that is filled with a Recaptcha token on load. This is typically used within a form. ```html
{!! RecaptchaV3::field('register') !!}
```