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

developernaren/facebook

Laravel package for posting to Facebook via a singleton FB service. Chain methods to build a status, add links, post as a page, then publish. Early-stage and built for personal use; more features planned.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation

    composer require developernaren/facebook
    

    Publish the config file:

    php artisan vendor:publish --provider="DeveloperNaren\Facebook\FacebookServiceProvider"
    
  2. Configuration Edit .env with your Facebook App credentials:

    FACEBOOK_APP_ID=your_app_id
    FACEBOOK_APP_SECRET=your_app_secret
    FACEBOOK_PAGE_ACCESS_TOKEN=your_page_token
    
  3. First Use Case Post a simple text update to a Facebook Page:

    use DeveloperNaren\Facebook\Facades\Facebook;
    
    $response = Facebook::post('/me/feed', [
        'message' => 'Hello, Facebook! This is my first post via Laravel.'
    ]);
    
    dd($response);
    
  4. Key Files to Review

    • config/facebook.php (default settings)
    • app/Providers/FacebookServiceProvider.php (service binding)
    • app/Facades/Facebook.php (facade usage)

Implementation Patterns

Common Workflows

1. Posting Content

  • Text Post
    Facebook::post('/me/feed', ['message' => 'Your message']);
    
  • Image/Video Upload
    $file = file_get_contents('path/to/image.jpg');
    $response = Facebook::post('/me/photos', [
        'source' => $file,
        'message' => 'Check out this image!'
    ]);
    
  • Link Sharing
    Facebook::post('/me/feed', [
        'link' => 'https://example.com',
        'message' => 'Check this out!'
    ]);
    

2. Fetching Data

  • Get Page Posts
    $posts = Facebook::get('/me/feed', [
        'limit' => 5,
        'fields' => 'message,created_time'
    ]);
    
  • Get User Profile
    $profile = Facebook::get('/me', ['fields' => 'name,email']);
    

3. Handling Responses

  • Check for Errors
    $response = Facebook::post('/me/feed', ['message' => 'Test']);
    if ($response->hasError()) {
        dd($response->getError());
    }
    
  • Extract Data
    $postId = $response->getData()['id'];
    

4. Batch Requests

$batch = [
    ['method' => 'POST', 'relative_url' => '/me/feed', 'body' => ['message' => 'Post 1']],
    ['method' => 'POST', 'relative_url' => '/me/feed', 'body' => ['message' => 'Post 2']],
];
$results = Facebook::batch($batch);

5. Integration with Laravel Jobs

use DeveloperNaren\Facebook\Facades\Facebook;

class PostToFacebookJob implements ShouldQueue
{
    public function handle()
    {
        Facebook::post('/me/feed', [
            'message' => 'Scheduled post from Laravel!'
        ]);
    }
}

6. Using Webhooks

  • Configure webhook in Facebook Developer Portal.
  • Handle incoming requests in Laravel:
    Route::post('/facebook/webhook', function (Request $request) {
        $hubVerifyToken = config('facebook.hub_verify_token');
        $challenge = $request->input('hub.challenge');
        $token = $request->input('hub.verify_token');
    
        if ($token === $hubVerifyToken) {
            return response()->json($challenge);
        }
    
        // Handle webhook events
        $data = $request->all();
        // Process $data (e.g., page_subscriptions, messages)
    });
    

Integration Tips

1. Laravel Service Container

Bind custom configurations:

$this->app->singleton('facebook', function ($app) {
    return Facebook::with([
        'default_graph_version' => 'v18.0',
        'http_client' => $app->make(HttpClient::class),
    ]);
});

2. Logging

Enable debug mode in config/facebook.php:

'debug' => env('FACEBOOK_DEBUG', false),

Log responses for debugging:

Facebook::withDebug(true)->post('/me/feed', ['message' => 'Test']);

3. Testing

Use mocking in PHPUnit:

$this->mock(Facebook::class)->shouldReceive('post')->andReturn($mockResponse);

4. Caching Tokens

Store and rotate tokens securely:

$token = cache()->remember('facebook_page_token', now()->addDays(30), function () {
    return Facebook::get('/oauth/access_token', [
        'grant_type' => 'fb_exchange_token',
        'client_id' => config('facebook.app_id'),
        'client_secret' => config('facebook.app_secret'),
        'fb_exchange_token' => session('fb_exchange_token'),
    ])->getData()['access_token'];
});

Gotchas and Tips

Pitfalls

1. Token Expiry

  • Facebook access tokens expire. Handle token refresh gracefully:
    try {
        $response = Facebook::get('/me');
    } catch (\DeveloperNaren\Facebook\Exceptions\OAuthException $e) {
        if ($e->getCode() === 190) { // Token expired
            $newToken = refreshFacebookToken();
            config(['facebook.page_access_token' => $newToken]);
            return Facebook::get('/me');
        }
        throw $e;
    }
    

2. Rate Limiting

  • Facebook enforces rate limits (e.g., 200 calls/hour for Graph API).
  • Implement retry logic with exponential backoff:
    use Symfony\Component\HttpClient\Retry\RetryStrategy;
    
    $client = HttpClient::create([
        'base_uri' => 'https://graph.facebook.com/',
        'auth_bearer' => config('facebook.page_access_token'),
        'retry' => RetryStrategy::fromOptions([
            'max_retries' => 3,
            'delay' => 1000,
            'multiplier' => 2,
            'max_delay' => null,
            'statusCodes' => [429, 500, 502, 503, 504],
        ]),
    ]);
    

3. Deprecated API Versions

4. Permissions

  • Ensure your app has the required permissions (e.g., pages_manage_posts, pages_read_engagement).
  • Test in Developer Mode before going live.

5. File Uploads

  • Large files may fail. Use multipart/form-data and chunk uploads if needed:
    $file = fopen('large_file.zip', 'r');
    $response = Facebook::post('/me/videos', [
        'source' => $file,
        'description' => 'Large file upload',
    ], [
        'headers' => ['Content-Type' => 'multipart/form-data'],
    ]);
    

Debugging Tips

1. Enable Debug Mode

Facebook::withDebug(true)->post('/me/feed', ['message' => 'Test']);

Check Laravel logs for raw responses.

2. Inspect Raw Responses

$response = Facebook::post('/me/feed', ['message' => 'Test']);
dd($response->getRawContent()); // Raw JSON response

3. Validate Input

  • Use Facebook's Graph API Explorer to test endpoints before coding.
  • Validate required fields for each endpoint (e.g., message or link for posts).

4. Common Errors

  • Error 100: Invalid parameter (check field names/values).
  • Error 190: Token expired (refresh token).
  • Error 4: Permission denied (check app permissions).
  • Error 10: Missing required field (e.g., access_token).

Extension Points

1. Custom HTTP Client

Extend the default HTTP client for additional features:

$client = HttpClient::create([
    'base_uri' => 'https://graph.facebook.com/',
    'auth_bearer' => config('facebook.page_access_token'),
    'headers' => [
        'User-Agent' => 'MyLaravelApp/1.0',
    ],
    'event_dispatcher' => $this->app->
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.
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
mkwebdesign/filament-watchdog-v5
renatomarinho/laravel-page-speed
zedmagdy/filament-business-hours
renatovdemoura/blade-elements-ui
devgeek/beacon-admin
benjamin-rqt/data-watcher-bundle