statikbe / laravel-cookie-consent

The package includes a script & styling for a cookie banner and a modal where the visitor can select his/her cookie preferences.
MIT License
156 stars 27 forks source link

Consent mode v2 #62

Open Yarooooo opened 6 months ago

Yarooooo commented 6 months ago

Is there a way II can use this to comply this with new Consent mode v2 ?

hamrak commented 1 month ago

1. Add Google Consent Mode Script

Add the Google Consent Mode script to your Blade template. This script should be included before any other scripts on your page.

<!-- Add this in your main layout file, typically in the <head> section -->
<script async src="https://www.googletagmanager.com/gtag/js?id=YOUR_TRACKING_ID"></script>
<script>
    window.dataLayer = window.dataLayer || [];
    function gtag(){dataLayer.push(arguments);}
    gtag('consent', 'default', {
        'ad_storage': 'denied',
        'analytics_storage': 'denied'
    });
    gtag('js', new Date());
    gtag('config', 'YOUR_TRACKING_ID');
</script>

Replace YOUR_TRACKING_ID with your actual Google Analytics tracking ID.

2. Modify the Cookie Consent Configuration

Update the configuration to handle consent for different types of cookies. You need to categorize cookies and ensure that the consent state is respected.

In the config/cookie-consent.php file:

return [
    'enabled' => env('COOKIE_CONSENT_ENABLED', true),
    'cookie_name' => 'laravel_cookie_consent',
    'cookie_lifetime' => 7300, // 20 years in days

    'customize_consent' => [
        'ad_storage' => [
            'label' => 'Marketing cookies',
            'description' => 'Allow us to personalize your experience and send you relevant content and offers.',
            'default' => 'denied',
            'required' => false,
        ],
        'analytics_storage' => [
            'label' => 'Analytical cookies',
            'description' => 'Allow us to analyze website use and improve visitor experience.',
            'default' => 'denied',
            'required' => false,
        ],
        // Add other categories as needed
    ],
];

3. Update Blade Template for Consent

Modify the Blade template used by the package to include the consent categories. This template is usually found at resources/views/vendor/cookie-consent/index.blade.php.

<div id="cookie-consent">
    <div class="cookie-consent__message">
        {{ __('This website uses cookies to ensure you get the best experience on our website.') }}
    </div>
    <div class="cookie-consent__buttons">
        <button class="cookie-consent__agree">
            {{ __('Accept all cookies') }}
        </button>
        <button class="cookie-consent__customize">
            {{ __('Customize settings') }}
        </button>
    </div>
    <div id="cookie-consent-customize" style="display: none;">
        @foreach (config('cookie-consent.customize_consent') as $key => $category)
            <div class="cookie-consent__category">
                <label>
                    <input type="checkbox" name="cookie_consent[{{ $key }}]" {{ $category['default'] == 'granted' ? 'checked' : '' }}>
                    {{ __($category['label']) }}
                </label>
                <p>{{ __($category['description']) }}</p>
            </div>
        @endforeach
        <button class="cookie-consent__save">
            {{ __('Save settings') }}
        </button>
    </div>
</div>

<script>
    document.querySelector('.cookie-consent__agree').addEventListener('click', function () {
        gtag('consent', 'update', {
            'ad_storage': 'granted',
            'analytics_storage': 'granted'
        });
        document.cookie = "laravel_cookie_consent=granted; path=/";
        document.getElementById('cookie-consent').style.display = 'none';
    });

    document.querySelector('.cookie-consent__customize').addEventListener('click', function () {
        document.getElementById('cookie-consent-customize').style.display = 'block';
    });

    document.querySelector('.cookie-consent__save').addEventListener('click', function () {
        const consentSettings = {};
        document.querySelectorAll('#cookie-consent-customize input').forEach(function (input) {
            consentSettings[input.name.split('[')[1].split(']')[0]] = input.checked ? 'granted' : 'denied';
        });
        gtag('consent', 'update', consentSettings);
        document.cookie = "laravel_cookie_consent=" + JSON.stringify(consentSettings) + "; path=/";
        document.getElementById('cookie-consent').style.display = 'none';
    });
</script>

4. Handle Consent States

In your middleware or wherever you check for consent, read the cookie and set the appropriate state.

// Example of reading the consent cookie
$consentCookie = json_decode($_COOKIE['laravel_cookie_consent'] ?? '{}', true);

if ($consentCookie['analytics_storage'] ?? 'denied' === 'granted') {
    // Load analytics scripts
}

if ($consentCookie['ad_storage'] ?? 'denied' === 'granted') {
    // Load marketing scripts
}

5. Ensure Cookie Consent Logic

Ensure your controllers, views, and scripts respect the user’s consent. For instance, only load tracking scripts if the user has granted consent.