PHPackages                             league/oauth2-facebook - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. [Authentication &amp; Authorization](/categories/authentication)
4. /
5. league/oauth2-facebook

ActiveLibrary[Authentication &amp; Authorization](/categories/authentication)

league/oauth2-facebook
======================

Facebook OAuth 2.0 Client Provider for The PHP League OAuth2-Client

2.2.0(4y ago)32013.0M—5.1%72[1 PRs](https://github.com/thephpleague/oauth2-facebook/pulls)20MITPHPPHP &gt;=7.3

Since Feb 4Pushed 1y ago18 watchersCompare

[ Source](https://github.com/thephpleague/oauth2-facebook)[ Packagist](https://packagist.org/packages/league/oauth2-facebook)[ RSS](/packages/league-oauth2-facebook/feed)WikiDiscussions main Synced 1mo ago

READMEChangelogDependencies (4)Versions (34)Used By (20)

Facebook Provider for OAuth 2.0 Client
======================================

[](#facebook-provider-for-oauth-20-client)

[![Build Status](https://camo.githubusercontent.com/21613213847c9c263e643358cf615085c01c8a5519d5ef366d0e8a47cbbaa2c9/68747470733a2f2f7472617669732d63692e6f72672f7468657068706c65616775652f6f61757468322d66616365626f6f6b2e706e673f6272616e63683d6d6173746572)](https://travis-ci.org/thephpleague/oauth2-facebook)[![Latest Stable Version](https://camo.githubusercontent.com/00c68a1b532a378df0a269d1f3087f86c24d3344f488e5c2fc3824af25119276/68747470733a2f2f706f7365722e707567782e6f72672f6c65616775652f6f61757468322d66616365626f6f6b2f762f737461626c652e706e67)](https://packagist.org/packages/league/oauth2-facebook)

This package provides Facebook OAuth 2.0 support for the PHP League's [OAuth 2.0 Client](https://github.com/thephpleague/oauth2-client).

This package is compliant with [PSR-1](https://github.com/php-fig/fig-standards/blob/master/accepted/PSR-1-basic-coding-standard.md), [PSR-2](https://github.com/php-fig/fig-standards/blob/master/accepted/PSR-2-coding-style-guide.md), [PSR-4](https://github.com/php-fig/fig-standards/blob/master/accepted/PSR-4-autoloader.md), and [PSR-7](https://github.com/php-fig/fig-standards/blob/master/accepted/PSR-7-http-message.md). If you notice compliance oversights, please send a patch via pull request.

Requirements
------------

[](#requirements)

The following versions of PHP are supported.

- PHP 7.3
- PHP 7.4
- PHP 8.0

Installation
------------

[](#installation)

Add the following to your `composer.json` file.

```
{
    "require": {
        "league/oauth2-facebook": "^2.0"
    }
}
```

Usage
-----

[](#usage)

### Authorization Code Flow

[](#authorization-code-flow)

```
session_start();

$provider = new \League\OAuth2\Client\Provider\Facebook([
    'clientId'          => '{facebook-app-id}',
    'clientSecret'      => '{facebook-app-secret}',
    'redirectUri'       => 'https://example.com/callback-url',
    'graphApiVersion'   => 'v2.10',
]);

if (!isset($_GET['code'])) {

    // If we don't have an authorization code then get one
    $authUrl = $provider->getAuthorizationUrl([
        'scope' => ['email', '...', '...'],
    ]);
    $_SESSION['oauth2state'] = $provider->getState();

    echo 'Log in with Facebook!';
    exit;

// Check given state against previously stored one to mitigate CSRF attack
} elseif (empty($_GET['state']) || ($_GET['state'] !== $_SESSION['oauth2state'])) {

    unset($_SESSION['oauth2state']);
    echo 'Invalid state.';
    exit;

}

// Try to get an access token (using the authorization code grant)
$token = $provider->getAccessToken('authorization_code', [
    'code' => $_GET['code']
]);

// Optional: Now you have a token you can look up a users profile data
try {

    // We got an access token, let's now get the user's details
    $user = $provider->getResourceOwner($token);

    // Use these details to create a new profile
    printf('Hello %s!', $user->getFirstName());

    echo '';
    var_dump($user);
    # object(League\OAuth2\Client\Provider\FacebookUser)#10 (1) { ...
    echo '';

} catch (\Exception $e) {

    // Failed to get user details
    exit('Oh dear...');
}

echo '';
// Use this to interact with an API on the users behalf
var_dump($token->getToken());
# string(217) "CAADAppfn3msBAI7tZBLWg...

// The time (in epoch time) when an access token will expire
var_dump($token->getExpires());
# int(1436825866)
echo '';
```

### The FacebookUser Entity

[](#the-facebookuser-entity)

When using the `getResourceOwner()` method to obtain the user node, it will be returned as a `FacebookUser` entity.

```
$user = $provider->getResourceOwner($token);

$id = $user->getId();
var_dump($id);
# string(1) "4"

$name = $user->getName();
var_dump($name);
# string(15) "Mark Zuckerberg"

$firstName = $user->getFirstName();
var_dump($firstName);
# string(4) "Mark"

$lastName = $user->getLastName();
var_dump($lastName);
# string(10) "Zuckerberg"

# Requires the "email" permission
$email = $user->getEmail();
var_dump($email);
# string(15) "thezuck@foo.com"

# Requires the "user_hometown" permission
$hometown = $user->getHometown();
var_dump($hometown);
# array(10) { ["id"]=> string(10) "12345567890" ...

# Requires the "user_about_me" permission
$bio = $user->getBio();
var_dump($bio);
# string(426) "All about me...

$pictureUrl = $user->getPictureUrl();
var_dump($pictureUrl);
# string(224) "https://fbcdn-profile-a.akamaihd.net/hprofile- ...

$isDefaultPicture = $user->isDefaultPicture();
var_dump($isDefaultPicture);
# boolean false

$coverPhotoUrl = $user->getCoverPhotoUrl();
var_dump($coverPhotoUrl);
# string(111) "https://fbcdn-profile-a.akamaihd.net/hphotos- ...

$gender = $user->getGender();
var_dump($gender);
# string(4) "male"

$locale = $user->getLocale();
var_dump($locale);
# string(5) "en_US"

$timezone = $user->getTimezone();
var_dump($timezone);
# int -5

$link = $user->getLink();
var_dump($link);
# string(62) "https://www.facebook.com/app_scoped_user_id/1234567890/"

$maxAge = $user->getMaxAge();
var_dump($maxAge);
# int 17 | null

$minAge = $user->getMinAge();
var_dump($minAge);
# int 21
```

You can also get all the data from the User node as a plain-old PHP array with `toArray()`.

```
$userData = $user->toArray();
```

### Graph API Version

[](#graph-api-version)

The `graphApiVersion` option is required. If it is not set, an `\InvalidArgumentException` will be thrown.

```
$provider = new League\OAuth2\Client\Provider\Facebook([
    /* . . . */
    'graphApiVersion'   => 'v2.10',
]);
```

Each version of the Graph API has breaking changes from one version to the next. This package no longer supports a fallback to a default Graph version since your app might break when the fallback Graph version is updated.

See the [Graph API version schedule](https://developers.facebook.com/docs/apps/changelog) for more info.

### Beta Tier

[](#beta-tier)

Facebook has a [beta tier](https://developers.facebook.com/docs/apps/beta-tier) that contains the latest deployments before they are rolled out to production. To enable the beta tier, set the `enableBetaTier` option to `true`.

```
$provider = new League\OAuth2\Client\Provider\Facebook([
    /* . . . */
    'enableBetaTier'   => true,
]);
```

### Refreshing a Token

[](#refreshing-a-token)

Facebook does not support refreshing tokens. In order to get a new "refreshed" token, you must send the user through the login-with-Facebook process again.

From the [Facebook documentation](https://developers.facebook.com/docs/facebook-login/access-tokens#extending):

> Once \[the access tokens\] expire, your app must send the user through the login flow again to generate a new short-lived token.

The following code will throw a `League\OAuth2\Client\Provider\Exception\FacebookProviderException`.

```
$grant = new \League\OAuth2\Client\Grant\RefreshToken();
$token = $provider->getAccessToken($grant, ['refresh_token' => $refreshToken]);
```

### Long-lived Access Tokens

[](#long-lived-access-tokens)

Facebook will allow you to extend the lifetime of an access token by [exchanging a short-lived access token with a long-lived access token](https://developers.facebook.com/docs/facebook-login/access-tokens#extending).

Once you obtain a short-lived (default) access token, you can exchange it for a long-lived one.

```
try {
    $token = $provider->getLongLivedAccessToken('short-lived-access-token');
} catch (Exception $e) {
    echo 'Failed to exchange the token: '.$e->getMessage();
    exit();
}

var_dump($token->getToken());
# string(217) "CAADAppfn3msBAI7tZBLWg...
```

### Getting Additional Data

[](#getting-additional-data)

Once you've obtained a user access token you can make additional requests to the Graph API using your [favorite HTTP client](https://github.com/guzzle/guzzle) to send the requests. For this example, we'll just use PHP's built-in `file_get_contents()` as our HTTP client to grab 5 events from the the authenticated user.

```
// Get 5 events from authenticated user
// Requires the `user_events` permission
$baseUrl = 'https://graph.facebook.com/v2.10';
$params = http_build_query([
    'fields' => 'id,name,start_time',
    'limit' => '5',
    'access_token' => $token->getToken(),
    'appsecret_proof' => hash_hmac('sha256', $token->getToken(), '{facebook-app-secret}'),
]);
$response = file_get_contents($baseUrl.'/me/events?'.$params);

// Raw JSON response from the Graph API
var_dump($response);
# string(1190) "{"data":[{"id":"123","name":"Derby City Swing 2016","start_time":"2016-01-28T17:00:00-0500"} ...

// Response as a plain-old PHP array
$data = json_decode($response, true);
var_dump($data);
# array(2) { ["data"]=> array(5) { ...
```

See more about:

- [The `/{user-id}/events` edge](https://developers.facebook.com/docs/graph-api/reference/user/events).
- [The `appsecret_proof`](https://developers.facebook.com/docs/graph-api/securing-requests).
- [The `file_get_contents()` function](http://php.net/file_get_contents).

If you need to make even more complex queries to the Graph API to get lots of data back with just one request, check out the [Facebook Query Builder](https://github.com/SammyK/FacebookQueryBuilder).

Testing
-------

[](#testing)

```
$ ./vendor/bin/phpunit
```

Contributing
------------

[](#contributing)

Please see [CONTRIBUTING](https://github.com/thephpleague/oauth2-facebook/blob/master/CONTRIBUTING.md) for details.

Credits
-------

[](#credits)

- [Sammy Kaye Powers](https://github.com/SammyK)
- [All Contributors](https://github.com/thephpleague/oauth2-facebook/contributors)

License
-------

[](#license)

The MIT License (MIT). Please see [License File](https://github.com/thephpleague/oauth2-facebook/blob/master/LICENSE) for more information.

###  Health Score

56

—

FairBetter than 98% of packages

Maintenance36

Infrequent updates — may be unmaintained

Popularity67

Solid adoption and visibility

Community43

Growing community involvement

Maturity69

Established project with proven stability

 Bus Factor1

Top contributor holds 58.5% of commits — single point of failure

How is this calculated?**Maintenance (25%)** — Last commit recency, latest release date, and issue-to-star ratio. Uses a 2-year decay window.

**Popularity (30%)** — Total and monthly downloads, GitHub stars, and forks. Logarithmic scaling prevents top-heavy scores.

**Community (15%)** — Contributors, dependents, forks, watchers, and maintainers. Measures real ecosystem engagement.

**Maturity (30%)** — Project age, version count, PHP version support, and release stability.

###  Release Activity

Cadence

Every ~80 days

Recently: every ~127 days

Total

33

Last Release

1544d ago

Major Versions

0.0.12 → 1.0.0-alpha12015-08-05

1.4.4 → 2.0.02017-01-25

1.4.5 → 2.0.22020-07-25

PHP version history (5 changes)0.0.0PHP &gt;=5.4.0

0.0.7PHP &gt;=5.5.0

2.0.0PHP ^5.6 || ^7.0

2.0.5PHP ^5.6 || ^7.0 || ^8.0

2.1.0PHP &gt;=7.3

### Community

Maintainers

![](https://www.gravatar.com/avatar/6b7311351d345939106c196014a18719b811326452f3a08adb1047a2143d7bcc?d=identicon)[SammyK](/maintainers/SammyK)

---

Top Contributors

[![SammyK](https://avatars.githubusercontent.com/u/578780?v=4)](https://github.com/SammyK "SammyK (76 commits)")[![shadowhand](https://avatars.githubusercontent.com/u/38203?v=4)](https://github.com/shadowhand "shadowhand (14 commits)")[![mikealmond](https://avatars.githubusercontent.com/u/600744?v=4)](https://github.com/mikealmond "mikealmond (11 commits)")[![Yozhef](https://avatars.githubusercontent.com/u/8971757?v=4)](https://github.com/Yozhef "Yozhef (5 commits)")[![antoin-m](https://avatars.githubusercontent.com/u/3316447?v=4)](https://github.com/antoin-m "antoin-m (4 commits)")[![lbacik](https://avatars.githubusercontent.com/u/7950189?v=4)](https://github.com/lbacik "lbacik (4 commits)")[![weaverryan](https://avatars.githubusercontent.com/u/121003?v=4)](https://github.com/weaverryan "weaverryan (4 commits)")[![pmaselkowski](https://avatars.githubusercontent.com/u/520283?v=4)](https://github.com/pmaselkowski "pmaselkowski (2 commits)")[![mabar](https://avatars.githubusercontent.com/u/20974277?v=4)](https://github.com/mabar "mabar (1 commits)")[![grifx](https://avatars.githubusercontent.com/u/1662628?v=4)](https://github.com/grifx "grifx (1 commits)")[![mlncn](https://avatars.githubusercontent.com/u/27131?v=4)](https://github.com/mlncn "mlncn (1 commits)")[![ctrlaltdylan](https://avatars.githubusercontent.com/u/2694734?v=4)](https://github.com/ctrlaltdylan "ctrlaltdylan (1 commits)")[![BenMorel](https://avatars.githubusercontent.com/u/1952838?v=4)](https://github.com/BenMorel "BenMorel (1 commits)")[![shyuan](https://avatars.githubusercontent.com/u/347809?v=4)](https://github.com/shyuan "shyuan (1 commits)")[![zegenie](https://avatars.githubusercontent.com/u/205936?v=4)](https://github.com/zegenie "zegenie (1 commits)")[![jerowork](https://avatars.githubusercontent.com/u/4119451?v=4)](https://github.com/jerowork "jerowork (1 commits)")[![autowp](https://avatars.githubusercontent.com/u/2299280?v=4)](https://github.com/autowp "autowp (1 commits)")[![ker0x](https://avatars.githubusercontent.com/u/5331654?v=4)](https://github.com/ker0x "ker0x (1 commits)")

---

Tags

clientfacebookAuthenticationoauthoauth2authorization

###  Code Quality

TestsPHPUnit

Code StylePHP\_CodeSniffer

### Embed Badge

![Health badge](/badges/league-oauth2-facebook/health.svg)

```
[![Health](https://phpackages.com/badges/league-oauth2-facebook/health.svg)](https://phpackages.com/packages/league-oauth2-facebook)
```

###  Alternatives

[league/oauth2-google

Google OAuth 2.0 Client Provider for The PHP League OAuth2-Client

42121.2M118](/packages/league-oauth2-google)[cakedc/oauth2-cognito

Cognito OAuth 2.0 Client Provider for The PHP League OAuth2-Client

18597.7k](/packages/cakedc-oauth2-cognito)

PHPackages © 2026

[Directory](/)[Categories](/categories)[Trending](/trending)[Changelog](/changelog)[Analyze](/analyze)
