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

Php Sdk V4 Laravel Package

facebook/php-sdk-v4

Official Facebook Graph SDK for PHP. Authenticate users, obtain access tokens via helpers, and call the Graph API to read/write Facebook data. Composer installable; v5 targets PHP 5.4+ with guidance for upgrading from v4 and Guzzle compatibility notes.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation:

    composer require facebook/graph-sdk
    

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

  2. Basic Initialization:

    $fb = new \Facebook\Facebook([
        'app_id' => env('FACEBOOK_APP_ID'),
        'app_secret' => env('FACEBOOK_APP_SECRET'),
        'default_graph_version' => 'v12.0', // Use latest stable version
    ]);
    
  3. First Use Case: Fetch User Profile

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

Key Entry Points

  • Facebook class: Core service for API calls.
  • Helpers: getRedirectLoginHelper(), getJavaScriptHelper(), etc., for auth flows.
  • File Uploads: fileToUpload(), videoToUpload() for media handling.

Implementation Patterns

1. Authentication Workflows

Server-Side Login (Redirect Flow)

$helper = $fb->getRedirectLoginHelper();
$loginUrl = $helper->getLoginUrl(
    'https://your-app.com/callback',
    ['email', 'public_profile']
);
  • Callback Handling:
    $accessToken = $helper->getAccessToken();
    if ($accessToken) {
        $fb->setDefaultAccessToken($accessToken->getValue());
        $user = $fb->get('/me')->getGraphUser();
    }
    

Client-Side Login (JavaScript SDK)

$helper = $fb->getJavaScriptHelper();
$signedRequest = $helper->getSignedRequest();
if ($signedRequest) {
    $userId = $signedRequest->getUserId();
    // Validate and use $userId
}

2. Data Fetching

Paginated Requests

$response = $fb->get('/me/feed', ['limit' => 10]);
$posts = $response->getGraphEdge();
while (true) {
    $nextUrl = $posts->getNextUrl();
    if (!$nextUrl) break;
    $posts = $fb->get($nextUrl)->getGraphEdge();
}

Batch Requests

$requests = [
    $fb->request('GET', '/me'),
    $fb->request('POST', '/me/feed', ['message' => 'Hello!']),
];
$batchResponse = $fb->sendBatchRequest($requests, '{access-token}');
foreach ($batchResponse as $response) {
    if ($response->getStatusCode() === 200) {
        // Process successful response
    }
}

3. File Uploads

Photos/Videos

// Photo upload
$response = $fb->post('/me/photos', [
    'source' => $fb->fileToUpload('/path/to/photo.jpg'),
    'message' => 'Check this out!'
], '{access-token}');

// Video upload (chunked)
$response = $fb->uploadVideo(
    'me',
    '/path/to/video.mp4',
    ['title' => 'My Video'],
    '{access-token}'
);

4. Page Tab Integration

$pageHelper = $fb->getPageTabHelper();
$signedRequest = $pageHelper->getSignedRequest();
if ($signedRequest) {
    $pageId = $pageHelper->getPageId();
    $isAdmin = $pageHelper->isAdmin();
    // Use $pageId and $isAdmin
}

5. Webhooks

  • Use Facebook\Webhook for handling Facebook webhook events (requires separate setup in Facebook Developer Dashboard).

Gotchas and Tips

Common Pitfalls

  1. Deprecation Warnings:

    • Facebook’s Graph API versions deprecate frequently. Always specify default_graph_version and check Facebook’s API changelog.
    • Example: v2.10 is deprecated; use v12.0 or higher.
  2. Guzzle Version Conflicts:

    • Guzzle 6.x: Requires a custom HTTP client implementation. Use the workaround.
    • Guzzle 7.x: Not officially supported. Downgrade or patch manually.
  3. Access Token Expiry:

    • Short-lived tokens (1 hour) expire quickly. Use the ExchangeToken helper to extend them:
      $longLivedToken = $fb->getDefaultAccessToken()->getValue();
      $accessToken = $fb->getAccessTokenFromShortLivedToken($longLivedToken);
      
  4. Signed Request Validation:

    • Always validate getRawSignedRequest() in production. Malformed requests can crash your app.
    • Test with $signedRequest->make($payload) for debugging.
  5. File Upload Limits:

    • Facebook enforces file size limits. For large files, use chunked uploads (e.g., uploadVideo()).

Debugging Tips

  1. Enable Debug Mode:

    $fb = new \Facebook\Facebook([
        'app_id' => '...',
        'app_secret' => '...',
        'default_graph_version' => 'v12.0',
        'debug' => true, // Logs HTTP requests/responses
    ]);
    
  2. Inspect Raw Responses:

    $response = $fb->get('/me');
    $rawResponse = $response->getRawResponse();
    file_put_contents('debug.json', $rawResponse);
    
  3. Handle Exceptions Gracefully:

    • Catch both FacebookResponseException (API errors) and FacebookSDKException (SDK issues).
    • Log errors with context (e.g., $e->getMessage(), $e->getResponseData()).

Configuration Quirks

  1. Environment Variables:

    • Store app_id, app_secret, and tokens in .env (use env() helper in Laravel):
      'app_id' => env('FACEBOOK_APP_ID'),
      'default_access_token' => env('FACEBOOK_PAGE_ACCESS_TOKEN'),
      
  2. CORS Issues:

    • If using JavaScript SDK, ensure your app’s domain is whitelisted in Facebook Developer Dashboard under Settings > Advanced.
  3. App Secret Proof:

    • For server-side flows, use app_secret_proof to prevent CSRF:
      $helper = $fb->getRedirectLoginHelper();
      $loginUrl = $helper->getLoginUrl('...', ['scope'], true); // Enable proof
      

Extension Points

  1. Custom HTTP Client:

    • Override the default HTTP client for Guzzle 6/7 or custom logging:
      $fb = new \Facebook\Facebook([
          'http_client_handler' => function () {
              return new \GuzzleHttp\Client(['debug' => true]);
          },
      ]);
      
  2. Middleware for API Calls:

    • Extend \Facebook\Facebook to add pre/post-processing:
      class CustomFacebook extends \Facebook\Facebook {
          public function get($path, $accessToken = null) {
              $response = parent::get($path, $accessToken);
              // Add custom logic (e.g., caching)
              return $response;
          }
      }
      
  3. Webhook Verification:

    • Validate webhook signatures manually if using raw webhook URLs:
      $challenge = $_REQUEST['hub_challenge'];
      $signature = $_SERVER['HTTP_X_HUB_SIGNATURE'];
      $expectedSignature = hash_hmac('sha1', $challenge, env('FACEBOOK_WEBHOOK_SECRET'));
      if ($signature !== $expectedSignature) {
          http_response_code(403);
          exit;
      }
      echo $challenge;
      

Performance Tips

  1. Batch Requests:

    • Reduce API calls by batching up to 50 requests (Facebook’s limit).
  2. Caching:

    • Cache frequent requests (e.g., /me) with Laravel’s cache:
      $user = cache()->remember('facebook_user_' . $userId, 3600, function () use ($fb, $userId) {
          return $fb->get("/$userId")->getGraphUser();
      });
      
  3. Async Uploads:

    • Use queues for large file uploads to avoid timeouts:
      dispatch(new UploadFacebookVideo($videoPath, $userId));
      
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.
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
babelqueue/php-sdk
facebook/capi-param-builder-php
babelqueue/symfony
hamzi/corewatch
minionfactory/raw-hydrator
hexters/coinpayment
rjcodes/rjcms
act-training/laravel-permissions-manager
alimarchal/laravel-chart-of-accounts
babenkoivan/elastic-scout-driver