• Stars
    star
    299
  • Rank 139,269 (Top 3 %)
  • Language
    PHP
  • License
    MIT License
  • Created almost 10 years ago
  • Updated over 1 year ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

Facebook Provider for the OAuth 2.0 Client

Facebook Provider for OAuth 2.0 Client

Build Status Latest Stable Version

This package provides Facebook OAuth 2.0 support for the PHP League's OAuth 2.0 Client.

This package is compliant with PSR-1, PSR-2, PSR-4, and PSR-7. If you notice compliance oversights, please send a patch via pull request.

Requirements

The following versions of PHP are supported.

  • PHP 7.3
  • PHP 7.4
  • PHP 8.0

Installation

Add the following to your composer.json file.

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

Usage

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 '<a href="'.$authUrl.'">Log in with Facebook!</a>';
    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 '<pre>';
    var_dump($user);
    # object(League\OAuth2\Client\Provider\FacebookUser)#10 (1) { ...
    echo '</pre>';

} catch (\Exception $e) {

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

echo '<pre>';
// 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 '</pre>';

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) "[email protected]"

# 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

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 for more info.

Beta Tier

Facebook has a 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

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:

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

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.

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

Once you've obtained a user access token you can make additional requests to the Graph API using your favorite HTTP client 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:

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.

Testing

$ ./vendor/bin/phpunit

Contributing

Please see CONTRIBUTING for details.

Credits

License

The MIT License (MIT). Please see License File for more information.

More Repositories

1

flysystem

Abstraction for local and remote filesystems
PHP
13,354
star
2

oauth2-server

A spec compliant, secure by default PHP OAuth 2.0 Server
PHP
6,362
star
3

omnipay

A framework agnostic, multi-gateway payment processing library for PHP 5.6+
PHP
5,813
star
4

fractal

Output complex, flexible, AJAX/RESTful data structures.
PHP
3,524
star
5

oauth2-client

Easy integration with OAuth 2.0 service providers.
PHP
3,508
star
6

csv

CSV data manipulation made easy in PHP
PHP
3,337
star
7

commonmark

Highly-extensible PHP Markdown parser which fully supports the CommonMark and GFM specs.
PHP
2,738
star
8

glide

Wonderfully easy on-demand image manipulation library with an HTTP based API.
PHP
2,550
star
9

climate

PHP's best friend for the terminal.
PHP
1,867
star
10

html-to-markdown

Convert HTML to Markdown with PHP
PHP
1,619
star
11

flysystem-aws-s3-v3

[READYONLY SUB-SPLIT]Flysystem Adapter for AWS SDK V3
PHP
1,557
star
12

skeleton

A skeleton repository for League Packages
PHP
1,525
star
13

event

Event package for your app and domain
PHP
1,519
star
14

plates

Native PHP template system
PHP
1,470
star
15

geotools

Geo-related tools PHP 7.3+ library built atop Geocoder and React libraries
PHP
1,366
star
16

color-extractor

Extract colors from an image like a human would do.
PHP
1,297
star
17

mime-type-detection

League Mime Type Detection
PHP
1,262
star
18

uri

[READ-ONLY] URI manipulation Library
PHP
1,032
star
19

pipeline

League\Pipeline
PHP
959
star
20

oauth1-client

OAuth 1 Client
PHP
936
star
21

tactician

A small, flexible command bus
PHP
858
star
22

container

Small but powerful dependency injection container
PHP
843
star
23

period

PHP's time range API
PHP
720
star
24

route

Fast PSR-7 based routing and dispatch component including PSR-15 middleware, built on top of FastRoute.
PHP
651
star
25

iso3166

A PHP library providing ISO 3166-1 data.
PHP
639
star
26

factory-muffin

Enables the rapid creation of objects for testing
PHP
533
star
27

openapi-psr7-validator

It validates PSR-7 messages (HTTP request/response) against OpenAPI specifications
PHP
525
star
28

config

Simple yet expressive schema-based configuration library for PHP apps
PHP
478
star
29

uri-interfaces

League URI Interfaces
PHP
459
star
30

shunt

[ABANDONED] PHP library for executing commands on multiple remote machines, via SSH
PHP
436
star
31

oauth2-google

Google Provider for the OAuth 2.0 Client
PHP
396
star
32

uri-parser

RFC3986/RFC3987 compliant URI parser
PHP
394
star
33

flysystem-bundle

Symfony bundle integrating Flysystem into Symfony applications
PHP
361
star
34

flysystem-cached-adapter

Flysystem Adapter Cache Decorator.
PHP
356
star
35

statsd

A library for working with StatsD
PHP
351
star
36

url

A simple PHP library to parse and manipulate URLs
PHP
347
star
37

booboo

A modern error handler capable of logging and formatting errors in a variety of ways.
PHP
338
star
38

omnipay-common

Core components for the Omnipay PHP payment processing library
PHP
330
star
39

monga

Simple and swift MongoDB abstraction.
PHP
328
star
40

flysystem-sftp

[READ-ONLY SUBSPLIT] Flysystem Adapter for SFTP
PHP
308
star
41

uri-components

[READ-ONLY] League URI components objects
PHP
307
star
42

omnipay-paypal

PayPal driver for the Omnipay PHP payment processing library
PHP
299
star
43

tactician-bundle

