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

facebook/php-sdk

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation Add the SDK via Composer (though note this is an archived package; consider alternatives like facebook/graph-sdk):

    composer require facebook/php-sdk:v5.0.0
    
  2. Basic Configuration Initialize the SDK in config/services.php:

    'facebook' => [
        'app_id' => env('FACEBOOK_APP_ID'),
        'app_secret' => env('FACEBOOK_APP_SECRET'),
        'default_graph_version' => 'v12.0',
    ],
    
  3. First Use Case: Login with Facebook In a controller, use the SDK to authenticate:

    use Facebook\Facebook;
    use Facebook\Exceptions\FacebookResponseException;
    use Facebook\Exceptions\FacebookSDKException;
    
    $fb = new Facebook([
        'app_id' => config('facebook.app_id'),
        'app_secret' => config('facebook.app_secret'),
        'default_graph_version' => config('facebook.default_graph_version'),
    ]);
    
    // Redirect user to Facebook for login
    $helper = $fb->getRedirectLoginHelper();
    $loginUrl = $helper->getLoginUrl(config('app.url') . '/callback');
    return redirect()->to($loginUrl);
    

Implementation Patterns

Workflows

  1. OAuth Flow

    • Callback Handling: Process the OAuth callback in a route:
      public function callback()
      {
          $helper = $fb->getRedirectLoginHelper();
          try {
              $accessToken = $helper->getAccessToken();
              $fb->get('/me', $accessToken);
              // Store token and fetch user data
          } catch (FacebookSDKException $e) {
              // Handle errors
          }
      }
      
    • Token Storage: Store the access token in the session or database for future API calls.
  2. API Calls

    • Graph API Requests: Fetch user data or post content:
      $response = $fb->get('/me?fields=name,email', $accessToken);
      $userData = $response->getDecodedBody();
      
    • Uploading Content: Share images or links:
      $data = [
          'message' => 'Check this out!',
          'link' => 'https://example.com',
          'picture' => '@' . realpath('path/to/image.jpg'),
      ];
      $fb->post('/me/feed', $data, $accessToken);
      
  3. Webhooks

    • Use the SDK to verify webhook signatures and process events:
      $challenge = $fb->verifyWebhookSignature(
          file_get_contents('php://input'),
          $_SERVER['HTTP_X_HUB_SIGNATURE'],
          config('facebook.app_secret')
      );
      

Integration Tips

  • Laravel Facade: Create a facade for cleaner syntax:

    // app/Facebook.php
    namespace App;
    use Facebook\Facebook;
    class Facebook extends \Illuminate\Support\Facades\Facade {
        protected static function getFacadeAccessor() { return 'facebook'; }
    }
    

    Register the facade in AppServiceProvider.

  • Middleware: Protect routes requiring Facebook auth:

    public function handle($request, Closure $next)
    {
        if (!$request->session()->has('facebook_token')) {
            return redirect()->route('facebook.login');
        }
        return $next($request);
    }
    
  • Caching Tokens: Use Laravel’s cache to store tokens and reduce API calls:

    $token = cache()->remember('facebook_token', now()->addHours(1), function () {
        return $fb->getLongLivedAccessToken($shortToken);
    });
    

Gotchas and Tips

Pitfalls

  1. Deprecation Warnings

    • The SDK is archived (last update: 2018). Use facebook/graph-sdk for newer features (Graph API v12+).
    • Example: FacebookSession is deprecated; use Facebook\Facebook directly.
  2. Token Expiry

    • Short-lived tokens expire in ~1 hour. Always request a long-lived token:
      $longToken = $fb->getLongLivedAccessToken($shortToken);
      
  3. Graph API Versioning

    • Hardcode the default_graph_version in config to avoid breaking changes. Example:
      'default_graph_version' => 'v12.0', // Use the version you’re testing against
      
  4. Error Handling

    • Always wrap API calls in try-catch blocks:
      try {
          $response = $fb->get('/me', $accessToken);
      } catch (FacebookResponseException $e) {
          // Handle HTTP errors (e.g., 404)
          dd($e->getMessage());
      } catch (FacebookSDKException $e) {
          // Handle SDK errors (e.g., invalid token)
          dd($e->getMessage());
      }
      
  5. CSRF Issues

    • Ensure your callback URL matches the one registered in Facebook Developer Dashboard. Mismatches cause Invalid redirect_uri errors.

Debugging Tips

  • Enable Debug Mode: Add 'debug' => true to the Facebook SDK config to log errors.
  • Inspect Responses: Use dd($response->getGraphNode()->asArray()) to debug API responses.
  • Token Validation: Verify tokens with:
    $fb->getDebugToken($accessToken);
    

Extension Points

  1. Custom Fields

    • Extend the SDK to fetch custom fields by modifying the Graph API query:
      $response = $fb->get('/me?fields=id,name,custom_field', $accessToken);
      
  2. Batch Requests

    • Use the SDK’s batching feature for multiple API calls:
      $batch = new FacebookRequestBatch([
          new FacebookRequest($fb, 'GET', '/me'),
          new FacebookRequest($fb, 'GET', '/me/friends'),
      ]);
      $requests = $batch->requests;
      $fb->sendBatch($requests, $accessToken);
      
  3. Webhook Verification

    • Extend the webhook handler to process specific events (e.g., message or comment):
      $input = file_get_contents('php://input');
      $data = json_decode($input, true);
      if ($data['object'] === 'page') {
          // Handle page events
      }
      
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.
anousss007/vigilance
supportpal/eloquent-model
ardenexal/fhir-models
laravel-at/laravel-image-sanitize
romalytar/yammi-audit-log-laravel
ardenexal/fhir-validation
arshaviras/weather-widget
laravel-chronicle/core
sunchayn/nimbus
daikazu/eloquent-salesforce-objects
unseen-codes/chat
romalytar/yammi-jobs-monitoring-laravel
kisame76/filament-db-table-state
nqxcode/laravel-lucene-search
dpfx/laravel-livewire-wizards
workos/workos-php-laravel
sofa/laravel-global-scope
nawasara/auth-primitives
adhocrat-io/arkhe-main
make-dev/orca-harpoon