Installation Add the bundle to your Symfony/Laravel project via Composer:
composer require cwd/facebook-bundle
For Laravel (Symfony-based), register the bundle in config/bundles.php:
return [
// ...
Cwd\FacebookBundle\CwdFacebookBundle::class => ['all' => true],
];
Configuration Publish the default config:
php artisan vendor:publish --tag=cwd-facebook-config
Update config/packages/cwd_facebook.yaml with your Facebook App ID, App Secret, and Redirect URI (e.g., http://your-app.test/login/facebook).
First Use Case: Login with Facebook
Add the login route to your routes/web.php:
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\Routing\Annotation\Route;
use Cwd\FacebookBundle\Controller\FacebookController;
Route::get('/login/facebook', [FacebookController::class, 'login']);
Route::get('/login/facebook/callback', [FacebookController::class, 'callback']);
Use the FacebookAuthenticator service in a controller:
use Cwd\FacebookBundle\Security\FacebookAuthenticator;
public function loginWithFacebook(FacebookAuthenticator $authenticator)
{
$user = $authenticator->getUser();
// Handle user data (e.g., $user->getId(), $user->getName())
}
Authentication Flow
return $this->redirect($authenticator->getLoginUrl());
$user = $authenticator->authenticate($request);
$this->authenticateUser($user); // Custom logic (e.g., create/update user in DB)
User Data Fetching Fetch basic or extended user data:
$userData = $authenticator->getUserData(['email', 'first_name', 'last_name']);
For profile pictures or additional fields, use the FacebookClient service:
$client = $this->container->get('cwd_facebook.client');
$profile = $client->get('/me?fields=id,name,picture.type(large)');
Graph API Integration
Use the FacebookClient to interact with the Graph API:
$client->post('/me/feed', ['message' => 'Hello from Laravel!']);
Handle pagination for large datasets:
$posts = $client->get('/me/posts', ['limit' => 10]);
while ($posts->hasNextPage()) {
$posts = $client->nextPage($posts);
}
Custom User Providers Extend the default user provider to map Facebook data to your Laravel models:
use Cwd\FacebookBundle\Security\User\FacebookUserProvider;
class CustomFacebookUserProvider extends FacebookUserProvider
{
public function loadUserByFacebookId($facebookId)
{
return User::where('facebook_id', $facebookId)->first();
}
}
Register the provider in config/packages/cwd_facebook.yaml:
user_provider: App\Service\CustomFacebookUserProvider
$this->app->bind('cwd_facebook.client', function ($app) {
return $app->make('cwd_facebook.client');
});
$cachedData = Cache::remember("facebook_{$userId}_profile", now()->addHours(1), function () use ($client, $userId) {
return $client->get("/{$userId}");
});
message or page events). Use Laravel’s Http facade to verify and process webhook signatures:
use Illuminate\Support\Facades\Http;
public function handleWebhook(Request $request)
{
$challenge = $request->input('hub.challenge');
$signature = $request->input('hub.verify_token');
$rawBody = file_get_contents('php://input');
if ($this->verifyWebhook($rawBody, $signature)) {
return response($challenge);
}
// Process event
}
App Domains and Redirect URIs:
localhost, your-app.test, yourdomain.com).https://your-app.test/login/facebook/callback). Test in "Development Mode" first.State Parameter:
state parameter in the login URL to prevent CSRF attacks:
$loginUrl = $authenticator->getLoginUrl(['state' => $request->get('state')]);
state parameter in the callback to ensure the request hasn’t been tampered with.User Data Permissions:
email instead of email, user_birthday, user_friends). Over-scoping can lead to approval issues.try {
$user = $authenticator->authenticate($request);
} catch (\League\OAuth2\Client\Provider\Exception\IdentityProviderException $e) {
return redirect()->route('home')->with('error', 'Facebook login failed');
}
Token Expiry:
FacebookClient to exchange them for long-lived tokens:
$longLivedToken = $client->getLongLivedAccessToken();
encryption or a dedicated table).Debugging:
config/packages/cwd_facebook.yaml:
debug: true
invalid_scope, invalid_redirect_uri). Common issues:
invalid_redirect_uri: Mismatch between configured and actual callback URLs.invalid_scope: Requested permissions not configured in Facebook App settings.Environment-Specific Config:
Use Laravel’s .env to manage Facebook credentials:
FACEBOOK_APP_ID=your_app_id
FACEBOOK_APP_SECRET=your_app_secret
FACEBOOK_REDIRECT_URI=http://your-app.test/login/facebook/callback
Override the bundle’s config in config/packages/cwd_facebook.yaml:
app_id: '%env(FACEBOOK_APP_ID)%'
app_secret: '%env(FACEBOOK_APP_SECRET)%'
redirect_uri: '%env(FACEBOOK_REDIRECT_URI)%'
Testing:
Use Facebook’s Graph API Explorer to test API calls manually. For Laravel testing, mock the FacebookClient:
$this->mock(FacebookClient::class, function ($mock) {
$mock->shouldReceive('get')
->with('/me')
->andReturn(['id' => '123', 'name' => 'Test User']);
});
Extending the Bundle:
FacebookController by binding your own controller to the cwd_facebook.controller service.FacebookUser class to add custom properties:
class CustomFacebookUser extends FacebookUser
{
public function getCustomField()
{
return $this->getData()['custom_field'] ?? null;
}
}
Update the user_class in config:
user_class: App\Entity\CustomFacebookUser
Performance:
$friends = $client->get('/me/friends?fields=id,name');
$friendIds = array_column($friends->getData(), 'id');
$batch = $client->createBatch();
foreach ($friendIds as $id) {
$batch->add($client->get("/{$id}?fields=email"));
}
$results = $client
How can I help you explore Laravel packages today?