PHPackages                             coversgift/facebook-pixel-capi - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. [API Development](/categories/api)
4. /
5. coversgift/facebook-pixel-capi

ActiveLibrary[API Development](/categories/api)

coversgift/facebook-pixel-capi
==============================

A simple Laravel package to send server-side events to the Facebook Conversions API (CAPI).

v1.1.0(10mo ago)02MITPHPPHP ^8.1

Since Jun 22Pushed 10mo agoCompare

[ Source](https://github.com/sm-jahangir/meta-pixel-capi)[ Packagist](https://packagist.org/packages/coversgift/facebook-pixel-capi)[ RSS](/packages/coversgift-facebook-pixel-capi/feed)WikiDiscussions main Synced 1mo ago

READMEChangelogDependencies (3)Versions (3)Used By (0)

Facebook Conversions API Service for Laravel
============================================

[](#facebook-conversions-api-service-for-laravel)

A simple Laravel package to send server-side events to the Facebook Conversions API (CAPI). This helps in tracking user actions more reliably, especially when browser-based tracking (like the Pixel) is blocked or limited.

Features
--------

[](#features)

- Easy-to-use Facade for sending events.
- Handles hashing of user data (`phone`, `userID`).
- Configurable via `.env` file.
- Supports test events for debugging.

1. Installation
---------------

[](#1-installation)

Since this is a local package, it's already integrated into your project. If it were a standard Composer package, you would run:

```
composer require codersgift/facebook-pixel-service
```

2. Configuration
----------------

[](#2-configuration)

### a. Register Service Provider and Facade

[](#a-register-service-provider-and-facade)

The package's Service Provider and Facade must be registered in your `config/app.php` file. Your project already has this configured.

**`config/app.php`**

```
'providers' => [
    // ...
    Codersgift\FacebookPixelService\Providers\FacebookPixelServiceProvider::class,
],

'aliases' => Facade::defaultAliases()->merge([
    // ...
    'FacebookPixel' => Codersgift\FacebookPixelService\Facades\FacebookPixel::class,
])->toArray(),
```

### b. Publish Configuration File

[](#b-publish-configuration-file)

To customize the configuration, publish the config file using the following Artisan command:

```
php artisan vendor:publish --provider="Codersgift\FacebookPixelService\Providers\FacebookPixelServiceProvider" --tag="config"
```

This command will create a `config/facebookpixel.php` file in your project, allowing you to manage settings centrally.

### c. Set Environment Variables

[](#c-set-environment-variables)

Add the following keys to your `.env` file with your Facebook App credentials.

```
FACEBOOK_PIXEL_ID=your_pixel_id
FACEBOOK_ACCESS_TOKEN=your_long_lived_access_token
FACEBOOK_TEST_EVENT_CODE=your_test_event_code_for_debugging
```

- `FACEBOOK_PIXEL_ID`: Your Facebook Pixel ID.
- `FACEBOOK_ACCESS_TOKEN`: A server-side access token generated from your Business Manager.
- `FACEBOOK_TEST_EVENT_CODE`: (Optional) Use this to test events in the Events Manager without affecting your production data. The package automatically uses this when `APP_ENV` is not `production`.

3. Usage
--------

[](#3-usage)

The primary way to use the service is through the `FacebookPixel` facade.

### a. Capturing the `_fbp` Cookie (Frontend)

[](#a-capturing-the-_fbp-cookie-frontend)

For accurate event matching and deduplication, it's crucial to send the `_fbp` (Facebook browser ID) cookie value with your server-side events. This value is created by the Facebook Pixel script on the user's browser.

You can capture it by adding a hidden input field to your forms and using a small JavaScript snippet to populate it.

**1. Add a hidden input to your form:**

```

    @csrf

```

**2. Add the following JavaScript to your page:**

This script will find the `_fbp` cookie and set its value to the hidden input field.

```

    document.addEventListener('DOMContentLoaded', function() {
        var fbpValue = null;
        if (document.cookie) {
            var cookies = document.cookie.split('; ');
            cookies.forEach(function(cookie) {
                if (cookie.startsWith('_fbp=')) {
                    fbpValue = cookie.split('=')[1];
                }
            });
        }
        if (fbpValue) {
            document.getElementById('fbp').value = fbpValue;
        }
    });

```

Now, when the form is submitted, the `fbp` value will be available in your controller via `$request->fbp`.

### b. Sending an Event (Backend)

[](#b-sending-an-event-backend)

To send an event, call the `sendPixelEvent` method with an array of event data.

```
use Codersgift\FacebookPixelService\Facades\FacebookPixel;

// ... inside a controller method

$eventId = uniqid();
$eventTime = time();

$eventData = [
    'event_name' => 'Purchase',
    'event_time' => $eventTime,
    'event_id' => $eventId, // ✅ Use same variable
    'fbp' => $request->fbp,

    'userID' => (string) $new_user->id,
    'phone' => $order->mobile,
    'email' => $order->email,
    'order_id' => (string) $order->id,
    'value' => $order->total,
    'currency' => 'BDT',
    'client_ip_address' => getRealIP(),
    'client_user_agent' => $agent->getUserAgent(),
    'content_ids' => $order->orderItems->pluck('product_id')->map(fn ($id) => (string) $id)->toArray(),
    'content_type' => 'product',
];

$response = FacebookPixel::sendPixelEvent($eventData);
```

### Event Data Parameters

[](#event-data-parameters)

The `$eventData` array should contain the following keys:

KeyRequiredDescription`event_name`YesThe type of event (e.g., `Purchase`, `AddToCart`, `ViewContent`).`event_time`YesUnix timestamp of when the event occurred.`event_id`YesA unique ID for this specific event. **Required for deduplication.**`userID`YesThe unique ID of the logged-in user in your system. Will be hashed.`phone`YesThe user's phone number. Will be hashed.`fbp`YesThe `_fbp` cookie from the user's browser. Helps with matching.`client_ip_address`YesThe user's IP address.`client_user_agent`YesThe user's browser user agent string.`value`YesThe monetary value of the event (e.g., total order price).`currency`YesThe currency code (e.g., `BDT`, `USD`).`content_ids`YesAn array of product IDs associated with the event.`content_type`YesThe type of content (usually `product` or `product_group`).`order_id`YesThe unique ID for the order.`email`NoThe user's email address. The service will hash it if provided.4. Example: Tracking a Purchase Event
-------------------------------------

[](#4-example-tracking-a-purchase-event)

This example shows how to track a purchase event from a controller and ensure it's deduplicated with the browser-side Pixel event.

### Controller (`OrderController.php`)

[](#controller-ordercontrollerphp)

This is a simplified version of your `placeOrder` method, highlighting the CAPI integration steps.

```
