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

Graph Sdk Laravel Package

facebook/graph-sdk

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation:

    composer require facebook/graph-sdk
    

    Ensure PHP ≥ 5.4 and avoid Guzzle 6.x (use Guzzle 5.x or apply workaround).

  2. Basic Initialization:

    $fb = new \Facebook\Facebook([
        'app_id' => env('FACEBOOK_APP_ID'),
        'app_secret' => env('FACEBOOK_APP_SECRET'),
        'default_graph_version' => 'v13.0', // Use latest stable version
    ]);
    
  3. First Use Case: Fetch a user’s profile (requires a valid access_token):

    try {
        $response = $fb->get('/me', '{access-token}');
        $user = $response->getGraphUser();
        return $user->getName();
    } catch (\Facebook\Exceptions\FacebookResponseException $e) {
        // Graph API error
    } catch (\Facebook\Exceptions\FacebookSDKException $e) {
        // SDK error (e.g., invalid token)
    }
    

Key Entry Points

  • Documentation: Official Docs (includes API reference and examples).
  • Helpers: Pre-built helpers for OAuth flows (getRedirectLoginHelper(), getJavaScriptHelper(), etc.).
  • Graph Nodes: Typed objects for responses (e.g., GraphUser, GraphPage).

Implementation Patterns

1. OAuth Flows

Use helpers for authentication:

// Server-side (Redirect) Flow
$helper = $fb->getRedirectLoginHelper();
$loginUrl = $helper->getLoginUrl(
    'https://your-app.com/callback',
    ['email', 'public_profile']
);

// Handle callback
$accessToken = $helper->getAccessToken();

2. Batch Requests

Execute multiple API calls in parallel:

$batch = new \Facebook\FacebookBatch([
    $fb->request('GET', '/me'),
    $fb->request('GET', '/me/friends'),
]);
$responses = $fb->sendBatch($batch);

3. File Uploads

Upload photos/videos:

$file = new \Facebook\FacebookFile($pathToFile);
$response = $fb->post(
    '/me/photos',
    ['source' => $file],
    '{access-token}'
);

4. Pagination

Handle paginated responses:

$request = $fb->request('GET', '/me/feed');
$response = $fb->send($request);
$paging = $response->getPaging();
$nextUrl = $paging->getNext() ?? null;

5. Webhooks

Validate signed requests (e.g., for Page subscriptions):

$signedRequest = \Facebook\FacebookSignedRequest::parse(
    $_REQUEST['hub_challenge'],
    $_REQUEST['hub_verify_token'],
    env('FACEBOOK_APP_SECRET')
);

6. Custom HTTP Clients

Replace the default client (e.g., for Guzzle 6.x):

$client = new \GuzzleHttp\Client();
$fb->setHttpClient($client);

7. Error Handling

Centralize error responses:

try {
    $response = $fb->get('/protected-endpoint', $token);
} catch (\Facebook\Exceptions\FacebookResponseException $e) {
    $error = $e->getResponseData();
    $errorCode = $e->getErrorCode(); // e.g., 190 (Invalid OAuth token)
}

8. Graph API Versions

Specify per-request or default:

// Default in config
$fb = new \Facebook\Facebook(['default_graph_version' => 'v13.0']);

// Per-request
$response = $fb->get('/me', $token, ['version' => 'v2.12']);

Gotchas and Tips