Bundle to integrate Tactician with Symfony projects
PHP
245
star
44

uri-schemes

Collection of URI Immutable Value Objects
PHP
216
star
45

uri-manipulations

Functions and Middleware to manipulate URI Objects
PHP
199
star
46

uri-hostname-parser

A lightweight hostname parser according to public suffix list ICANN section
PHP
197
star
47

omnipay-stripe

Stripe driver for the Omnipay PHP payment processing library
PHP
184
star
48

oauth2-server-bundle

Symfony bundle for the OAuth2 Server.
PHP
183
star
49

json-guard

Validation of json-schema.org compliant schemas.
PHP
175
star
50

flysystem-local

PHP
152
star
51

commonmark-ext-table

The table extension for CommonMark PHP implementation
PHP
128
star
52

glide-laravel

Glide adapter for Laravel
PHP
121
star
53

oauth2-github

GitHub Provider for the OAuth 2.0 Client
PHP
109
star
54

flysystem-ziparchive

Flysystem Adapter for ZipArchive's
PHP
101
star
55

omnipay-example

Example application for Omnipay PHP payments library
PHP
100
star
56

glide-symfony

Glide adapter for Symfony
PHP
96
star
57

oauth2-linkedin

LinkedIn Provider for the OAuth 2.0 Client
PHP
83
star
58

flysystem-memory

Flysystem Memory Adapter
PHP
75
star
59

tactician-container

Load Tactician handlers from any PSR-11/container-interop container
PHP
75
star
60

stack-attack

StackPHP Middleware based on Rack::Attack
PHP
74
star
61

flysystem-webdav

[READ ONLY] WebDAV adapter for Flysystem
PHP
70
star
62

flysystem-dropbox

Flysystem Adapter for Dropbox [ABANDONED] replacement: https://packagist.org/packages/spatie/flysystem-dropbox
PHP
67
star
63

stack-robots

StackPHP middleware providing robots.txt disallow for non-production environments
PHP
67
star
64

oauth2-instagram

Instagram Provider for the OAuth 2.0 Client
PHP
65
star
65

tactician-logger

Adds PSR-3 logging support to the Tactician Command Bus
PHP
62
star
66

omnipay-mollie

Mollie driver for the Omnipay PHP payment processing library
PHP
62
star
67

di

An Ultra-Fast Dependency Injection Container. DEPRECATED
PHP
58
star
68

tactician-doctrine

Tactician plugins for the Doctrine ORM, primarily transactions
PHP
57
star
69

omnipay-authorizenet

Authorize.Net driver for the Omnipay payment processing library
PHP
57
star
70

omnipay-sagepay

Sage Pay driver for the Omnipay PHP payment processing library
PHP
55
star
71

flysystem-azure-blob-storage

PHP
53
star
72

flysystem-aws-s3-v2

Flysystem Adapter for AWS SDK V2
PHP
50
star
73

DEPRECATED-squery

PHP wrapper for osquery
PHP
49
star
74

phpunit-coverage-listener

Report code coverage statistics to third-party services
PHP
48
star
75

thephpleague.github.io

The League of Extraordinary Packages website
SCSS
45
star
76

construct-finder

PHP code construct finder
PHP
42
star
77

factory-muffin-faker

A wrapper around faker for factory muffin
PHP
40
star
78

uri-query-parser

a parser and a builder to work with URI query string the right way in PHP
PHP
37
star
79

flysystem-rackspace

Flysystem Adapter for Rackspace
PHP
37
star
80

flysystem-azure

Flysystem adapter for the Windows Azure.
PHP
35
star
81

flysystem-sftp-v3

PHP
35
star
82

omnipay-braintree

Braintree Driver for Omnipay Gateway
PHP
34
star
83

json-reference

A library for working with JSON References.
PHP
33
star
84

uri-src

URI manipulation Library
PHP
29
star
85

commonmark-extras

Useful extensions for the league/commonmark parser
PHP
28
star
86

uploads

Receive, validate, and distribute uploaded files.
PHP
27
star
87

object-mapper

PHP
27
star
88

omnipay-dummy

Dummy driver for the Omnipay PHP payment processing library
PHP
26
star
89

flysystem-replicate-adapter

Flysystem Adapter Decorator for Replicating Filesystems.
PHP
24
star
90

omnipay-paymentexpress

PaymentExpress driver for the Omnipay PHP payment processing library
PHP
24
star
91

omnipay-worldpay

WorldPay driver for the Omnipay PHP payment processing library
PHP
23
star
92

flysystem-ftp

[SUB-SPLIT] Flysystem FTP Adapter
PHP
23
star
93

flysystem-async-aws-s3

PHP
22
star
94

omnipay-migs

MIGS driver for the Omnipay PHP payment processing library
PHP
21
star
95

omnipay-payfast

PayFast driver for the Omnipay PHP payment processing library
PHP
21
star
96

flysystem-google-cloud-storage

PHP
20
star
97

omnipay-firstdata

First Data driver for the Omnipay PHP payment processing library
PHP
20
star
98

omnipay-multisafepay

MultiSafepay driver for the Omnipay PHP payment processing library
PHP
19
star
99

flysystem-gridfs

GridFS Adapter for Flysystem
PHP
19
star
100

tactician-bernard

Tactician integration with the Bernard queueing library
PHP
19
star