Installation
Run composer require silici0/facebook-api:dev-master in your Laravel project.
Note: Use dev-master explicitly as the package lacks stable releases.
Publish Configuration
Execute php artisan vendor:publish --provider="silici0\FacebookApi\FacebookApiServiceProvider" to generate the config file.
Environment Setup
Add your Facebook Pixel ID and Access Token to .env:
FACEBOOK_PIXEL_ID='your_pixel_id'
FACEBOOK_ACCESS_TOKEN='your_access_token'
First Use Case: Test Event Verify connectivity with a test event:
use silici0\FacebookApi\Facades\FacebookApi;
$response = FacebookApi::sendTest('TEST123');
$eventsReceived = $response->getEventsReceived(); // Check if 1
CRM Integration
Use the sendCRM() method to sync user data with Facebook’s CRM API. Structure payloads as associative arrays:
$payload = [
'user' => ['id' => '123', 'email' => 'user@example.com'],
'custom' => ['lead_source' => 'Website'],
'event' => [
'name' => 'Purchase',
'unixtimestamp' => time(),
'id' => hash('sha256', 'user@example.com') // Deduplication hash
]
];
FacebookApi::sendCRM([$payload]);
Event Batch Processing Loop through user arrays for bulk operations:
$users = User::where('is_lead', true)->get();
$payloads = $users->map(fn($user) => [
'user' => ['id' => $user->id, 'email' => $user->email],
'event' => ['name' => 'Lead', 'unixtimestamp' => time(), 'id' => hash('sha256', $user->email)]
])->toArray();
FacebookApi::sendCRM($payloads);
Response Handling Inspect responses for errors or trace IDs:
$response = FacebookApi::sendCRM($payload);
if ($response->getMessages()) {
Log::error('Facebook API Error:', $response->getMessages());
}
FacebookApi::method() over instantiating the class directly for cleaner code.FacebookCRMSyncJob) to avoid timeouts.No Rate Limiting Handling Facebook’s API enforces rate limits (e.g., 500 calls/hour). Implement exponential backoff or queue delays:
try {
FacebookApi::sendCRM($payload);
} catch (\Facebook\Exceptions\FacebookResponseException $e) {
if ($e->getCode() === 429) {
sleep(10); // Retry after delay
}
}
Deprecated dev-master
Avoid production use until a stable release is published. Fork or patch locally if critical.
Hash Collisions
Facebook’s deduplication hash must be consistent per user. Use hash('sha256', $user->email) or a deterministic ID.
Missing Error Documentation
Response objects lack clear error codes. Log raw responses ($response->getRawResponse()) for debugging.
Enable Facebook SDK Debugging
Add to config/facebook.php:
'debug' => env('APP_DEBUG', false),
'graph_version' => 'v18.0',
Validate Tokens Test your access token with:
$tokenInfo = FacebookApi::getTokenInfo();
dd($tokenInfo);
Custom Event Names Extend the class to validate event names against Facebook’s CRM Events:
protected function validateEventName(string $name): void {
$validEvents = ['Purchase', 'Lead', 'AddToCart'];
if (!in_array($name, $validEvents)) {
throw new \InvalidArgumentException("Invalid event name: $name");
}
}
Webhook Verification
Add a verifyWebhook method to validate Facebook’s challenge tokens:
public static function verifyWebhook(string $challenge, string $token): string {
return $token === config('facebook.webhook_token') ? $challenge : '';
}
Retry Logic Implement a retry decorator for transient failures:
public static function withRetry(callable $callback, int $retries = 3): mixed {
for ($i = 0; $i < $retries; $i++) {
try {
return $callback();
} catch (\Exception $e) {
if ($i === $retries - 1) throw $e;
sleep(2 ** $i);
}
}
}
How can I help you explore Laravel packages today?