定制 abr4xas/clarity-laravel 二次开发

按需修改功能、优化性能、对接业务系统,提供一站式技术支持

邮箱:yvsm@zunyunkeji.com | QQ:316430983 | 微信:yvsm316

abr4xas/clarity-laravel

Composer 安装命令:

composer require abr4xas/clarity-laravel

包简介

Easy integration of Microsoft Clarity into your Laravel application.

README 文档

README

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

Easy integration of Microsoft Clarity into your Laravel application.

Installation

You can install the package via composer:

composer require abr4xas/clarity-laravel

You can publish the config file with:

php artisan vendor:publish --tag="clarity-config"

This is the contents of the published config file:

<?php

return [
    'id' => env('CLARITY_ID', 'XXXXXX'),
    'enabled' => env('CLARITY_ENABLED', true),
    'enabled_identify_api' => env('CLARITY_IDENTIFICATION_ENABLED', false),
    'global_tags' => [],
    'consent_version' => env('CLARITY_CONSENT_VERSION', 'v2'),
    'consent_required' => env('CLARITY_CONSENT_REQUIRED', false),
    'auto_tag_environment' => env('CLARITY_AUTO_TAG_ENV', true),
    'auto_tag_routes' => env('CLARITY_AUTO_TAG_ROUTES', false),
    'auto_identify_users' => env('CLARITY_AUTO_IDENTIFY', false),
];

Optionally, you can publish the views using

php artisan vendor:publish --tag="clarity-views"

Usage

General Tracking

  • Create an account: The first thing you need to do is create an account on Microsoft Clarity. You can sign up on their website and follow the steps to create your account. Then, get your tracking code and that's it.
  • Simply add the blade components to your base layout files.

The enabled attribute is optional, but can be used to control the tags integration from blade files that extend the base layout. It accepts true/false. This can still be controlled globally via the .env file should you need to disable the integration global on different environments as well.

<!-- Should be placed in the head -->
<x-clarity::script :enabled="$enabled" />

Custom Tags API

Microsoft Clarity's Custom Tags API allows you to segment and filter sessions on the Clarity dashboard using custom metadata. This is useful for tracking user roles, subscription plans, feature flags, A/B test variants, and more.

Using the Blade Component

<!-- Set a single value -->
<x-clarity::tag key="plan" :values="['premium']" />

<!-- Set multiple values -->
<x-clarity::tag key="features" :values="['chat', 'video', 'notifications']" />

<!-- Dynamic values -->
<x-clarity::tag key="user_role" :values="[auth()->user()->role]" />

Using the Helper Function

For more programmatic use cases, you can use the clarity_tag() helper function anywhere in your application:

// In a controller
clarity_tag('subscription', 'pro');

// Multiple values
clarity_tag('permissions', 'read', 'write', 'admin');

// Array of values
clarity_tag('features', ['feature_a', 'feature_b']);

// In middleware
class TrackUserSegment
{
    public function handle($request, Closure $next)
    {
        if (auth()->check()) {
            clarity_tag('user_segment', auth()->user()->segment);
        }
        return $next($request);
    }
}

The helper will return the rendered script tag which you can echo in your views, or it will return null if Clarity is disabled.

Global Tags

Global tags are automatically applied to all Clarity sessions. Define them in your config/clarity.php file:

'global_tags' => [
    'environment' => [env('APP_ENV', 'production')],
    'version' => ['1.0.0'],
    'region' => ['us-east'],
],

These tags will be automatically included when the Clarity script loads, making it easy to filter sessions by environment, version, or any other global attribute.

Consent API

Microsoft Clarity supports Cookie Consent APIs for GDPR/CCPA compliance. This package supports both Consent V1 and V2.

Configuration

// In config/clarity.php or .env
'consent_version' => env('CLARITY_CONSENT_VERSION', 'v2'), // 'v1' or 'v2'
'consent_required' => env('CLARITY_CONSENT_REQUIRED', false),

Using the Blade Component

<!-- Grant consent (V2 - recommended) -->
<x-clarity::consent :granted="true" />

<!-- Deny consent (V2) -->
<x-clarity::consent :granted="false" />

