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 Client Laravel Package

adrienbrault/facebook-client

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation:

    composer require adrienbrault/facebook-client
    

    Ensure guzzlehttp/guzzle is also installed (dependency).

  2. First Use Case: Authenticate and fetch a user's profile:

    use Facebook\Facebook;
    
    $fb = new Facebook([
        'app_id' => env('FACEBOOK_APP_ID'),
        'app_secret' => env('FACEBOOK_APP_SECRET'),
        'default_graph_version' => 'v18.0',
    ]);
    
    $response = $fb->get('/me?fields=id,name,email', ['access_token' => $userToken]);
    $userData = $response->getDecodedBody();
    
  3. Key Files:

    • vendor/facebook/client/src/Facebook.php (main class)
    • vendor/facebook/client/src/Exceptions/FacebookResponseException.php (error handling)
    • config/facebook.php (if using Laravel config publishing).

Implementation Patterns

Common Workflows

  1. Authentication:

    • OAuth2 Flow:
      $helper = $fb->getRedirectLoginHelper();
      $permissions = ['email', 'public_profile'];
      $loginUrl = $helper->getLoginUrl('https://your-app.com/callback', $permissions);
      
    • Token Storage: Use Laravel's session() or cache() to store short-lived tokens.
  2. API Calls:

    • GET Requests:
      $response = $fb->get('/me/feed', ['access_token' => $token]);
      
    • POST Requests (e.g., publishing):
      $response = $fb->post('/me/feed', ['message' => 'Hello'], ['access_token' => $token]);
      
    • Batch Requests (for efficiency):
      $batch = $fb->batch([
          ['method' => 'GET', 'relative_url' => '/me'],
          ['method' => 'GET', 'relative_url' => '/me/friends'],
      ]);
      $results = $batch->request(['access_token' => $token]);
      
  3. Webhooks:

    • Use Laravel's route:web middleware and verify signatures:
      $challenge = input('hub.challenge');
      $mode = input('hub.mode');
      $token = input('hub.verify_token');
      $challengeResponse = $fb->verifyWebhook($token, $challenge, $mode);
      
  4. Pagination:

    • Handle paginated responses (e.g., /me/photos):
      $response = $fb->get('/me/photos', ['access_token' => $token, 'limit' => 10]);
      $nextUrl = $response->getNextUrl(); // Fetch next page
      
  5. Uploads:

    • Stream files directly:
      $response = $fb->post('/me/photos', [
          'source' => fopen('path/to/image.jpg', 'r'),
          'message' => 'Check this out!',
      ], ['access_token' => $token]);
      

Integration Tips

  • Laravel Service Provider: Bind the client to the container for dependency injection:

    $this->app->singleton(Facebook::class, function ($app) {
        return new Facebook([
            'app_id' => config('facebook.app_id'),
            'app_secret' => config('facebook.app_secret'),
            'default_graph_version' => config('facebook.default_version'),
        ]);
    });
    
  • Middleware for Auth: Create middleware to validate Facebook tokens:

    public function handle($request, Closure $next) {
        $token = $request->bearerToken();
        if (!$token || !$this->validateToken($token)) {
            abort(401);
        }
        return $next($request);
    }
    
  • Rate Limiting: Implement Laravel's throttle middleware for API calls to avoid hitting Facebook's limits.


Gotchas and Tips

Pitfalls

  1. Token Expiry:

    • Short-lived tokens (1 hour) expire quickly. Use the refreshToken endpoint or implement a token refresh flow:
      $response = $fb->post('/oauth/access_token', [
          'grant_type' => 'fb_exchange_token',
          'client_id' => env('FACEBOOK_APP_ID'),
          'client_secret' => env('FACEBOOK_APP_SECRET'),
          'fb_exchange_token' => $shortLivedToken,
      ]);
      
  2. Graph API Versioning:

    • Always specify default_graph_version (e.g., v18.0). Deprecated versions may break without warning.
  3. Error Handling:

    • Facebook returns HTTP errors (e.g., 400 for invalid parameters). Use try-catch:
      try {
          $response = $fb->get('/invalid-endpoint');
      } catch (FacebookResponseException $e) {
          $error = $e->getMessage();
      }
      
  4. Permissions:

    • Users must grant permissions explicitly. Test with https://developers.facebook.com/tools/explorer/ first.
  5. Webhook Verification:

    • Always verify webhook challenges on the first request to avoid security issues.

Debugging Tips

  • Enable Debug Mode:

    $fb = new Facebook([...], ['debug' => true]);
    

    Logs HTTP requests/responses to storage/logs/facebook.log.

  • Inspect Raw Responses: Use getRawResponse() to debug unexpected data:

    $raw = $response->getRawResponse();
    
  • Use Postman: Test endpoints manually in Postman with the same access_token to isolate issues.

Extension Points

  1. Custom HTTP Client: Override the default Guzzle client for logging or retries:

    $fb = new Facebook([...], [
        'http_client' => new CustomGuzzleClient(),
    ]);
    
  2. Event Dispatching: Extend the client to dispatch Laravel events (e.g., FacebookAuthSuccess) after token validation.

  3. Caching Responses: Cache frequent API calls (e.g., user profiles) with Laravel's cache:

    $cacheKey = "fb_user_{$userId}";
    return cache()->remember($cacheKey, now()->addHours(1), function () use ($fb, $userId) {
        return $fb->get("/$userId");
    });
    
  4. Testing: Use FacebookMock (from the package) for unit tests:

    $fbMock = new FacebookMock();
    $fbMock->shouldReceive('get')->andReturn(new FacebookResponse($mockData));
    
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