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.
Installation
composer require developernaren/facebook
Publish the config file:
php artisan vendor:publish --provider="DeveloperNaren\Facebook\FacebookServiceProvider"
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
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);
Key Files to Review
config/facebook.php (default settings)app/Providers/FacebookServiceProvider.php (service binding)app/Facades/Facebook.php (facade usage)Facebook::post('/me/feed', ['message' => 'Your message']);
$file = file_get_contents('path/to/image.jpg');
$response = Facebook::post('/me/photos', [
'source' => $file,
'message' => 'Check out this image!'
]);
Facebook::post('/me/feed', [
'link' => 'https://example.com',
'message' => 'Check this out!'
]);
$posts = Facebook::get('/me/feed', [
'limit' => 5,
'fields' => 'message,created_time'
]);
$profile = Facebook::get('/me', ['fields' => 'name,email']);
$response = Facebook::post('/me/feed', ['message' => 'Test']);
if ($response->hasError()) {
dd($response->getError());
}
$postId = $response->getData()['id'];
$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);
use DeveloperNaren\Facebook\Facades\Facebook;
class PostToFacebookJob implements ShouldQueue
{
public function handle()
{
Facebook::post('/me/feed', [
'message' => 'Scheduled post from 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)
});
Bind custom configurations:
$this->app->singleton('facebook', function ($app) {
return Facebook::with([
'default_graph_version' => 'v18.0',
'http_client' => $app->make(HttpClient::class),
]);
});
Enable debug mode in config/facebook.php:
'debug' => env('FACEBOOK_DEBUG', false),
Log responses for debugging:
Facebook::withDebug(true)->post('/me/feed', ['message' => 'Test']);
Use mocking in PHPUnit:
$this->mock(Facebook::class)->shouldReceive('post')->andReturn($mockResponse);
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'];
});
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;
}
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],
]),
]);
default_graph_version in config to avoid breaking changes.pages_manage_posts, pages_read_engagement).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'],
]);
Facebook::withDebug(true)->post('/me/feed', ['message' => 'Test']);
Check Laravel logs for raw responses.
$response = Facebook::post('/me/feed', ['message' => 'Test']);
dd($response->getRawContent()); // Raw JSON response
message or link for posts).access_token).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->
How can I help you explore Laravel packages today?