combindma/laravel-facebook-pixel
Composer 安装命令:
composer require combindma/laravel-facebook-pixel
包简介
Meta pixel integration for Laravel
README 文档
README
A Complete Meta pixel implementation for your Laravel application.
Table of Contents
- About Combind Agency
- Introduction
- Upgrading to Version 5
- Pre-requisites
- Installation
- Usage - Meta Pixel
- Usage - Conversions API
- Track and Send Together
- Testing
- Contributing
- Security Vulnerabilities
- Credits
- License
About Combind Agency
Combine Agency is a leading web development agency specializing in building innovative and high-performance web applications using modern technologies. Our experienced team of developers, designers, and project managers is dedicated to providing top-notch services tailored to the unique needs of our clients.
If you need assistance with your next project or would like to discuss a custom solution, please feel free to contact us or visit our website for more information about our services. Let's build something amazing together!
Introduction
This package provides a smooth integration of Meta Pixel, along with a straightforward implementation of the latest Conversions API, enhancing your overall experience.
Upgrading to Version 5
If you are upgrading from version 4, please refer to our Version 5 Migration Guide for detailed instructions on how to make a smooth transition.
Pre-requisites
Register a Meta Pixel
To get started with the Meta pixel, you must have a 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.
Obtain Your App Secret
Your App Secret is required to generate a valid appsecret_proof for every Conversions API request. Facebook uses it to generate an appsecret_proof that gets sent with each request for added security, but it's not strictly mandatory for API to work.
You can find it in your Meta App Dashboard → Settings → Basic → App Secret.
Installation
You can install the package via composer:
composer require combindma/laravel-facebook-pixel
Optionally, you can publish the views using:
php artisan vendor:publish --tag="meta-pixel-views"
You can publish the config file with:
php artisan vendor:publish --tag="meta-pixel-config"
This is the contents of the published config file:
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', ''), /* * Your Meta App Secret, required to generate a valid appsecret_proof for the Conversions API. * Found in your Meta App Dashboard under Settings > Basic. */ 'app_secret' => env('META_PIXEL_APP_SECRET'), /* * 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), /* * Enable or disable logging. Useful for debugging. */ 'logging' => env('META_PIXEL_LOGGING', false), /* * This is used to test server events */ 'test_event_code' => env('META_TEST_EVENT_CODE'), ];
If you plan on using the flash-functionality you must register the MetaPixelMiddleware:
Global Middleware:
->withMiddleware(function (Middleware $middleware) { $middleware->append(MetaPixelMiddleware::class); })
Or Assigning Middleware to Routes (recommended if you have admin routes):
Route::group(['middleware' => [MetaPixelMiddleware::class]], static function () { });
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> <x-metapixel-head/> </head> <body> <x-metapixel-body/> </body>
To add an event, use the track() function.
// CheckoutController.php use Combindma\FacebookPixel\Facades\MetaPixel; public function index() { MetaPixel::track('Purchase', ['currency' => 'USD', 'value' => 30.00]); return view('thank-you'); }
This renders:
<html> <head> <script>/* Meta 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 MetaPixel::track('Purchase', ['currency' => 'USD', 'value' => 30.00], '123456'); //Or create a unique id using $eventId = uniqid('ViewContent_', true); MetaPixel::track('ViewContent', [], $eventId);
Calling track() multiple times with the same event name during the same request now preserves every event in the order it was added.
MetaPixel::track('AddToCart', ['value' => 30.00], 'cart-line-1'); MetaPixel::track('AddToCart', ['value' => 45.00], 'cart-line-2');
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 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'); }
After a form submit, the following event will be parsed on the contact page:
<html> <head> <script>/* Meta pixel's base script */</script> <!-- ... --> </head> <body> <script> fbq( 'track', 'Lead', { 'content_name': 'Auto Insurance', 'content_category': 'Quote', 'value': 400.00, 'currency': 'USD' } ); </script> <!-- ... --> </html>
Available Methods
use Combindma\FacebookPixel\Facades\MetaPixel; // Retrieve your Pixel id $id = MetaPixel::pixelId(); // Set Pixel id on the fly MetaPixel::setPixelId('XXXXXXXX'); // Set Pixel token on the fly MetaPixel::setToken('XXXXXXXX'); // Set Pixel testEventCode on the fly MetaPixel::setTestEventCode('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). 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. 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();
Calling flashEvent() multiple times with the same event name during the same request also preserves every event in the order it was added.
Custom Events
You can also track a specific custom event on your website. This feature is not available for flashed events.
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');
This renders:
<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>
Advanced matching
This package enables advanced matching by default. It retrieves the authenticated user's email and ID and includes them in the fbq('init') call.
You can disable it by adding META_PIXEL_ADVANCED_MATCHING_ENABLED=false to your .env file.
<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>
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 MetaPixel is macroable.
use Combindma\FacebookPixel\Facades\MetaPixel; // Include this in your macroable file MetaPixel::macro('purchase', function ($product) { MetaPixel::track('Purchase', [ 'currency' => 'EUR', 'value' => $product->price ]); }); //in your controller MetaPixel::purchase($product);
Usage - Conversions API
If you plan on using Conversions API, you should specify the following in your .env file first:
META_PIXEL_TOKEN=your-access-token META_PIXEL_APP_SECRET=your-app-secret
For every request, you should specify a unique event ID to help deduplicate Meta Pixel and Conversions API events.
This is how you can start:
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([$content]) ->setCurrency('usd') ->setValue(123.45); $eventId = uniqid('prefix_'); //send request MetaPixel::send('Purchase', $eventId ,$custom_data, $user_data);
If you don't specify the $user_data parameter, the package retrieves the email and ID from Auth::user() when the user is authenticated.
It uses the authenticated user ID as the external_id value in both Meta Pixel and Conversions API.
MetaPixel::send('Purchase', $eventId, $custom_data);
Track and Send Together
If you want the package to handle deduplication for you, use trackAndSend(). It tracks the browser event and sends the Conversions API event using the same event ID.
use Combindma\FacebookPixel\Facades\MetaPixel; use FacebookAds\Object\ServerSide\CustomData; $customData = (new CustomData()) ->setCurrency('usd') ->setValue(123.45); MetaPixel::trackAndSend( 'Purchase', ['currency' => 'USD', 'value' => 123.45], $customData, );
If you already have your own event ID, you can still pass it explicitly:
MetaPixel::trackAndSend( 'Purchase', ['currency' => 'USD', 'value' => 123.45], $customData, eventId: 'order-123', );
You can also provide custom UserData when needed:
use FacebookAds\Object\ServerSide\UserData; $userData = (new UserData()) ->setEmail('joe@eg.com'); MetaPixel::trackAndSend( 'Purchase', ['currency' => 'USD', 'value' => 123.45], $customData, userData: $userData, );
If you want to test server events, you need to specify META_TEST_EVENT_CODE in your .env file. By default, this test code will be sent in all API requests.
Do not forget to remove it after you finish your server-side tests.
You can use the Payload Helper to learn more about the requests to send.
Testing
composer test
Contributing
Contributions are welcome. Please open a pull request with tests for any behavior change or bug fix.
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.
combindma/laravel-facebook-pixel 适用场景与选型建议
combindma/laravel-facebook-pixel 是一款 基于 PHP 开发的 Composer 扩展包,目前已累计 81.62k 次下载、GitHub Stars 达 50, 最近一次更新时间为 2021 年 03 月 23 日, 在 PHP 生态内属于活跃度较高的组件。
它主要适用于以下技术方向: 「laravel」 「combindma」 「meta-pixel」 等业务场景。在实际项目中,围绕这些方向常见需要落地的问题包括:接口对接、性能调优、并发安全、与既有框架(Laravel / ThinkPHP / Yii / Webman 等)的兼容适配,以及生产环境的日志埋点与稳定性保障。
我们在过去多个企业项目中使用过 combindma/laravel-facebook-pixel 或与其功能相近的方案,如果你在选型或落地过程中遇到问题,例如 版本兼容、二次改造、私有化封装、与内部系统对接、生产 BUG 排查,欢迎联系我们协助评估。
基于 combindma/laravel-facebook-pixel 在你已有业务上做功能扩展、字段裁剪、UI 适配、与内部账号 / 权限 / 日志系统的深度对接。
线上偶发问题、内存泄漏、慢查询、并发异常等排查修复;针对高流量场景做缓存、队列、索引层面的调优。
承接完整的项目从需求 → 设计 → 开发 → 上线 → 长期运维;也可按月提供技术保姆服务。
与 combindma/laravel-facebook-pixel 相关的其它包
同方向 / 同关键字的高下载量 PHP Composer 包推荐,方便对比选型:
Laravel package to communicate with the CMI payment plateform
A Laravel package for tracking popular entries(by Models) of a website in a certain time
A simple package for tracking user activities on your Laravel website.
Laravel Twillio SMS API Integration
A key-value storage for laravel
Alfabank REST API integration
统计信息
- 总下载量: 81.62k
- 月度下载量: 0
- 日度下载量: 0
- 收藏数: 50
- 点击次数: 27
- 依赖项目数: 0
- 推荐数: 0
其他信息
- 授权协议: MIT
- 更新时间: 2021-03-23