PHPackages                             samuelthomas2774/oauth-client - 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. samuelthomas2774/oauth-client

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

samuelthomas2774/oauth-client
=============================

An OAuth 2.0 Client library with built-in support for Facebook, Google, Microsoft, Yahoo, GitHub, LinkedIn &amp; more.

v3.0.2(6y ago)121112[1 issues](https://github.com/samuelthomas2774/oauth-client/issues)MITPHP

Since Jul 10Pushed 6y ago1 watchersCompare

[ Source](https://github.com/samuelthomas2774/oauth-client)[ Packagist](https://packagist.org/packages/samuelthomas2774/oauth-client)[ Docs](https://samuelthomas2774.github.io/oauth-client/)[ RSS](/packages/samuelthomas2774-oauth-client/feed)WikiDiscussions master Synced 1mo ago

READMEChangelog (10)Dependencies (1)Versions (10)Used By (0)

OAuth Client
============

[](#oauth-client)

An OAuth 2.0 Client library with built-in support for Facebook, Google, Microsoft, Yahoo, GitHub, LinkedIn &amp; more.

> You can see the current source running on Heroku from [examples/all-2](examples/all-2) here:

**[Built-in providers](#built-in-providers)**

- [Facebook](https://facebook.com)
- [Google](https://google.co.uk)
- [Microsoft](https://microsoft.com/en-gb/)
- [Yahoo](https://yahoo.co.uk)
- [GitHub](https://github.com)
- [LinkedIn](https://linkedin.com)
- [Spotify](https://spotify.com)
- [Amazon](https://amazon.co.uk)
- [Disqus](https://disqus.com)
- [Instagram](https://instagram.com)
- [TeamViewer](https://teamviewer.com)
- [WordPress.com](https://wordpress.com)
- [Eventbrite](https://eventbrite.com)
- [Foursquare](https://foursquare.com)
- [SpeechMore](https://speechmore.ml)
- [GitLab](https://about.gitlab.com)
- [Mastodon](https://joinmastodon.org)
- [Discord](https://discordapp.com)
- [Pinterest](https://pinterest.co.uk)
- [Slack](https://slack.com)
- [DigitalOcean](https://digitalocean.com)
- [Gitter](https://gitter.im)
- [Deezer](https://deezer.com)
- [DeviantArt](https://deviantart.com)
- [Twitch](https://twitch.tv)
- [Vimeo](https://vimeo.com)
- [Reddit](https://reddit.com)
- Other, just create a new `OAuth2\\GenericOAuthProvider` object and include the `base_api_endpoint`, `authorise_endpoint` and `token_endpoint` options

Requirements and installation
-----------------------------

[](#requirements-and-installation)

This requires at least PHP 7.1.

VersionSupportedPHP 5.6NoPHP 7.0NoPHP 7.1YesPHP 7.2YesPHP 7.3Yes### Composer

[](#composer)

1. Add `"samuelthomas2774/oauth-client": "~3.0.0"` to your composer.json ```
    {
        "require": {
            "samuelthomas2774/oauth-client": "~3.0.0"
        }
    }
    ```
2. Run Composer
    This will automatically download the latest patch version. ```
    composer install

    ```

Usage
-----

[](#usage)

1. Include `vendor/autoload.php` in all pages that need access to any provider
    This will load any class in the src directory when used. ```
    require_once __DIR__ . '/vendor/autoload.php';
    ```
2. Create a new `OAuth2\\OAuth` object with the parameters `$client_id`, `$client_secret` and `$options`
    The `$options` array must have at least `base_api_endpoint`, `authorise_endpoint` and `token_endpoint`. ```
    use OAuth2\GenericOAuthProvider;

    $client_id = 'client-id';
    $client_secret = 'client-secret';

    $client = new GenericOAuthProvider($client_id, $client_secret, null, [
        'session_prefix' => 'facebook_',
        'base_api_endpoint' => 'https://graph.facebook.com',
        'authorise_endpoint' => 'https://facebook.com/dialog/oauth',
        'token_endpoint' => 'oauth/access_token', // Relative to the base API URL
    ]);
    ```

- To get a link to the authorise page: ```
    $redirect_url = 'https://example.com/facebook/code.php';
    $scope = ['email', 'user_friends']; // Optional scope array

    // Returns an OAuth2\AuthoriseUrl object
    // This will be converted to a string automatically if needed
    // You can use this object to get the OAuth2\State object to store extra state data accessible with
    // $client->getRequestState() when the user accepts/rejects the authorise request
    $login_url = $client->generateAuthoriseUrlAndState($redirect_url, $scope);

    // Add data to the state object
    // Every time generateAuthoriseUrlAndState is called a new state object will be created with separate data,
    // so you can have multiple authorise links on the same page and have the authorise response page react differently
    // depending on which link was used
    $login_url->getState()->next_url = '/';
    ```

    ```
    // You can also set the state parameter yourself (not recommended)
    // $login_url->getState() will still return a state object, but the attached data won't be saved
    // Use $login_url->getStateId(), $login_url->getState()->getId() or cast the state object to a string to get the
    // value of the state parameter
    $state = '...'; // Generate a random value and store in somewhere the next page can access (or set to null to not set a state parameter)
    $login_url = $client->generateAuthoriseUrl($state, $redirect_url, $scope);
    ```
- To get an access token from the code that was returned: ```
    // Validates the request state and returns an OAuth2\AccessToken object
    $token = $client->getAccessTokenFromRequestCodeAndState();
    ```

    ```
    // You can also validate the state and pass the redirect url and an optional requested scope array yourself
    // Only do this if you set the state parameter when you generated the authorise link

    $redirect_url = 'https://example.com/facebook/code.php'; // Must match the $redirect_url given to generateAuthoriseUrl exactly
    $requested_scope = ['email', 'user_friends']; // Optional requested scope array to include in the AccessToken object
    $token = $client->getAccessTokenFromRequestCode($redirect_url, $requested_scope);
    ```
- To get an access token a refresh token: ```
    // Returns an object of data returned from the server
    // This may include a new refresh_token
    // $token can be a string (a refresh token) or an AccessToken object with a refresh token returned by all
    // getAccessToken* methods
    $new_token = $oauth->getAccessTokenFromRefreshToken($token);
    ```
- To make API requests with the access token: ```
    try {
        $response = $client->api('GET', 'me' /*, $guzzle_options = [] /*, $auth = null */);
    } catch (Exception $error) {
        echo 'OAuth provider returned an error: ' . print_r($error, true);
    }
    ```
- To get/set the current access token: You do not need to do this at the start of the script to get the access token from the session, this is done automatically. Also, this function updates the access token in the session. ```
    // Get
    $token = $client->getAccessToken();

    // Set
    $client->setAccessToken($new_token);

    // Set without updating the access token in the session
    $client->setAccessToken($new_token, false);
    ```

Built-in providers
------------------

[](#built-in-providers)

Any other providers please contact me at  and I'll add it as soon as possible.

**Provider****Class****Sign-up url**AmazonOAuth2\\Providers\\Amazon\\AmazonDeezerOAuth2\\Providers\\Deezer\\DeezerDeviantArtOAuth2\\Providers\\DeviantArt\\DeviantArtDigitalOceanOAuth2\\Providers\\DigitalOcean\\DigitalOceanDiscord `P`OAuth2\\Providers\\Discord\\DiscordDisqusOAuth2\\Providers\\Disqus\\DisqusEventbriteOAuth2\\Providers\\Eventbrite\\EventbriteFacebook `P`OAuth2\\Providers\\Facebook\\FacebookFoursquareOAuth2\\Providers\\Foursquare\\FoursquareGitHub `P`OAuth2\\Providers\\GitHub\\GitHubGitLab `P` `I`OAuth2\\Providers\\GitLab\\GitLab \*GitterOAuth2\\Providers\\Gitter\\GitterGoogle `P`OAuth2\\Providers\\Google\\GoogleInstagramOAuth2\\Providers\\Instagram\\InstagramLinkedIn `P`OAuth2\\Providers\\Linkedin\\LinkedinMastodon `P` `I`OAuth2\\Providers\\Mastodon\\Mastodon \*MicrosoftOAuth2\\Providers\\Microsoft\\MicrosoftPinterestOAuth2\\Providers\\Pinterest\\PinterestRedditOAuth2\\Providers\\Reddit\\RedditSlack `P`OAuth2\\Providers\\Slack\\SlackSpeechMore `P`OAuth2\\Providers\\SpeechMore\\SpeechMoreSpotifyOAuth2\\Providers\\Spotify\\SpotifyTeamViewerOAuth2\\Providers\\TeamViewer\\TeamViewerTwitchOAuth2\\Providers\\Twitch\\TwitchVimeoOAuth2\\Providers\\Vimeo\\VimeoWordPress.comOAuth2\\Providers\\WordPress\\WordPressYahoo `P`OAuth2\\Providers\\Yahoo\\Yahoo\* This URL is for the default instance used

All the built-in providers implement `OAuth2\UserProfilesInterface`, which adds an extra method to get a `OAuth2\UserProfile` object.

```
try {
    $user = $client->getUserProfile();
} catch (Exception $error) {
    echo 'OAuth provider returned an error: ' . print_r($error, true);
}
```

Some also implement `OAuth2\UserPicturesInterface` (`P`), which adds a method to get the URL of the user's picture/avatar.

```
try {
    $picture_url = $client->getUserPictureUrl();
} catch (Exception $error) {
    echo 'OAuth provider returned an error: ' . print_r($error, true);
}
```

As GitLab and Mastodon support multiple instances they implement `OAuth2\MultipleInstancesInterface`, which adds an option and method to set the instance's URL.

```
use OAuth2\Providers\GitLab\GitLab;

$client = new GitLab($client_id, $client_secret, null, [
    'instance_url' => 'https://gitlab.fancy.org.uk',
]);

$client->setInstanceUrl('https://gitlab.com');
```

### Additional methods for providers

[](#additional-methods-for-providers)

[Facebook](src/Providers/Facebook/README.md) and [Discord](src/Providers/Discord/README.md) have additional methods.

Extending the OAuth2 class
--------------------------

[](#extending-the-oauth2-class)

You can extend the OAuth2 and other classes to add new functions and make existing functions work differently:

```
use OAuth2\Providers\Facebook\Facebook;

class My_Extended_Facebook_Class extends Facebook
{
    // Change the base_api_endpoint option to use a different API version
    public $base_api_endpoint = 'https://graph.facebook.com/v1.0/';

    // Add a new function for getting the current user's ID
    public function getUserId(): string
    {
        $user = $this->getUserProfile(['id']);
        return $user->id;
    }
}
```

You can then use the newly created class:

```
$client = new My_Extended_Facebook_Class('client-id', 'client-secret');

try {
    echo 'Your Facebook User ID (for this app) is: ' . htmlentities($client->getUserId());
} catch (Exception $exception) {
    echo 'Facebook returned an error: ' . $exception->getMessage();
}
```

###  Health Score

32

—

LowBetter than 72% of packages

Maintenance18

Infrequent updates — may be unmaintained

Popularity18

Limited adoption so far

Community9

Small or concentrated contributor base

Maturity69

Established project with proven stability

 Bus Factor1

Top contributor holds 100% 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 ~215 days

Recently: every ~283 days

Total

8

Last Release

2455d ago

Major Versions

v2.2.0 → v3.x-dev2019-08-28

### Community

Maintainers

![](https://www.gravatar.com/avatar/63ba47dfc3204082b01a5aefa7db688a21910a781b78738fdc1a910ef0081460?d=identicon)[samuelthomas2774](/maintainers/samuelthomas2774)

---

Top Contributors

[![samuelthomas2774](https://avatars.githubusercontent.com/u/8474065?v=4)](https://github.com/samuelthomas2774 "samuelthomas2774 (171 commits)")

---

Tags

oauthoauth-clientoauth2oauth2-clientphpclientoauthoauth2oauth2-clientoauth-client

### Embed Badge

![Health badge](/badges/samuelthomas2774-oauth-client/health.svg)

```
[![Health](https://phpackages.com/badges/samuelthomas2774-oauth-client/health.svg)](https://phpackages.com/packages/samuelthomas2774-oauth-client)
```

###  Alternatives

[mollie/oauth2-mollie-php

Mollie Provider for OAuth 2.0 Client

251.7M1](/packages/mollie-oauth2-mollie-php)[omines/oauth2-gitlab

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

36721.5k13](/packages/omines-oauth2-gitlab)

PHPackages © 2026

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