PHPackages                             piv915/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. piv915/oauth2-facebook

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

piv915/oauth2-facebook
======================

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

1.0.0(10y ago)020MITPHPPHP &gt;=5.5.0

Since Feb 4Pushed 10y ago1 watchersCompare

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

READMEChangelogDependencies (4)Versions (17)Used By (0)

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 5.5
- PHP 5.6
- PHP 7.0
- HHVM

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

[](#installation)

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

```
{
    "require": {
        "league/oauth2-facebook": "~1.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.4',
]);

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...

// Number of seconds until the access token will expire, and need refreshing
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- ...

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

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

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

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.4',
]);
```

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-lives 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...
```

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

28

—

LowBetter than 54% of packages

Maintenance20

Infrequent updates — may be unmaintained

Popularity6

Limited adoption so far

Community10

Small or concentrated contributor base

Maturity66

Established project with proven stability

 Bus Factor1

Top contributor holds 89.1% 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 ~13 days

Total

16

Last Release

3916d ago

Major Versions

0.0.12 → 1.0.0-alpha12015-08-05

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

0.0.7PHP &gt;=5.5.0

### Community

Maintainers

![](https://www.gravatar.com/avatar/f3e9f2d9e9c53d9ddbc7b7377c4cc96d11da5eb4aaf00deebfd76fce284903d5?d=identicon)[pixkvix](/maintainers/pixkvix)

---

Top Contributors

[![SammyK](https://avatars.githubusercontent.com/u/578780?v=4)](https://github.com/SammyK "SammyK (41 commits)")[![weaverryan](https://avatars.githubusercontent.com/u/121003?v=4)](https://github.com/weaverryan "weaverryan (4 commits)")[![ctrlaltdylan](https://avatars.githubusercontent.com/u/2694734?v=4)](https://github.com/ctrlaltdylan "ctrlaltdylan (1 commits)")

---

Tags

clientfacebookAuthenticationoauthoauth2authorization

###  Code Quality

TestsPHPUnit

Code StylePHP\_CodeSniffer

### Embed Badge

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

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

###  Alternatives

[league/oauth2-facebook

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

32013.0M66](/packages/league-oauth2-facebook)[league/oauth2-google

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

41721.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)
