Weave Code
Code Weaver
Helps Laravel developers discover, compare, and choose open-source packages. See popularity, security, maintainers, and scores at a glance to make better decisions.
Feedback
Share your thoughts, report bugs, or suggest improvements.
Subject
Message

Facebook Api Laravel Package

silici0/facebook-api

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Steps

  1. Installation Run composer require silici0/facebook-api:dev-master in your Laravel project. Note: Use dev-master explicitly as the package lacks stable releases.

  2. Publish Configuration Execute php artisan vendor:publish --provider="silici0\FacebookApi\FacebookApiServiceProvider" to generate the config file.

  3. Environment Setup Add your Facebook Pixel ID and Access Token to .env:

    FACEBOOK_PIXEL_ID='your_pixel_id'
    FACEBOOK_ACCESS_TOKEN='your_access_token'
    
  4. 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
    

Implementation Patterns

Core Workflows

  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]);
    
  2. 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);
    
  3. Response Handling Inspect responses for errors or trace IDs:

    $response = FacebookApi::sendCRM($payload);
    if ($response->getMessages()) {
        Log::error('Facebook API Error:', $response->getMessages());
    }
    

Integration Tips

  • Laravel Facade: Prefer FacebookApi::method() over instantiating the class directly for cleaner code.
  • Queue Jobs: Offload CRM syncs to queues (e.g., FacebookCRMSyncJob) to avoid timeouts.
  • Webhook Validation: Combine with Facebook’s webhook system for real-time event validation.

Gotchas and Tips

Pitfalls

  1. 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
        }
    }
    
  2. Deprecated dev-master Avoid production use until a stable release is published. Fork or patch locally if critical.

  3. Hash Collisions Facebook’s deduplication hash must be consistent per user. Use hash('sha256', $user->email) or a deterministic ID.

  4. Missing Error Documentation Response objects lack clear error codes. Log raw responses ($response->getRawResponse()) for debugging.

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

Extension Points

  1. 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");
        }
    }
    
  2. 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 : '';
    }
    
  3. 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);
            }
        }
    }
    
Weaver

How can I help you explore Laravel packages today?

Conversation history is not saved when not logged in.
Prompt
Add packages to context
No packages found.
besmartand-pro/php-quality-config
sentix/ai-chatbot
codifyo/ts-generator-bundle
mintobit/jobqueue
a4sex/maintenance-bundle
a4sex/entity-date-update
a4sex/client-identifier
a4sex/base-utilites
a4sex/key-value-storage
a4sex/micro-status
chilldev/dependency-injection-extra
datinglibre/datinglibre-app-api
biberltd/corebundle
bricre/symfony-bundle-test
biberltd/logbundle
dominium/http-adapter-bundle
dominium/google-analytics
a4sex/auto-clean-entity
christhompsontldr/laravel-inky
spatie/mailcoach-vapor