bkfdev/laravel-facebook-pixel

Facebook Pixel integration for Laravel

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

This package is auto-updated.

Last update: 2024-10-28 18:32:23 UTC


README

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

A Complete Facebook Pixel implementation for your Laravel application.

Introduction

This package provides a smooth integration of Meta Pixel, along with a straightforward implementation of the latest Conversions API, enhancing your overall experience.

Pre-requisites

Register a Meta Pixel

To get started with the pixel Meta, you must have a Meta pixel registered: Read this guide.

Conversions API

If you plan to use Conversions API then you need to:

Obtain An Access Token

To use the Conversions API, you need to generate an access token, which will be passed as a parameter in every API call.

Refer to Conversions API Guide to learn more.

Installation

You can install the package via composer:

composer require bkfdev/laravel-facebook-pixel

You can publish the config file with:

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

This is the contents of the published config file:

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')
];

If you plan on using the flash-functionality you must install the FacebookPixelMiddleware, after the StartSession middleware:

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

Usage - Meta Pixel

Include scripts in Blade

Insert head view after opening head tag, and body view after opening body tag

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

Your events will also be rendered here. To add an event, use the track() function.

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

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

This renders:

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

You can also specify a unique event ID for any of your events so that, if you plan using the conversions API you avoid duplications.

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

Flashing data for the next request

The package can also set event to render on the next request. This is useful for setting data after an internal redirect.

// 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');
}

After a form submit, the following event will be parsed on the contact page:

<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>

Available Methods

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();

Custom Events

You can also track a specific custom event on your website. This feature is not available for flashed events.

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');

This renders:

<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>

Advanced matching

This package provides by default advanced matching. We retrieve the email and the user id from authenticated user and include it in the Pixel base code fbq('init') function call as a third parameter.

<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>

Macroable

Adding events to pages can become a repetitive process. Since this package isn't supposed to be opinionated on what your events should look like, the FacebookPixel is macroable.

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);

Usage - Conversions API

If you plan on using Conversions API functionalities. Yous should specify the token in your .env file first.

For every request yous should specify a unique event id for handling Pixel Duplicate Events and Conversions API.

This is how you can start:

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);

If you don't specify the $user_data parameter, by default we retrieve the email & the id from Auth::user() if the user is authenticated. We use the user id as a same external_id in Meta Pixel and conversions API

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

If you want to test server events, you need to specify the FACEBOOK_TEST_EVENT_CODE in your .env file. By default, this test code will be sent in all API request.

So Don't forget to delete after you finish your server tests.

You can use the Playload Helper to learn more about the requests to send.

Testing

composer test

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.