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.

This package is auto-updated.

Last update: 2025-08-15 19:54:55 UTC


README

Latest Stable Version Total Downloads License PHP Version Require GitHub stars GitHub forks

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

Via Composer (Recommended)

composer require jerry4rahul/facebook-graph-sdk

Via Packagist

Visit Packagist for more installation options.

Manual Installation

  1. Download the latest release from GitHub
  2. Extract the files to your project directory
  3. 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

  1. Always use try-catch blocks when making API calls
  2. Validate input parameters before sending requests
  3. Use field selection to minimize data transfer
  4. Implement proper pagination for large datasets
  5. Handle rate limiting gracefully
  6. Store long-lived tokens securely
  7. Use batch requests for multiple operations
  8. Enable logging for debugging

Requirements

System Requirements

  • PHP: 8.0 or higher
  • Extensions:
    • ext-curl - For HTTP requests
    • ext-json - For JSON parsing
    • ext-mbstring - For string manipulation
  • Dependencies:
    • guzzlehttp/guzzle ^7.2 - HTTP client library
    • psr/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

Commercial Support

For commercial support, custom development, or consulting services, please contact jerry.rahul2@gmail.com.

Authors

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
Made with ❤️ by jerry4rahul