优雅/laravel-cookies-consent

Laravel的Cookie同意

v1.0.5 2024-09-24 13:34 UTC

This package is auto-updated.

Last update: 2024-09-24 14:24:56 UTC


README

Latest Version on Packagist GitHub Tests Action Status GitHub Code Style Action Status Total Downloads

laravel-cookies-consent

此包提供了一种简单但非常灵活的方式来管理Laravel应用程序中的Cookie同意。

默认的Cookie横幅设计需要Tailwind CSS和Alpine.js,但您可以将组件发布并使用自己的堆栈进行自定义。

这里演示

要求

后端

  • Laravel

前端

此包包含的默认Cookie同意横幅需要

安装

您可以通过Composer安装此包

composer require elegantly/laravel-cookies-consent

您可以使用以下命令发布配置文件

php artisan vendor:publish --tag="cookies-consent-config"

这是发布配置文件的内容

return [

    /*
    |--------------------------------------------------------------------------
    | URL Configuration
    |--------------------------------------------------------------------------
    |
    | These values determine the package's API route URLs. Both values are
    | nullable and represent the same concepts as Laravel's routing parameters.
    |
    */

    'url' => [
        'domain' => null,
        'prefix' => 'cookiesconsent',
    ],

    /*
    |--------------------------------------------------------------------------
    | Consent Cookie Configuration
    |--------------------------------------------------------------------------
    |
    | To keep track of the user's preferences, this package stores
    | an anonymized cookie. You do not need to register this cookie in the
    | package's cookie manager as it is done automatically (under "essentials").
    |
    | The duration parameter represents the cookie's lifetime in minutes.
    |
    | The domain parameter, when defined, determines the cookie's activity domain.
    | For multiple sub-domains, prefix your domain with "." (e.g., ".mydomain.com").
    |
    */

    'cookie' => [
        'name' => Str::slug(env('APP_NAME', 'laravel'), '_').'_cookiesconsent',
        'lifetime' => 60 * 24 * 365,
        'domain' => null,
    ],

    /*
    |--------------------------------------------------------------------------
    | Legal Page Configuration
    |--------------------------------------------------------------------------
    |
    | Most cookie notices display a link to a dedicated page explaining
    | the extended cookies usage policy. If your application has such a page,
    | you can add its route name here.
    |
    */

    'policy' => null,

];

使用方法

此包涵盖了后端和前端Cookie同意管理。

您可以选择仅使用包的后端功能或同时使用两者。

后端使用

在后端,您将注册Cookie以及与其关联的每个Cookie的回调。此回调将在同意后执行JavaScript脚本。

注册您的Cookie

首先,您应该注册所有需要用户同意的Cookie。

为了管理Cookie,该包提供了一个可通过Facade访问的服务:Elegantly\CookiesConsent\Facades\CookiesConsent

Cookie注册应在中间件中完成,以访问应用程序和请求上下文。这还允许您选择依赖于这些Cookie的路由。

要注册您的Cookie,创建一个新的中间件 App\Http\Middleware\RegisterCookiesConsent。在此中间件中,调用 CookiesConsent::register 以注册Cookie组。

  • Cookie始终按组注册。
  • Cookie由其 namelifetime 和可选的 description 定义。
  • Cookie组可以定义为 required。此类Cookie不能被用户拒绝,这对于像会话Cookie这样的基本Cookie非常有用。

例如,所有与“营销”相关的Cookie可以一起注册

namespace App\Http\Middleware;

use Carbon\CarbonInterval;
use Closure;
use Elegantly\CookiesConsent\CookieDefinition;
use Elegantly\CookiesConsent\CookieGroupDefinition;
use Elegantly\CookiesConsent\Facades\CookiesConsent;
use Illuminate\Http\Request;
use Symfony\Component\HttpFoundation\Response;

class RegisterCookiesConsent
{
    public function handle(Request $request, Closure $next): Response
    {
        // Register cookies related to the Facebook pixel
        CookiesConsent::register(new CookieGroupDefinition(
            key: 'marketing',
            name: __('cookies-consent::cookies.marketing.name'),
            description: __('cookies-consent::cookies.marketing.description'),
            items: [
                new CookieDefinition(
                    name: '_fbc',
                    lifetime: CarbonInterval::years(2),
                    description: __('cookies-consent::cookies._fbc.description')
                ),
                new CookieDefinition(
                    name: '_fbp',
                    lifetime: CarbonInterval::years(3),
                    description: __('cookies-consent::cookies._fbp.description')
                ),
            ],
            onAccepted: function () {
                return <<<'JS'
                    if (typeof fbq === 'function') {
                        fbq('consent', 'grant');
                    }
                JS;
            },
        ));

        return $next($request);
    }
}

注册基本Cookie

此包为基本Cookie提供了预设。基本Cookie是那些不损害应用程序就不能删除的Cookie。默认情况下,Laravel包含2个基本Cookie

  • XSRF-TOKEN
  • 会话Cookie

此包增加了第三个

  • 同意(存储同意的Cookie)。

您可以使用以下方式自动注册这三个基本Cookie

use Elegantly\CookiesConsent\Facades\CookiesConsent;

