combindma/laravel-facebook-pixel

为Laravel提供的Meta像素集成

5.0.1 2024-05-17 18:40 UTC

This package is auto-updated.

Last update: 2024-09-17 19:29:35 UTC


README

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

为您的Laravel应用程序提供一个完整的Meta像素实现。

关于Combind Agency

Combine Agency 是一家领先的网页开发公司,专注于使用现代技术构建创新和高性能的网页应用程序。我们的经验丰富的开发人员、设计师和项目经理致力于为客户提供量身定制的高质量服务。

如果您需要帮助您的下一个项目或想讨论定制解决方案,请随时联系我们或访问我们的网站以获取有关我们服务的更多信息。让我们共同打造一些令人惊叹的东西!

简介

此软件包提供了一个顺畅的Meta Pixel集成,以及最新转换API的简单实现,从而增强您的整体体验。

升级到版本5

如果您是从版本4升级,请参阅我们的版本5迁移指南以获取如何平滑过渡的详细说明。

先决条件

注册Meta Pixel

要开始使用Meta像素,您必须注册一个像素: 阅读此指南

转换API

如果您计划使用转换API,则需要

获取访问令牌

要使用转换API,您需要生成一个访问令牌,该令牌将在每个API调用中作为参数传递。

有关更多信息,请参阅转换API指南

安装

您可以通过Composer安装此软件包

composer require combindma/laravel-facebook-pixel

可选,您可以使用以下方式发布视图

php artisan vendor:publish --tag="meta-pixel-views"

您可以使用以下方式发布配置文件

php artisan vendor:publish --tag="meta-pixel-config"

这是已发布配置文件的内容

return [
   /*
     * The Meta pixel id, should be a code that looks something like "1202417153106158".
     */
    'pixel_id' => env('META_PIXEL_ID', ''),

    /*
     * The key under which data is saved to the session with flash.
     */
    'session_key' => env('META_PIXEL_SESSION_KEY', config('app.name').'_metaPixel'),

    /*
     * Only if you plan using Conversions API for server events
     * To use the Conversions API, you need an access token. For Documentation please see: https://developers.facebook.com/docs/marketing-api/conversions-api/get-started
     */
    'token' => env('META_PIXEL_TOKEN', ''),

    /*
     * Enable or disable advanced matching. Useful for adjusting user privacy.
     */
    'advanced_matching_enabled' => env('META_PIXEL_ADVANCED_MATCHING_ENABLED', true),

    /*
     * Enable or disable script rendering. Useful for local development.
     */
    'enabled' => env('META_PIXEL_ENABLED', false),

    /*
     * This is used to test server events
     */
    'test_event_code' => env('META_TEST_EVENT_CODE'),
];

如果您计划使用闪烁功能,您必须注册MetaPixelMiddleware

全局中间件

->withMiddleware(function (Middleware $middleware) {
     $middleware->append(MetaPixelMiddleware::class);
})

或将中间件分配给路由(如果您有管理路由,则推荐使用)

Route::group(['middleware' => [MetaPixelMiddleware::class]], static function () {

});

用法 - Meta像素

在Blade中包含脚本

在打开head标签后插入head视图,在打开body标签后插入body视图

<!DOCTYPE html>
<html>
<head>
    <x-metapixel-head/>
</head>
<body>
    <x-metapixel-body/>
</body>

如果您使用UUID作为用户ID,您应向head组件添加userIdAsString属性

<head>
    <x-metapixel-head :userIdAsString="true"/>
</head>

要添加事件,请使用track()函数。

// CheckoutController.php
use Combindma\FacebookPixel\Facades\MetaPixel;

public function index()
{
    MetaPixel::track('Purchase', ['currency' => 'USD', 'value' => 30.00]);
    return view('thank-you');
}

这将渲染

<html>
  <head>
    <script>/* Meta pixel's base script */</script>
    <!-- ... -->
  </head>
  <body>
  <script>fbq('track', 'Purchase', {"currency":"USD","value":30});</script>
  <!-- ... -->
</html>

您还可以为任何事件指定唯一的event ID,这样,如果您计划使用转换API,就可以避免重复。

//For example your order id
MetaPixel::track('Purchase', ['currency' => 'USD', 'value' => 30.00], '123456');

//Or create a unique id using
$eventId = uniqid('ViewContent_', true);
MetaPixel::track('ViewContent', [], $eventId);

为下一次请求闪烁数据

此软件包还可以设置事件以在下一个请求中渲染。这对于在内部重定向后设置数据很有用。

// ContactController.php
use Combindma\FacebookPixel\Facades\MetaPixel;

public function postContact()
{
    // Do contact form stuff...
    MetaPixel::flashEvent('Lead', [
        'content_name' => 'Auto Insurance',
        'content_category' => 'Quote',
        'value' => 400.00,
        'currency' => 'USD'
    ]);
    return redirect()->action('ContactController@getContact');
}

表单提交后,以下事件将在联系页面解析

<html>
<head>
    <script>/* Meta pixel's base script */</script>
    <!-- ... -->
</head>
<body>
<script>
    fbq(
        'track', 'Lead', {
            'content_name': 'Auto Insurance',
            'content_category': 'Quote',
            'value': 40.00,
            'currency': 'USD'
        }
    );
</script>
<!-- ... -->
</html>