Using the Helper Function

// Grant consent
clarity_consent(true);

// Deny consent
clarity_consent(false);

Important

Consent V2 is recommended and will be enforced for EEA, UK, and Switzerland users starting October 31, 2025.

Auto-Tagging Middleware

The package includes middleware that automatically tags sessions with useful information:

  • Environment tagging: Automatically tags sessions with the current environment (local, staging, production)
  • Route tagging: Optionally tags sessions with route names and prefixes
  • Auto-identification: Automatically identifies authenticated users

Registering the Middleware

For Laravel 11+:

You need to manually register the middleware in your bootstrap/app.php file. Add it to the web middleware group:

// bootstrap/app.php

use Illuminate\Foundation\Application;
use Illuminate\Foundation\Configuration\Exceptions;
use Illuminate\Foundation\Configuration\Middleware;

return Application::configure(basePath: dirname(__DIR__))
    ->withMiddleware(function (Middleware $middleware) {
        $middleware->web(append: [
            \Abr4xas\ClarityLaravel\Middleware\ClarityMiddleware::class,
            // or use the alias:
            // 'clarity',
        ]);
    })
    ->withExceptions(function (Exceptions $exceptions) {
        //
    })->create();

For Laravel 10 and below:

You need to manually register the middleware in your app/Http/Kernel.php file. Add it to the web middleware group:

// app/Http/Kernel.php

protected $middlewareGroups = [
    'web' => [
        // ... other middleware
        \Abr4xas\ClarityLaravel\Middleware\ClarityMiddleware::class,
        // or use the alias:
        // 'clarity',
    ],
];

Alternatively, you can apply it to specific routes or route groups:

// In your routes file
Route::middleware('clarity')->group(function () {
    // Your routes
});

Configuration

Configure the middleware behavior in config/clarity.php:

'auto_tag_environment' => env('CLARITY_AUTO_TAG_ENV', true),
'auto_tag_routes' => env('CLARITY_AUTO_TAG_ROUTES', false),
'auto_identify_users' => env('CLARITY_AUTO_IDENTIFY', false),

When enabled, these tags and identifications are automatically included in your Clarity sessions without any additional code.

Identify API

To implement the Identify API, use identify component. Set CLARITY_IDENTIFICATION_ENABLED value to true on the env file.

Attributes:

  • user attribute is required accepts the User Model instance or any object. The email and name attributes are used.
  • enabled attribute is optional.
  • custom_session_id attribute is optional.
  • custom_page_id attribute is optional.
@auth
    <x-clarity::identify :user="request()->user()"/>
@endauth

This will compile as:

window.clarity("identify", "user@example.com", null, null, "Username")

Using the Helper Function

You can also use the clarity_identify() helper for programmatic identification:

// Basic usage
clarity_identify(auth()->user());

// With custom session and page IDs
clarity_identify(
    user: auth()->user(),
    customSessionId: 'custom-session-123',
    customPageId: 'checkout-page'
);

Custom IDs

You can set custom user IDs, session IDs, and page IDs independently using dedicated helpers or components. Note: These require the Identify API to be enabled (CLARITY_IDENTIFICATION_ENABLED=true).

Using Helper Functions

// Set custom user ID
clarity_set_custom_user_id('user-123');

// Set custom session ID
clarity_set_custom_session_id('session-456');

// Set custom page ID
clarity_set_custom_page_id('page-789');

Using Blade Components

<x-clarity::custom-user-id user_id="user-123" />
<x-clarity::custom-session-id session_id="session-456" />
<x-clarity::custom-page-id page_id="page-789" />

Queue System

The package includes a queue system that ensures tags and other Clarity API calls are executed even if Clarity hasn't fully loaded yet. This is handled automatically - tags are queued and processed when Clarity becomes available.

You can also manually include the queue component if needed:

<x-clarity::queue />

Available Helper Functions

