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

cwd/facebook-bundle

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation Add the bundle to your Symfony/Laravel project via Composer:

    composer require cwd/facebook-bundle
    

    For Laravel (Symfony-based), register the bundle in config/bundles.php:

    return [
        // ...
        Cwd\FacebookBundle\CwdFacebookBundle::class => ['all' => true],
    ];
    
  2. Configuration Publish the default config:

    php artisan vendor:publish --tag=cwd-facebook-config
    

    Update config/packages/cwd_facebook.yaml with your Facebook App ID, App Secret, and Redirect URI (e.g., http://your-app.test/login/facebook).

  3. First Use Case: Login with Facebook Add the login route to your routes/web.php:

    use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
    use Symfony\Component\Routing\Annotation\Route;
    use Cwd\FacebookBundle\Controller\FacebookController;
    
    Route::get('/login/facebook', [FacebookController::class, 'login']);
    Route::get('/login/facebook/callback', [FacebookController::class, 'callback']);
    

    Use the FacebookAuthenticator service in a controller:

    use Cwd\FacebookBundle\Security\FacebookAuthenticator;
    
    public function loginWithFacebook(FacebookAuthenticator $authenticator)
    {
        $user = $authenticator->getUser();
        // Handle user data (e.g., $user->getId(), $user->getName())
    }
    

Implementation Patterns

Workflows

  1. Authentication Flow

    • Redirect users to Facebook for OAuth:
      return $this->redirect($authenticator->getLoginUrl());
      
    • Handle the callback in your controller:
      $user = $authenticator->authenticate($request);
      $this->authenticateUser($user); // Custom logic (e.g., create/update user in DB)
      
  2. User Data Fetching Fetch basic or extended user data:

    $userData = $authenticator->getUserData(['email', 'first_name', 'last_name']);
    

    For profile pictures or additional fields, use the FacebookClient service:

    $client = $this->container->get('cwd_facebook.client');
    $profile = $client->get('/me?fields=id,name,picture.type(large)');
    
  3. Graph API Integration Use the FacebookClient to interact with the Graph API:

    $client->post('/me/feed', ['message' => 'Hello from Laravel!']);
    

    Handle pagination for large datasets:

    $posts = $client->get('/me/posts', ['limit' => 10]);
    while ($posts->hasNextPage()) {
        $posts = $client->nextPage($posts);
    }
    
  4. Custom User Providers Extend the default user provider to map Facebook data to your Laravel models:

    use Cwd\FacebookBundle\Security\User\FacebookUserProvider;
    
    class CustomFacebookUserProvider extends FacebookUserProvider
    {
        public function loadUserByFacebookId($facebookId)
        {
            return User::where('facebook_id', $facebookId)->first();
        }
    }
    

    Register the provider in config/packages/cwd_facebook.yaml:

    user_provider: App\Service\CustomFacebookUserProvider
    

Integration Tips

  • Laravel-Specific: Use Laravel’s service container to bind the bundle’s services:
    $this->app->bind('cwd_facebook.client', function ($app) {
        return $app->make('cwd_facebook.client');
    });
    
  • Caching API Responses: Cache frequent Graph API calls using Laravel’s cache:
    $cachedData = Cache::remember("facebook_{$userId}_profile", now()->addHours(1), function () use ($client, $userId) {
        return $client->get("/{$userId}");
    });
    
  • Webhook Setup: Configure Facebook App Webhooks in the Facebook Developer Dashboard to handle real-time events (e.g., message or page events). Use Laravel’s Http facade to verify and process webhook signatures:
    use Illuminate\Support\Facades\Http;
    
    public function handleWebhook(Request $request)
    {
        $challenge = $request->input('hub.challenge');
        $signature = $request->input('hub.verify_token');
        $rawBody = file_get_contents('php://input');
    
        if ($this->verifyWebhook($rawBody, $signature)) {
            return response($challenge);
        }
        // Process event
    }
    

Gotchas and Tips

Pitfalls

  1. App Domains and Redirect URIs:

    • Ensure your App Domains in the Facebook Developer Dashboard match your Laravel app’s domains (e.g., localhost, your-app.test, yourdomain.com).
    • Redirect URIs must include the full callback path (e.g., https://your-app.test/login/facebook/callback). Test in "Development Mode" first.
  2. State Parameter:

    • Always include a state parameter in the login URL to prevent CSRF attacks:
      $loginUrl = $authenticator->getLoginUrl(['state' => $request->get('state')]);
      
    • Validate the state parameter in the callback to ensure the request hasn’t been tampered with.
  3. User Data Permissions:

    • Request only the minimum required permissions (e.g., email instead of email, user_birthday, user_friends). Over-scoping can lead to approval issues.
    • Handle cases where users deny permissions gracefully:
      try {
          $user = $authenticator->authenticate($request);
      } catch (\League\OAuth2\Client\Provider\Exception\IdentityProviderException $e) {
          return redirect()->route('home')->with('error', 'Facebook login failed');
      }
      
  4. Token Expiry:

    • Short-lived tokens (e.g., access tokens) expire after ~1 hour. Use the FacebookClient to exchange them for long-lived tokens:
      $longLivedToken = $client->getLongLivedAccessToken();
      
    • Store tokens securely (e.g., in Laravel’s encryption or a dedicated table).
  5. Debugging:

    • Enable debug mode in config/packages/cwd_facebook.yaml:
      debug: true
      
    • Check logs for OAuth errors (e.g., invalid_scope, invalid_redirect_uri). Common issues:
      • invalid_redirect_uri: Mismatch between configured and actual callback URLs.
      • invalid_scope: Requested permissions not configured in Facebook App settings.

Tips

  1. Environment-Specific Config: Use Laravel’s .env to manage Facebook credentials:

    FACEBOOK_APP_ID=your_app_id
    FACEBOOK_APP_SECRET=your_app_secret
    FACEBOOK_REDIRECT_URI=http://your-app.test/login/facebook/callback
    

    Override the bundle’s config in config/packages/cwd_facebook.yaml:

    app_id: '%env(FACEBOOK_APP_ID)%'
    app_secret: '%env(FACEBOOK_APP_SECRET)%'
    redirect_uri: '%env(FACEBOOK_REDIRECT_URI)%'
    
  2. Testing: Use Facebook’s Graph API Explorer to test API calls manually. For Laravel testing, mock the FacebookClient:

    $this->mock(FacebookClient::class, function ($mock) {
        $mock->shouldReceive('get')
             ->with('/me')
             ->andReturn(['id' => '123', 'name' => 'Test User']);
    });
    
  3. Extending the Bundle:

    • Custom Controllers: Override the default FacebookController by binding your own controller to the cwd_facebook.controller service.
    • Custom User Entities: Extend the FacebookUser class to add custom properties:
      class CustomFacebookUser extends FacebookUser
      {
          public function getCustomField()
          {
              return $this->getData()['custom_field'] ?? null;
          }
      }
      
      Update the user_class in config:
      user_class: App\Entity\CustomFacebookUser
      
  4. Performance:

    • Batch API requests for multiple users (e.g., fetching friends’ data):
      $friends = $client->get('/me/friends?fields=id,name');
      $friendIds = array_column($friends->getData(), 'id');
      $batch = $client->createBatch();
      foreach ($friendIds as $id) {
          $batch->add($client->get("/{$id}?fields=email"));
      }
      $results = $client
      
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.
andydefer/laravel-notification
adachsoft/cli-process-tester
jhaskell13/laraflow
sebastienheyd/boilerplate-media-manager
ccast/tagixo-primix
pretendtrue/laravel-builder
sawmainek/laravel-scout-tntsearch-driver
tomshaw/laravel-calendar-table
dibakar/laravel-ownership
steadrun/laravel-monitor
labyrinthe/connect-laravel
elmogy/layan
drewdan/sentinel-client
dskripchenko/laravel-llm
fatryst/nuonuo
stevenay/myanfont
gmostafa/php-graphql-client
xeviant/paystack
snowsoft/faker
meditationsteps/blogetc