可用方法

use Combindma\FacebookPixel\Facades\MetaPixel;

// Retrieve your Pixel id
$id = MetaPixel::pixelId();
// Set Pixel id on the fly
MetaPixel::setPixelId('XXXXXXXX');
// Check whether script rendering is enabled
$enabled = MetaPixel::isEnabled(); // true|false
// Enable and disable script rendering on the fly
MetaPixel::enable();
MetaPixel::disable();
// Add event to the event layer (automatically renders right before the pixel script). Setting new values merges them with the previous ones.
MetaPixel::track('eventName', ['attribute' => 'value']);
MetaPixel::track('eventName', ['attribute' => 'value'], 'event_id'); //with an event id
MetaPixel::track('eventName'); //without properties 
MetaPixel::track('eventName', [], 'event_id'); //with an event id but without properties
// Flash event for the next request. Setting new values merges them with the previous ones.
MetaPixel::flashEvent('eventName', ['attribute' => 'value']);
MetaPixel::flashEvent('eventName', ['attribute' => 'value'], 'event_id'); //with an event id
MetaPixel::flashEvent('eventName'); //without properties
//Clear the event layer.
MetaPixel::clear();

自定义事件

您还可以跟踪您网站上的特定自定义事件。此功能不适用于闪烁事件。

use Combindma\FacebookPixel\Facades\MetaPixel;

// In your controller
MetaPixel::trackCustom('CUSTOM-EVENT-NAME', ['custom_parameter' => 'ABC', 'value' => 10.00, 'currency' => 'USD']);
//With an event ID
MetaPixel::trackCustom('CUSTOM-EVENT-NAME', ['custom_parameter' => 'ABC', 'value' => 10.00, 'currency' => 'USD'], 'EVENT_ID');

这将渲染

<html>
  <head>
    <script>/* Meta Pixel's base script */</script>
    <!-- ... -->
  </head>
  <body>
  <script>
      fbq('trackCustom', 'CUSTOM-EVENT-NAME', {'custom_parameter': 'ABC', 'value': 10.00, 'currency': 'USD'});
      /* If you specify the event ID */
      fbq('trackCustom', 'CUSTOM-EVENT-NAME', {'custom_parameter': 'ABC', 'value': 10.00, 'currency': 'USD'}, { eventID : 'EVENT_ID' });
  </script>
  <!-- ... -->
</html>

高级匹配

该包默认提供高级匹配功能。我们从认证用户检索电子邮件和用户ID,并将其作为第三个参数包含在Pixel基础代码fbq('init')函数调用中。您可以通过在.env文件中添加META_PIXEL_ADVANCED_MATCHING_ENABLED=false来禁用它

<html>
<head>
    <script>
        /* Meta pixel's base script */
        <!-- ... -->
        fbq('init', '{PixelID}', {
            em: 'email@email.com', //Email provided with Auth::user()->email
            external_id: 12345, //User id provided with Auth::id()
        });
    </script>
    <!-- ... -->
</head>
<body>
<!-- ... -->
</html>

可宏化

向页面添加事件可能是一个重复的过程。由于这个包不应该对您的事件外观提出意见,所以MetaPixel是可宏化的。

use Combindma\FacebookPixel\Facades\MetaPixel;

//include this in your macrobale file
MetaPixel::macro('purchase', function ($product) {
    MetaPixel::track('Purchase', [
        'currency' => 'EUR',
        'value' => $product->price
    ]);
});

//in your controller
MetaPixel::purchase($product);

用法 - 转化API

如果您计划使用转化API功能,您应该在.env文件中首先指定令牌。

对于每个请求,您应该指定一个唯一的事件ID,以处理Pixel重复事件和转化API。

这样您就可以开始了

use Combindma\FacebookPixel\Facades\MetaPixel;
use FacebookAds\Object\ServerSide\Content;
use FacebookAds\Object\ServerSide\CustomData;
use FacebookAds\Object\ServerSide\DeliveryCategory;
use FacebookAds\Object\ServerSide\UserData;

//Prepare User Data first.
// By default, the IP Address, User Agent and fbc/fbp cookies are added.
$user_data = MetaPixel::userData()->setEmail('joe@eg.com')->setPhone('12345678901');

$content = (new Content())
    ->setProductId('product123')
    ->setQuantity(1)
    ->setDeliveryCategory(DeliveryCategory::HOME_DELIVERY);
    
$custom_data = (new CustomData())
    ->setContents(array($content))
    ->setCurrency('usd')
    ->setValue(123.45);
    
$eventId = uniqid('prefix_');
    
//send request
MetaPixel::send('Purchase', $eventId ,$custom_data, $user_data);

如果您没有指定$user_data参数,默认情况下,如果用户已认证,我们将从Auth::user()检索电子邮件和ID。我们使用用户ID作为Meta Pixel和转化API中的相同external_id

MetaPixel::send('Purchase', $eventId, $custom_data);

如果您想测试服务器事件,您需要指定.env文件中的FACEBOOK_TEST_EVENT_CODE。默认情况下,此测试代码将在所有API请求中发送。

所以,测试结束后,别忘了删除。

您可以使用Playload Helper来了解发送请求的更多信息。

测试

composer test

贡献

有关详细信息,请参阅CONTRIBUTING

安全漏洞

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

致谢

许可

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