This package provides convenient helper functions for use anywhere in your Laravel application:

  • clarity_tag(string $key, mixed ...$values): ?string - Set custom tags for session filtering
  • clarity_identify(object $user, ?string $customSessionId = null, ?string $customPageId = null): ?string - Identify a user in the current session (requires Identify API enabled)
  • clarity_consent(bool $granted = true): ?string - Set consent for the current session
  • clarity_set_custom_user_id(string $userId): ?string - Set a custom user ID (requires Identify API enabled)
  • clarity_set_custom_session_id(string $sessionId): ?string - Set a custom session ID (requires Identify API enabled)
  • clarity_set_custom_page_id(string $pageId): ?string - Set a custom page ID (requires Identify API enabled)

These helpers respect your configuration settings and will return null when Clarity is disabled.

Advanced Usage Examples

Complete Setup with Auto-Tagging

// config/clarity.php
return [
    'id' => env('CLARITY_ID'),
    'enabled' => env('CLARITY_ENABLED', true),
    'enabled_identify_api' => true,
    'auto_tag_environment' => true,
    'auto_tag_routes' => true,
    'auto_identify_users' => true,
    'global_tags' => [
        'app_version' => [config('app.version')],
        'deployment' => [env('DEPLOYMENT_ID')],
    ],
];

Conditional Consent Handling

// In your cookie consent handler
if ($userConsented) {
    echo clarity_consent(true);
} else {
    echo clarity_consent(false);
}

Dynamic Tagging Based on User Actions

// In a controller after user action
public function upgradePlan(Request $request)
{
    // ... upgrade logic ...

    // Tag the session for analysis
    clarity_tag('plan_upgrade', [
        'from' => $request->user()->plan,
        'to' => $request->input('new_plan'),
        'timestamp' => now()->toIso8601String(),
    ]);

    return redirect()->route('dashboard');
}

Testing

composer test

Changelog

Please see CHANGELOG for more information on what has changed recently.

Contributing

Please see CONTRIBUTING for details.

Security Vulnerabilities

Please review our security policy on how to report security vulnerabilities.

Credits

License

The MIT License (MIT). Please see License File for more information.

This package is strongly inspired by Google Tag Manager for Laravel created by @awcodes.

abr4xas/clarity-laravel 适用场景与选型建议

abr4xas/clarity-laravel 是一款 基于 PHP 开发的 Composer 扩展包,目前已累计 76.77k 次下载、GitHub Stars 达 57, 最近一次更新时间为 2024 年 03 月 04 日, 在 PHP 生态内属于活跃度较高的组件。

它主要适用于以下技术方向: 「laravel」 「abr4xas」 「clarity-laravel」 「Microsoft Clarity」 等业务场景。在实际项目中,围绕这些方向常见需要落地的问题包括:接口对接、性能调优、并发安全、与既有框架(Laravel / ThinkPHP / Yii / Webman 等)的兼容适配,以及生产环境的日志埋点与稳定性保障。

我们在过去多个企业项目中使用过 abr4xas/clarity-laravel 或与其功能相近的方案,如果你在选型或落地过程中遇到问题,例如 版本兼容、二次改造、私有化封装、与内部系统对接、生产 BUG 排查,欢迎联系我们协助评估。

围绕 abr4xas/clarity-laravel 我们能提供哪些服务?
定制开发 / 二次开发

基于 abr4xas/clarity-laravel 在你已有业务上做功能扩展、字段裁剪、UI 适配、与内部账号 / 权限 / 日志系统的深度对接。

BUG 修复 & 性能优化

线上偶发问题、内存泄漏、慢查询、并发异常等排查修复;针对高流量场景做缓存、队列、索引层面的调优。

项目外包 & 长期维护

承接完整的项目从需求 → 设计 → 开发 → 上线 → 长期运维;也可按月提供技术保姆服务。

yvsm@zunyunkeji.com QQ:316430983 微信:yvsm316 西安尊云信息科技 · 专注 PHP / Go / 分布式系统研发

统计信息

  • 总下载量: 76.77k
  • 月度下载量: 0
  • 日度下载量: 0
  • 收藏数: 57
  • 点击次数: 8
  • 依赖项目数: 0
  • 推荐数: 0

GitHub 信息

  • Stars: 57
  • Watchers: 1
  • Forks: 2
  • 开发语言: PHP

其他信息

  • 授权协议: MIT
  • 更新时间: 2024-03-04