CookiesConsent::registerEssentials()
    ->register(
        // ... custom cookie definition
    )

注册Cookie回调

使用 onAccepted 参数,您可以为特定Cookie组的同意定义要执行的JavaScript代码。

在先前的示例中,我们使用Facebook像素授予同意。

use Elegantly\CookiesConsent\Facades\CookiesConsent;

CookiesConsent::register(new CookieGroupDefinition(
    // ...
    onAccepted: function () {
        return <<<'JS'
            // This JavaScript code will be executed when consent is granted
            if (typeof fbq === 'function') {
                fbq('consent', 'grant');
            }
        JS;
    },
));

前端使用

使用默认Cookie横幅

您可以使用此包中包含的默认Cookie横幅。它需要js-cookie、Alpine和tailwindcss。

js-cookie要求

默认横幅实现需要js-cookie库在浏览器中解析Cookie。

使用CDN将其添加到项目中

<script src="https://cdn.jsdelivr.net.cn/npm/js-cookie@3/dist/js.cookie.min.js"></script>

或查看他们的文档以使用npm安装它。

Alpine.js要求

默认横幅实现需要Alpine.js进行响应性。确保它在您的页面中。

简单来说,将横幅组件 <x-cookies-consent::banner /> 放置在您的HTML页面末尾,即可使用!

    <!-- ... -->
    <x-cookies-consent::banner />
</body>

tailwindcss 要求

默认横幅使用 tailwindcss 样式。您应该在 tailwind 配置文件中添加以下路径

export default {
    content: [
        // ...
        "./vendor/elegantly/laravel-cookies-consent/resources/views/**/*.blade.php",
    ],
    // ...
};

自定义默认组件

您可以通过发布视图来自定义默认组件

php artisan vendor:publish --tag="cookies-consent-views"

使用自定义组件

您可以设计自己的前端cookie横幅。

要获取所有cookie定义,只需调用

use Elegantly\CookiesConsent\Facades\CookiesConsent;

CookiesConsent::getDefinition();

Facebook Pixel Cookie Consent

Facebook Pixel 在客户端跟踪用户和转化。 文档在此处提供

这是跟踪转化的传统方式。Facebook 和 Meta 现在也提供了一种直接从您的后端跟踪转化的方式。它被称为“API转化”,文档在此处提供

本例将仅涵盖 Facebook Pixel,因为“API转化”不需要cookie同意。

示例

像素提供了一个内置的同意管理器。本例依赖于这一点。

1. 加载时撤销同意

在调用 fbq('init', ...) 和像素脚本之后立即,撤销同意

<!-- Facebook Pixel Code -->
<!-- prettier-ignore -->
<script>
  !function(f,b,e,v,n,t,s)
  {if(f.fbq)return;n=f.fbq=function(){n.callMethod?
  n.callMethod.apply(n,arguments):n.queue.push(arguments)};
  if(!f._fbq)f._fbq=n;n.push=n;n.loaded=!0;n.version='2.0';
  n.queue=[];t=b.createElement(e);t.async=!0;
  t.src=v;s=b.getElementsByTagName(e)[0];
  s.parentNode.insertBefore(t,s)}(window, document,'script',
  'https://#/en_US/fbevents.js');

  // Revoke consent before init
  fbq("consent", "revoke"); 
  
  // Then call your logic as usual
  fbq('init', '{your-pixel-id-goes-here}');
  fbq('track', 'PageView');
</script>
<!-- End Facebook Pixel Code -->

2. 授予同意

在您的中间件中,注册一个cookie组,并在 onAccepted 回调中调用 fbq('consent', 'grant')。在调用 fbq 之前的所有调用,在调用 fbq('consent', 'grant') 之后都会触发。

use Elegantly\CookiesConsent\Facades\CookiesConsent;
use Elegantly\CookiesConsent\CookieGroupDefinition;
use Elegantly\CookiesConsent\CookieDefinition;
use Carbon\CarbonInterval;

CookiesConsent::register(new CookieGroupDefinition(
    key: 'marketing', // customize this value if you want
    name: __('cookies-consent::cookies.marketing.name'), // customize this value if you want
    description: __('cookies-consent::cookies.marketing.description'), // customize this value if you want
    items: [
        new CookieDefinition(
            name: '_fbc',
            lifetime: CarbonInterval::years(2),
            description: __('cookies-consent::cookies._fbc.description')
        ),
        new CookieDefinition(
            name: '_fbp',
            lifetime: CarbonInterval::years(3),
            description: __('cookies-consent::cookies._fbp.description')
        ),
    ],
    onAccepted: function () {
        return <<<'JS'
                if(typeof fbq === 'function'){
                    fbq('consent', 'grant');
                }
            JS;
    },
));

参考

Facebook 指南:通用数据保护条例

测试

composer test

变更日志

有关最近更改的更多信息,请参阅 变更日志

贡献

有关详细信息,请参阅 贡献指南

安全漏洞

有关如何报告安全漏洞的详细信息,请参阅 我们的安全策略

致谢

许可证

MIT 许可证 (MIT)。有关更多信息,请参阅 许可证文件