Server Side Analytics: Facebook/Meta
For this one there is an official package from meta:
composer require facebook/php-business-sdkYou need to obtain the access token from meta so you will be able to authenticate the request you sent to Meta.
A bit more complicate here more parameters to set that are required:
acess_token— from Metapixel_id— the id for the frond end pixelfbc— click id from the ad that was clickedfbp— additional parameter from Meta for more accurate filtering
If you are using Meta Pixel it’s quite easy to obtain the fbc and fbp when an ad is clicked and the URL you’ve provided is reached the Pixel sets two cookies:
_fbc_fbp
If you don’t use Meta Pixel, you can still obtain them from the URL before you sent them to the Conversion API you need to format them properly, for more information on that visit the documentation.
Tip: You can set up the implementation without the
fbcandfbpparameters, but is recommended to sent them along to have a better accuracy.
use FacebookAds\Api;
use FacebookAds\Object\ServerSide\ActionSource;
use FacebookAds\Object\ServerSide\Content;
use FacebookAds\Object\ServerSide\CustomData;
use FacebookAds\Object\ServerSide\Event;
use FacebookAds\Object\ServerSide\EventRequest;
use FacebookAds\Object\ServerSide\UserData;
...
$access_token = config('services.meta.pixel_api_key');
$pixel_id = config('services.meta.pixel_id');
$meta_fbc = $user->meta_click_id;
$meta_fbp = $user->meta_fbp;
Api::init(null, null, $access_token);
$user_data = (new UserData)->setEmail($user->email);
$content = (new Content)
->setProductId($plan)
->setQuantity(1);
$custom_data = (new CustomData)
->setContents([$content])
->setCurrency('USD')
->setValue($amount_paid);
$event = (new Event)
->setEventName($event_name)
->setEventTime(time())
->setUserData($user_data)
->setCustomData($custom_data)
->setActionSource(ActionSource::SYSTEM_GENERATED);
$request = (new EventRequest($pixel_id))
->setEvents([$event]);
$response = $request->execute();Heads up: The
EventResponseclass provides a lot functionalities one of which isvalid()method, DO NOT use it’s hard coded totruedoesn’t matter what will be sent from Meta it will always be through!
And that’s it the events are sent, of course a log or something should be implemented for a future reference but other than that it’s pretty much done.
Conclusion
It’s good to use out of the box packages but always take a peek under the hood you never know what surprise might be hidden there.