bkfdev/laravel-facebook-pixel

Laravel 的 Facebook Pixel 集成

v1.0.8 2024-01-28 16:46 UTC

This package is auto-updated.

Last update: 2024-09-28 18:16:08 UTC


README

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

为您的 Laravel 应用程序提供完整的 Facebook Pixel 实现。

简介

此包提供了 Meta Pixel 的顺畅集成,以及最新的 Conversions API 的直接实现,增强您的整体体验。

先决条件

注册 Meta Pixel

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

Conversions API

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

获取访问令牌

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

请参阅 Conversions API 指南 了解更多信息。

安装

您可以通过 composer 安装此包

composer require bkfdev/laravel-facebook-pixel

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

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

这是发布配置文件的内容

return [
   /*
     * The Facebook Pixel id, should be a code that looks something like "XXXXXXXXXXXXXXXX".
     */
    'facebook_pixel_id' => env('FACEBOOK_PIXEL_ID', ''),

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

    /*
     * 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('FACEBOOK_PIXEL_TOKEN', ''), //Only if you plan using Conversions API for server events

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

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

如果您计划使用 闪存功能,则必须在 StartSession 中间件之后安装 FacebookPixelMiddleware

// app/Http/Kernel.php
protected $middleware = [
    ...
    \Illuminate\Session\Middleware\StartSession::class,
    \Bkfdev\FacebookPixel\FacebookPixelMiddleware::class,
    ...
];

使用 - Meta Pixel

在 Blade 中包含脚本

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

<!DOCTYPE html>
<html>
    <head>
        @include('facebookpixel::head')
    </head>
    <body>
        @include('facebookpixel::body')
    </body>
</html>

您的活动也将在这里呈现。要添加活动,请使用 track() 函数。

// CheckoutController.php
use Bkfdev\FacebookPixel\Facades\FacebookPixel;

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

这会呈现

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

您还可以为任何活动指定一个唯一的活动 ID,以便在使用转换 API 时避免重复。

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

为下一次请求闪存数据

该包还可以设置在下一个请求上呈现的事件。这在设置内部重定向后的数据时非常有用。

// ContactController.php
use Bkfdev\FacebookPixel\Facades\FacebookPixel;

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

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

<html>
<head>
    <script>/* Facebook 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 Bkfdev\FacebookPixel\Facades\FacebookPixel;

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

自定义事件

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

use Bkfdev\FacebookPixel\Facades\FacebookPixel;

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

这会呈现

<html>
  <head>
    <script>/* Facebook 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,并将其作为 fbq('init') 函数调用的第三个参数包含在 Pixel 基础代码中。

<html>
<head>
    <script>
        /* Facebook 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>

宏化

向页面添加事件可能是一个重复的过程。由于此包不打算对您的事件的外观提出意见,因此 FacebookPixel 可宏化。

use Bkfdev\FacebookPixel\Facades\FacebookPixel;

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

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

使用 - Conversions API

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

对于每个请求,您应该指定一个唯一的活动 ID,以处理像素重复事件和转换 API。

这是您开始的方式

use Bkfdev\FacebookPixel\Facades\FacebookPixel;
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 = FacebookPixel::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
FacebookPixel::send('Purchase', $eventId ,$custom_data, $user_data);

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

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

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

所以,请不要忘记在您完成服务器测试后删除它。

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

测试

composer test

贡献

请查看贡献指南以获取详细信息。

安全漏洞

请查看我们关于如何报告安全漏洞的安全策略

致谢

许可证

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