jerry4rahul / facebook-graph-sdk
A modern, comprehensive PHP SDK for the Facebook Graph API with enhanced error handling, pagination support, rate limiting, and extensive API coverage.
Fund package maintenance!
jerry4rahul
Requires
- php: >=8.0
- ext-curl: *
- ext-json: *
- ext-mbstring: *
- guzzlehttp/guzzle: ^7.2
- psr/log: ^1.1|^2.0|^3.0
Requires (Dev)
- friendsofphp/php-cs-fixer: ^3.0
- phpstan/phpstan: ^1.0
- phpunit/phpunit: ^9.0|^10.0
- squizlabs/php_codesniffer: ^3.6
This package is auto-updated.
Last update: 2025-08-15 19:54:55 UTC
README
A modern, comprehensive PHP SDK for the Facebook Graph API with enhanced error handling, pagination support, rate limiting, and extensive API coverage. Compatible with Graph API v18.0-v23.0+ and PHP 8.0+.
Note: This SDK supports Facebook Graph API v18.0-v23.0+ and requires PHP 8.0 or higher for optimal performance and type safety.
Features
- 🚀 Complete Graph API Coverage: Support for posts, pages, comments, reactions, events, groups, albums, photos, videos, stories, and more
- 🛡️ Enhanced Error Handling: Detailed error codes and messages with custom exception types and retry mechanisms
- 📄 Advanced Pagination: Automatic cursor-based pagination with field selection and bulk data retrieval
- ✅ Input Validation: Comprehensive validation for all API parameters with security checks
- 🔒 Type Safety: Full PHP 8+ type hints, strict typing, and modern PHP features
- 📊 PSR-3 Logging: Built-in logging support for debugging, monitoring, and audit trails
- ⚡ Rate Limiting: Automatic rate limit tracking, handling, and usage monitoring
- 📦 Batch Requests: Support for Facebook's batch API with optimized request handling
- 📱 Story Support: Upload photo stories and video stories to Facebook pages
- 🔄 Binary Uploads: Direct binary file uploads with progress tracking
- 🔐 OAuth 2.0: Complete OAuth flow implementation with token management
- 🎯 Field Selection: Granular field selection for optimized API responses
- 🔄 Auto Retry: Intelligent retry mechanism for failed requests
- 📈 Analytics: Built-in insights and analytics data retrieval
Table of Contents
- Installation
- Quick Start
- Usage Examples
- Error Handling
- Authentication
- Configuration
- Rate Limiting
- Best Practices
- Requirements
- Contributing
- License
Installation
Via Composer (Recommended)
composer require jerry4rahul/facebook-graph-sdk
Via Packagist
Visit Packagist for more installation options.
Manual Installation
- Download the latest release from GitHub
- Extract the files to your project directory
- Include the autoloader:
require_once 'path/to/facebook-graph-sdk/vendor/autoload.php';
Quick Start
Basic Setup
<?php require_once 'vendor/autoload.php'; use Jerry4rahul\FacebookGraphSdk\Facebook; use Jerry4rahul\FacebookGraphSdk\FacebookException; // Method 1: Direct configuration $facebook = new Facebook([ 'app_id' => 'your-app-id', 'app_secret' => 'your-app-secret', 'default_graph_version' => 'v18.0', // Optional, defaults to v18.0 'default_access_token' => 'your-access-token', // Optional 'timeout' => 30, // Optional, defaults to 30 seconds 'max_retry_attempts' => 3, // Optional, defaults to 3 ]);
Environment Variables (Recommended)
// Set environment variables $_ENV['FACEBOOK_APP_ID'] = 'your-app-id'; $_ENV['FACEBOOK_APP_SECRET'] = 'your-app-secret'; // Initialize from environment $facebook = new Facebook(); // Set access token later $facebook->setDefaultAccessToken('your-access-token');
With Custom Logger
use Monolog\Logger; use Monolog\Handler\StreamHandler; $logger = new Logger('facebook-sdk'); $logger->pushHandler(new StreamHandler('facebook.log', Logger::DEBUG)); $facebook = new Facebook([ 'app_id' => 'your-app-id', 'app_secret' => 'your-app-secret', 'logger' => $logger, ]);
Usage Examples
User Information
try { // Get current user info $user = $facebook->me(['id', 'name', 'email']); echo "Hello, " . $user['name']; // Get user with custom fields $userDetails = $facebook->me([], null, ['id', 'name', 'email', 'picture']); } catch (FacebookException $e) { echo "Error: " . $e->getMessage(); }
Pages Management
// Get user's pages with pagination $pages = $facebook->pages('me', [], ['id', 'name', 'access_token'], 10); // Get all pages (automatic pagination) $allPages = $facebook->getAllPages('me/accounts', ['fields' => 'id,name,access_token']); foreach ($allPages['data'] as $page) { echo "Page: " . $page['name'] . "\n"; }
Posts and Content
// Create a post $postData = [ 'message' => 'Hello from PHP SDK!', 'link' => 'https://example.com' ]; $result = $facebook->createPost('page-id', $postData); echo "Post created with ID: " . $result['id']; // Get posts with pagination $posts = $facebook->posts('page-id', [], ['id', 'message', 'created_time'], 25); // Update a post $facebook->updatePost('post-id', ['message' => 'Updated message']); // Delete a post $facebook->deletePost('post-id');
Story Uploads
// Upload photo story to Facebook page $photoStoryData = [ 'source' => new CURLFile('/path/to/photo.jpg', 'image/jpeg'), 'caption' => 'Check out this amazing photo story!' ]; $photoStory = $facebook->uploadPhotoStory('page-id', $photoStoryData); echo "Photo story uploaded with ID: " . $photoStory['id']; // Upload video story to Facebook page $videoStoryData = [ 'source' => new CURLFile('/path/to/video.mp4', 'video/mp4'), 'title' => 'My Video Story', 'description' => 'An exciting video story!' ]; $videoStory = $facebook->uploadVideoStory('page-id', $videoStoryData); echo "Video story uploaded with ID: " . $videoStory['id']; // Upload story with binary data $binaryData = file_get_contents('/path/to/media.jpg'); $storyResult = $facebook->postBinary('upload:page-id/photo_stories', $binaryData, [ 'Content-Type' => 'image/jpeg' ]);
Comments and Interactions
// Get comments on a post $comments = $facebook->comments('post-id', [], ['id', 'message', 'from'], 50); // Add a comment $facebook->comment('post-id', 'Great post!'); // Get likes $likes = $facebook->likes('post-id', [], ['id', 'name']); // Like a post $facebook->like('post-id'); // Unlike a post $facebook->unlike('post-id');
Media Upload
// Upload photo $photoData = [ 'message' => 'Check out this photo!' ]; $result = $facebook->uploadMedia('page-id', '/path/to/photo.jpg', $photoData); echo "Photo uploaded with ID: " . $result['id'];
Events
// Get user's events $events = $facebook->events('me', [], ['id', 'name', 'start_time'], 20); // Create an event $eventData = [ 'name' => 'My Event', 'start_time' => '2024-12-31T20:00:00+0000', 'description' => 'New Year Party' ]; $event = $facebook->createEvent('page-id', $eventData);
Groups
// Get user's groups $groups = $facebook->groups('me', [], ['id', 'name', 'privacy']); // Get group feed $groupFeed = $facebook->groupFeed('group-id', [], ['id', 'message', 'from']); // Post to group $facebook->postToGroup('group-id', ['message' => 'Hello group!']);
Albums and Photos
// Get user's albums $albums = $facebook->albums('me', [], ['id', 'name', 'count']); // Create an album $albumData = [ 'name' => 'My Album', 'description' => 'Photos from my trip' ]; $album = $facebook->createAlbum('page-id', $albumData); // Get photos from album $photos = $facebook->albumPhotos('album-id', [], ['id', 'source', 'created_time']); // Upload photo to album $facebook->uploadPhoto('album-id', '/path/to/photo.jpg', ['message' => 'Great shot!']);
Videos
// Get user's videos $videos = $facebook->videos('me', [], ['id', 'title', 'source']); // Upload video $videoData = [ 'title' => 'My Video', 'description' => 'Check out this video!' ]; $video = $facebook->uploadVideo('page-id', '/path/to/video.mp4', $videoData); // Create live video $liveVideoData = [ 'title' => 'Live Stream', 'description' => 'Going live now!' ]; $liveVideo = $facebook->createLiveVideo('page-id', $liveVideoData);
Insights and Analytics
// Get page insights $insights = $facebook->insights('page-id', [ 'metric' => 'page_impressions,page_reach', 'period' => 'day', 'since' => '2024-01-01', 'until' => '2024-01-31' ]); // Get post insights $postInsights = $facebook->insights('post-id', [ 'metric' => 'post_impressions,post_clicks' ]);
Batch Requests
// Execute multiple requests in a single batch $batchRequests = [ [ 'method' => 'GET', 'relative_url' => 'me?fields=id,name' ], [ 'method' => 'GET', 'relative_url' => 'me/posts?limit=5' ], [ 'method' => 'POST', 'relative_url' => 'me/feed', 'body' => 'message=Hello from batch request!' ] ]; $batchResults = $facebook->batch($batchRequests); foreach ($batchResults as $result) { if ($result['code'] == 200) { $data = json_decode($result['body'], true); // Process successful response } }
Pagination
// Manual pagination with cursor $posts = $facebook->posts('page-id', [], ['id', 'message'], 10); if (isset($posts['paging']['next'])) { // Get next page using cursor $nextCursor = $posts['paging']['cursors']['after']; $nextPosts = $facebook->posts('page-id', [], ['id', 'message'], 10, $nextCursor); } // Automatic pagination (get all results) $allPosts = $facebook->getAllPages('page-id/posts', [ 'fields' => 'id,message,created_time' ], null, 5); // Max 5 pages echo "Total posts: " . $allPosts['total_items']; echo "Total pages: " . $allPosts['total_pages'];
Error Handling
use Jerry4rahul\FacebookGraphSdk\Exceptions\FacebookException; try { $result = $facebook->get('invalid-endpoint'); } catch (FacebookException $e) { echo "Error Type: " . $e->getErrorType() . "\n"; echo "Error Code: " . $e->getErrorCode() . "\n"; echo "Error Subcode: " . $e->getErrorSubcode() . "\n"; echo "Message: " . $e->getMessage() . "\n"; echo "User Message: " . $e->getErrorUserMessage() . "\n"; // Check for specific error types if ($e->isAuthenticationError()) { // Handle authentication errors echo "Please check your access token"; } elseif ($e->isValidationError()) { // Handle validation errors echo "Please check your input parameters"; } elseif ($e->isRateLimitError()) { // Handle rate limiting echo "Rate limit exceeded, please try again later"; } }
Authentication
OAuth 2.0 Flow
use Jerry4rahul\FacebookGraphSdk\OAuth2Client; $oAuth2Client = $facebook->getOAuth2Client(); // Step 1: Get login URL $loginUrl = $oAuth2Client->getAuthorizationUrl([ 'scope' => 'pages_manage_posts,pages_read_engagement' ]); echo "<a href='$loginUrl'>Login with Facebook</a>"; // Step 2: Exchange code for access token (in callback) if (isset($_GET['code'])) { try { $accessToken = $oAuth2Client->getAccessTokenFromCode($_GET['code']); $facebook->setDefaultAccessToken($accessToken['access_token']); // Get long-lived token $longLivedToken = $facebook->getLongLivedAccessToken($accessToken['access_token']); } catch (FacebookException $e) { echo "Authentication failed: " . $e->getMessage(); } }
Token Validation
// Validate token expiry if (!$facebook->validateTokenExpiry()) { echo "Access token has expired"; // Redirect to login or refresh token } // Validate specific token if (!$facebook->validateTokenExpiry('specific-access-token')) { echo "Token is invalid or expired"; }
Configuration
Custom HTTP Client Options
$facebook = new Facebook($app, [ 'timeout' => 30, 'max_retry_attempts' => 3, 'graph_version' => 'v18.0' ]);
Logging
use Monolog\Logger; use Monolog\Handler\StreamHandler; // Create logger $logger = new Logger('facebook-sdk'); $logger->pushHandler(new StreamHandler('facebook.log', Logger::DEBUG)); // Set logger $facebook->setLogger($logger);
Rate Limiting
// Check rate limit usage $rateLimitUsage = $facebook->getRateLimitUsage(); if (isset($rateLimitUsage['x-app-usage'])) { $usage = json_decode($rateLimitUsage['x-app-usage'], true); echo "API calls used: " . $usage['call_count'] . "%"; echo "CPU time used: " . $usage['cpu_time'] . "%"; }
Best Practices
- Always use try-catch blocks when making API calls
- Validate input parameters before sending requests
- Use field selection to minimize data transfer
- Implement proper pagination for large datasets
- Handle rate limiting gracefully
- Store long-lived tokens securely
- Use batch requests for multiple operations
- Enable logging for debugging
Requirements
System Requirements
- PHP: 8.0 or higher
- Extensions:
ext-curl
- For HTTP requestsext-json
- For JSON parsingext-mbstring
- For string manipulation
- Dependencies:
guzzlehttp/guzzle
^7.2 - HTTP client librarypsr/log
- PSR-3 logging interface
Supported Facebook Graph API Versions
- v23.0
- v22.0
- v21.0
- v20.0
- v19.0
- v18.0 (Default)
Supported PHP Versions
PHP Version | Support Status |
---|---|
8.3 | ✅ Fully Supported |
8.2 | ✅ Fully Supported |
8.1 | ✅ Fully Supported |
8.0 | ✅ Fully Supported |
7.4 | ❌ Not Supported |
Security
Reporting Security Vulnerabilities
If you discover a security vulnerability, please send an email to jerry.rahul2@gmail.com. All security vulnerabilities will be promptly addressed.
Security Best Practices
- Always validate and sanitize user input
- Store access tokens securely (encrypted)
- Use HTTPS for all API communications
- Implement proper rate limiting
- Regularly rotate access tokens
- Monitor API usage for suspicious activity
Changelog
See CHANGELOG.md for a detailed list of changes and version history.
License
This project is licensed under the MIT License - see the LICENSE file for details.
Contributing
We welcome contributions! Please see CONTRIBUTING.md for details on:
- How to submit bug reports
- How to suggest new features
- Development setup
- Coding standards
- Pull request process
Development Setup
# Clone the repository git clone https://github.com/jerry4rahul/facebook-graph-sdk.git cd facebook-graph-sdk # Install dependencies composer install # Run tests composer test # Run code style checks composer cs-check
Support
Getting Help
- 📖 Documentation: Read this README and inline code documentation
- 🐛 Bug Reports: GitHub Issues
- 💡 Feature Requests: GitHub Issues
- 💬 Discussions: GitHub Discussions
Commercial Support
For commercial support, custom development, or consulting services, please contact jerry.rahul2@gmail.com.
Authors
- Rahul Kumar Sharma - Initial work - jerry4rahul
See also the list of contributors who participated in this project.
Acknowledgments
- Facebook for providing the Graph API
- The PHP community for excellent tools and libraries
- All contributors and users of this SDK