Installation:
composer require adrienbrault/facebook-client
Ensure guzzlehttp/guzzle is also installed (dependency).
First Use Case: Authenticate and fetch a user's profile:
use Facebook\Facebook;
$fb = new Facebook([
'app_id' => env('FACEBOOK_APP_ID'),
'app_secret' => env('FACEBOOK_APP_SECRET'),
'default_graph_version' => 'v18.0',
]);
$response = $fb->get('/me?fields=id,name,email', ['access_token' => $userToken]);
$userData = $response->getDecodedBody();
Key Files:
vendor/facebook/client/src/Facebook.php (main class)vendor/facebook/client/src/Exceptions/FacebookResponseException.php (error handling)config/facebook.php (if using Laravel config publishing).Authentication:
$helper = $fb->getRedirectLoginHelper();
$permissions = ['email', 'public_profile'];
$loginUrl = $helper->getLoginUrl('https://your-app.com/callback', $permissions);
session() or cache() to store short-lived tokens.API Calls:
$response = $fb->get('/me/feed', ['access_token' => $token]);
$response = $fb->post('/me/feed', ['message' => 'Hello'], ['access_token' => $token]);
$batch = $fb->batch([
['method' => 'GET', 'relative_url' => '/me'],
['method' => 'GET', 'relative_url' => '/me/friends'],
]);
$results = $batch->request(['access_token' => $token]);
Webhooks:
route:web middleware and verify signatures:
$challenge = input('hub.challenge');
$mode = input('hub.mode');
$token = input('hub.verify_token');
$challengeResponse = $fb->verifyWebhook($token, $challenge, $mode);
Pagination:
/me/photos):
$response = $fb->get('/me/photos', ['access_token' => $token, 'limit' => 10]);
$nextUrl = $response->getNextUrl(); // Fetch next page
Uploads:
$response = $fb->post('/me/photos', [
'source' => fopen('path/to/image.jpg', 'r'),
'message' => 'Check this out!',
], ['access_token' => $token]);
Laravel Service Provider: Bind the client to the container for dependency injection:
$this->app->singleton(Facebook::class, function ($app) {
return new Facebook([
'app_id' => config('facebook.app_id'),
'app_secret' => config('facebook.app_secret'),
'default_graph_version' => config('facebook.default_version'),
]);
});
Middleware for Auth: Create middleware to validate Facebook tokens:
public function handle($request, Closure $next) {
$token = $request->bearerToken();
if (!$token || !$this->validateToken($token)) {
abort(401);
}
return $next($request);
}
Rate Limiting:
Implement Laravel's throttle middleware for API calls to avoid hitting Facebook's limits.
Token Expiry:
refreshToken endpoint or implement a token refresh flow:
$response = $fb->post('/oauth/access_token', [
'grant_type' => 'fb_exchange_token',
'client_id' => env('FACEBOOK_APP_ID'),
'client_secret' => env('FACEBOOK_APP_SECRET'),
'fb_exchange_token' => $shortLivedToken,
]);
Graph API Versioning:
default_graph_version (e.g., v18.0). Deprecated versions may break without warning.Error Handling:
400 for invalid parameters). Use try-catch:
try {
$response = $fb->get('/invalid-endpoint');
} catch (FacebookResponseException $e) {
$error = $e->getMessage();
}
Permissions:
https://developers.facebook.com/tools/explorer/ first.Webhook Verification:
Enable Debug Mode:
$fb = new Facebook([...], ['debug' => true]);
Logs HTTP requests/responses to storage/logs/facebook.log.
Inspect Raw Responses:
Use getRawResponse() to debug unexpected data:
$raw = $response->getRawResponse();
Use Postman:
Test endpoints manually in Postman with the same access_token to isolate issues.
Custom HTTP Client: Override the default Guzzle client for logging or retries:
$fb = new Facebook([...], [
'http_client' => new CustomGuzzleClient(),
]);
Event Dispatching:
Extend the client to dispatch Laravel events (e.g., FacebookAuthSuccess) after token validation.
Caching Responses: Cache frequent API calls (e.g., user profiles) with Laravel's cache:
$cacheKey = "fb_user_{$userId}";
return cache()->remember($cacheKey, now()->addHours(1), function () use ($fb, $userId) {
return $fb->get("/$userId");
});
Testing:
Use FacebookMock (from the package) for unit tests:
$fbMock = new FacebookMock();
$fbMock->shouldReceive('get')->andReturn(new FacebookResponse($mockData));
How can I help you explore Laravel packages today?