Pitfalls

  1. Guzzle 6.x Incompatibility:

  2. Deprecated FacebookSession:

    • v5.x removed FacebookSession in favor of AccessToken. Update code to use:
      $accessToken = $fb->getAccessToken();
      
  3. Graph API Versioning:

    • Facebook deprecates versions aggressively. Always use the latest stable version (e.g., v13.0).
    • Check Graph API Changelog for breaking changes.
  4. CSRF in Redirect Flow:

    • Ensure state parameter is validated in callbacks to prevent CSRF:
      $helper->getLoginUrl($redirectUrl, $permissions, ['state' => $csrfState]);
      
  5. Long-Lived Tokens:

    • Short-lived tokens (2h) expire quickly. Exchange for long-lived (60 days) via:
      $longLivedToken = $fb->getLongLivedAccessToken($shortLivedToken);
      
  6. App Secret Proof:

    • Required for server-side auth. Enable in config:
      $fb = new \Facebook\Facebook([
          'app_id' => '...',
          'app_secret' => '...',
          'default_graph_version' => 'v13.0',
          'app_secret_proof' => true, // Default: true in v5+
      ]);
      
  7. Pagination Edge Cases:

    • Use getNext() and getPrevious() on GraphPaging to handle cursors.
    • Deep pagination (e.g., /me/feed?fields=comments) requires nested field queries.
  8. File Uploads:

    • Only application/octet-stream is supported for non-image/video files.
    • For videos, use GraphVideo and specify source:
      $response = $fb->post(
          '/me/videos',
          ['source' => $file, 'title' => 'My Video'],
          $token
      );
      

Debugging Tips

  1. Enable Debug Mode:

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

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

  2. Inspect Raw Responses:

    $response = $fb->get('/me');
    $rawData = $response->getDecodedBody();
    
  3. Test Locally:

    • Use the Graph API Explorer to validate endpoints before coding.
    • Mock responses in tests with FacebookMockHttpClient.
  4. Token Validation:

    • Verify tokens with:
      $tokenMetadata = $fb->get('/debug_token', $token, ['input_token' => $token]);
      

Extension Points

  1. Custom HTTP Clients: Implement FacebookHttpClientInterface for custom logic (e.g., retries, proxies).

  2. Persistent Data: Store tokens/state in a custom PersistentDataInterface:

    $fb->setPersistentDataHandler(new CustomPersistentData());
    
  3. URL Detection: Override URL parsing with UrlDetectionInterface (e.g., for custom domains).

  4. Graph Nodes: Extend GraphNode for custom fields:

    class CustomGraphNode extends \Facebook\GraphNodes\GraphNode {
        public function getCustomField() { ... }
    }
    

Configuration Quirks

  1. Environment Variables: Use Laravel’s .env for credentials:

    FACEBOOK_APP_ID=your_app_id
    FACEBOOK_APP_SECRET=your_secret
    FACEBOOK_DEFAULT_VERSION=v13.0
    
  2. Caching Tokens: Store AccessToken objects in Laravel’s cache:

    cache()->put('facebook_token', $accessToken, now()->addHours(1));
    
  3. Service Provider: Bind the SDK in AppServiceProvider:

    $this->app->singleton('facebook', function ($app) {
        return new \Facebook\Facebook([
            'app_id' => env('FACEBOOK_APP_ID'),
            'app_secret' => env('FACEBOOK_APP_SECRET'),
            'default_graph_version' => env('FACEBOOK_DEFAULT_VERSION'),
        ]);
    });
    

Performance

  1. Batch Requests: Reduce API calls by batching (e.g., fetch user + friends in one request).

  2. Field Expansion: Limit fields to avoid over-fetching:

    $response = $fb->get('/me', $token, ['fields' => 'id,name,email']);
    
  3. **Async Upload

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.
emuniq/filament-browser-notifications
syriable/filament-translator
hungnm28/livewire-form
wenprise/eloquent
crudly/encrypted
fadion/bouncy
cuci/prototurk-sdk
gos/pubsub-router-bundle
cuci/prototurk-sdk-symfony
clementtalleu/easyadmin-markdown-bundle
codeflextech/permission-manager
karnoweb/livewire-datepicker
sayedenam/sayed-dashboard
milito/query-filter
apiboxsym/user-bundle
apiboxsym/health-check-bundle
jayeshmepani/jpl-moshier-ephemeris-php
elnasnato/laraliveui
labrodev/rest-sdk
sampaui/sampaui