laravel-google-recaptcha-v3

repository·master·Indexed 42 days ago

https://github.com/ryandadeng/laravel-google-recaptcha-v3

Searchable repository documentation for Ryandadeng Laravel Google Recaptcha V3 from https://github.com/ryandadeng/laravel-google-recaptcha-v3.

Tokens
8K
Snippets
24
Records
27
Agent score
53%

What's inside laravel-google-recaptcha-v3

  1. Configure reCAPTCHA Badge Display Styles

    master

    You can control how the reCAPTCHA badge appears by modifying the configuration:

    • Corner (Default): Set 'inline' => false in the config. The badge appears in the bottom right.
    • Inline: Set 'inline' => true in the config. The badge is displayed within the form where the reCAPTCHA is rendered.
    • Invisible: Set 'inline' => true and apply display: none to the reCAPTCHA div. Note: You must include the Google Privacy Policy and Terms of Service text on your page to comply with Google's requirements.
  2. Install Laravel Google reCAPTCHA v3

    master

    Install the package via Composer. If you are using a Laravel version $\le$ 5.4, you must manually register the Service Provider and Facade in config/app.php. For Laravel $\ge$ 5.5, the package supports auto-discovery.

    $ composer require timehunter/laravel-google-recaptcha-v3 "~2.5"

    Manual registration for Laravel $\le$ 5.4:

    'providers' = [
        ....,
        TimeHunter\LaravelGoogleReCaptchaV3\Providers\GoogleReCaptchaV3ServiceProvider::class
    ]
    
    'aliases' = [
         ....,
         'GoogleReCaptchaV3' => TimeHunter\LaravelGoogleReCaptchaV3\Facades\GoogleReCaptchaV3::class
    ]
  3. Publish package configuration, Vue components, and translations

    master

    You can publish the package's assets to your application to customize them. Use the following Artisan commands to publish specific parts of the package:

    • Configuration: Publishes config/googlerecaptchav3.php to your application's config/ directory. Tag: googlerecaptchav3.config.
    • Vue Component: Publishes the GoogleReCaptchaV3.vue component to resources/js/components/googlerecaptchav3/GoogleReCaptchaV3.vue. Tag: googlerecaptchav3.vuejs.
    • Translations: Publishes language files to resources/lang/vendor/GoogleReCaptchaV3. Tag: googlerecaptchav3.lang.
    php artisan vendor:publish --tag=googlerecaptchav3.config
    php artisan vendor:publish --tag=googlerecaptchav3.vuejs
    php artisan vendor:publish --tag=googlerecaptchav3.lang
  4. Use the Google reCAPTCHA v3 Vue component

    master

    For package versions >= 2.2.0, you can use a lightweight Vue component. You must first publish the component to your project to gain control over the file and its configuration.

    1. Publish the component

    Run the following Artisan command to publish the Vue component file to js/components/googlerecaptchav3/GoogleReCaptchaV3.vue:

    2. Integrate into your Vue application

    Import the component and register it. You can provide the site-key via a prop or by hard-coding it directly into the published component file.

    Supported Props:

    • siteKey: The reCAPTCHA site key string.
    • id: The HTML ID for the component.
    • inline: Boolean to enable inline mode.
    • action: The reCAPTCHA action name (e.g., contact_us).
    • v-model: Binds the reCAPTCHA response token to your form data.

    Important: You must call .execute() on the component ref every time you submit a form to refresh the reCAPTCHA token.

    $ php artisan vendor:publish --provider="TimeHunter\LaravelGoogleReCaptchaV3\Providers\GoogleReCaptchaV3ServiceProvider" --tag=googlerecaptchav3.vuejs
    <template>
        <div class="container">
            <form @submit.prevent="submit">
                <google-re-captcha-v3
                  v-model="form.gRecaptchaResponse"
                  ref="captcha"
                  :site-key="mySiteKeyVariable"
                  id="contact_us_id"
                  inline
                  action="contact_us"
                ></google-re-captcha-v3>
                <button type="submit">Submit</button>
            </form>
        </div>
    </template>
    
    <script>
        import GoogleReCaptchaV3 from '../../components/googlerecaptchav3/GoogleReCaptchaV3';
    
        export default {
            components: {
                GoogleReCaptchaV3
            },
            data() {
                return {
                    form: {
                        gRecaptchaResponse: null
                    },
                    mySiteKeyVariable: 'Your Site Key String',
                }
            },
            methods: {
                submit() {
                    axios.post('/verify', this.form).then(
                        response => {
                            this.$refs.captcha.execute(); // Refresh token on success
                        }
                    ).catch(
                        error => {
                            this.$refs.captcha.execute(); // Refresh token on error
                        });
                }
            }
        }
    </script>
  5. Publish Configuration, Vue, and Language Assets

    master

    Use the following Artisan commands to publish the necessary assets to your project:

    • Config: googlerecaptchav3.config (creates config/googlerecaptchav3.php)
    • Vue Components: googlerecaptchav3.vuejs (creates js/components/googlerecaptchav3)
    • Translations: googlerecaptchav3.lang (creates resources/lang/vendor/GoogleReCaptchaV3/*)
    # Publish configuration
    $ php artisan vendor:publish --provider="TimeHunter\LaravelGoogleReCaptchaV3\Providers\GoogleReCaptchaV3ServiceProvider" --tag=googlerecaptchav3.config
    
    # Publish Vue components
    $ php artisan vendor:publish --provider="TimeHunter\LaravelGoogleReCaptchaV3\Providers\GoogleReCaptchaV3ServiceProvider" --tag=googlerecaptchav3.vuejs
    
    # Publish language files
    $ php artisan vendor:publish --provider="TimeHunter\LaravelGoogleReCaptchaV3\Providers\GoogleReCaptchaV3ServiceProvider" --tag=googlerecaptchav3.lang
  6. Display reCAPTCHA v3 in Blade templates

    master

    To use reCAPTCHA in your views, follow these steps:

    1. Initialize the API: Include the script at the bottom of your layout file using {!! GoogleReCaptchaV3::init() !!}. To support Content Security Policy, you can pass a nonce: {!! GoogleReCaptchaV3::init(['nonce' => nonce()]) !!}.
    2. Render the reCAPTCHA: Use one of the following methods to place the reCAPTCHA in your forms:
      • render(['id1'=>'action1', 'id2'=>'action2']): Renders multiple reCAPTCHAs. Requires corresponding div elements with matching IDs in your HTML.
      • renderOne($id, $action): Renders a single reCAPTCHA for a specific ID.
      • renderField($id, $action, $class, $style): Renders the reCAPTCHA as an input field directly within the form.
    {{-- 1. Initialize in layout --}}
    {!! GoogleReCaptchaV3::init() !!}
    
    {{-- 2. Method One: render() --}}
    <form method="POST" action="/verify">
        <div id="contact_us_id"></div>
        <input type="submit" value="submit">
    </form>
    {!! GoogleReCaptchaV3::render(['contact_us_id'=>'contact_us']) !!}
    
    {{-- 2. Method Two: renderOne() --}}
    <form method="POST" action="/verify">
        <div id="signup_id"></div>
        <input type="submit" value="submit">
    </form>
    {!! GoogleReCaptchaV3::renderOne('signup_id', 'signup') !!}
    
    {{-- 2. Method Three: renderField() --}}
    <form method="POST" action="/verify">
       {!! GoogleReCaptchaV3::renderField('contact_us_id', 'contact_us_action') !!}
        <input type="submit" value="submit">
    </form>
  7. Configure reCAPTCHA credentials and score thresholds

    master

    Set your Google credentials in your .env file:

    RECAPTCHA_V3_SECRET_KEY=
    RECAPTCHA_V3_SITE_KEY=

    In config/googlerecaptchav3.php, you can define specific settings for different actions, including the threshold and whether to perform score_comparison.

    Note: To use score_comparison, you must set 'is_score_enabled' => true in the config file.

    'setting' =  [
        [
            'action' => 'contact_us', // Google reCAPTCHA required parameter
            'threshold' => 0.2, // score threshold
            'score_comparison' => false // if true, system compares score against threshold for this action
        ],
        [
            'action' => 'signup',
            'threshold' => 0.2,
            'score_comparison' => true
        ],
    ]
    
    'is_score_enabled' = true
  8. Configure the HTTP request method

    master

    The package allows you to choose between two HTTP request clients via the configuration. This is handled by binding the RequestClientInterface based on the value returned by the configuration's getRequestMethod() method:

    • guzzle: Uses GuzzleRequestClient.
    • curl: Uses CurlRequestClient (this is the default if the method is not recognized).
  9. Verify reCAPTCHA using the GoogleReCaptchaV3 Facade

    master

    You can verify responses directly in your controllers using the GoogleReCaptchaV3 facade.

    • setAction($action): (Optional) Sets the action to verify against the Google response.
    • verifyResponse($token, $ip = null): Verifies the token. Returns a response object.
    • setScore($score): (Optional) Manually assigns a score, which bypasses config-based score checking.

    Methods available on the response object:

    • getMessage(): Returns the status message.
    • isSuccess(): Returns boolean success status.
    • toArray(): Returns response data as an array.
    // Basic verification
    GoogleReCaptchaV3::setAction($action)->verifyResponse($value, $ip = null);
    
    // Checking success and getting message
    $response = GoogleReCaptchaV3::verifyResponse($request->input('g-recaptcha-response'), $request->getClientIp());
    if ($response->isSuccess()) {
        // logic
    }
    
    // Manual score override
    GoogleReCaptchaV3::setScore($score)
        ->setAction($action)
        ->verifyResponse($request->input('g-recaptcha-response'), $request->getClientIp());
  10. Access the GoogleReCaptchaV3 service

    master

    The package binds the main service to the Laravel Service Container under the string identifier GoogleReCaptchaV3. You can resolve this instance to interact with the reCAPTCHA V3 functionality.

    The service is constructed using a configuration object (ReCaptchaConfigV3Interface) and a request client (RequestClientInterface).

    $reCaptcha = app('GoogleReCaptchaV3');
  11. Refresh reCAPTCHA response during Ajax requests

    master

    The package provides two JavaScript functions to handle reCAPTCHA during asynchronous operations:

    • getReCaptchaV3Response(fieldId): Retrieves the current reCAPTCHA response token by the element's ID.
    • refreshReCaptchaV3(fieldId, actionName): Resets the reCAPTCHA response. This should be called after an Ajax request (on success or error) to ensure a fresh token is available for the next submission.
    // Example Ajax usage
    $("#test").click(function (e) {
        e.preventDefault();
        $.ajax({
            type: 'POST',
            url: '/verify',
            data: {
                'g-recaptcha-response': getReCaptchaV3Response('contact_id')
            },
            success: function (data) {
                refreshReCaptchaV3('contact_id', 'contact');
            },
            error: function(err){
                refreshReCaptchaV3('contact_id', 'contact');
            }
        });
    });
  12. Implement a custom ReCaptchaConfigV3Interface

    master

    If you need to store your reCAPTCHA configuration (like site keys or secrets) in a custom location such as a database instead of standard config files, implement the TimeHunter\LaravelGoogleReCaptchaV3\Interfaces\ReCaptchaConfigV3Interface interface.

    After creating your implementation, bind it in your application's Service Provider.

    // 1. Implement the interface
    class YourOwnCustomImplementation implements ReCaptchaConfigV3Interface {
        // ... implementation logic
    }
    
    // 2. Register in your Service Provider
    $this->app->bind(
        \TimeHunter\LaravelGoogleReCaptchaV3\Interfaces\ReCaptchaConfigV3Interface::class,
        YourOwnCustomImplementation::class
    );