PHPackages                             guangzhonghedd01/oauth2-google - 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. guangzhonghedd01/oauth2-google

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

guangzhonghedd01/oauth2-google
==============================

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

3.0.2(7y ago)13.6kMITPHP

Since Mar 22Pushed 7y agoCompare

[ Source](https://github.com/guangzhonghedd01/oauth2-google)[ Packagist](https://packagist.org/packages/guangzhonghedd01/oauth2-google)[ RSS](/packages/guangzhonghedd01-oauth2-google/feed)WikiDiscussions master Synced today

READMEChangelog (1)Dependencies (5)Versions (15)Used By (0)

Google Provider for OAuth 2.0 Client
====================================

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

[![Join the chat](https://camo.githubusercontent.com/2de4c3b205256fa6697b46aa7b43084118c60392fbe141787bad98b07df1e30f/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f6769747465722d6a6f696e2d3144434537332e737667)](https://gitter.im/thephpleague/oauth2-google)[![Build Status](https://camo.githubusercontent.com/9d273a0ec15375cacb1e13a1cd8b9b9467a1c80f0f0b4abd4d8eceb13a44060f/68747470733a2f2f696d672e736869656c64732e696f2f7472617669732f7468657068706c65616775652f6f61757468322d676f6f676c652e737667)](https://travis-ci.org/thephpleague/oauth2-google)[![Code Coverage](https://camo.githubusercontent.com/facd381bc1f16a8c3687f806b604699896abeec325144cd53353c2ab854c1d53/68747470733a2f2f696d672e736869656c64732e696f2f636f766572616c6c732f7468657068706c65616775652f6f61757468322d676f6f676c652e737667)](https://coveralls.io/r/thephpleague/oauth2-google)[![Code Quality](https://camo.githubusercontent.com/00898919d2859e8ee34fe6fe22a74582888febe4c46e889efc1569a3cbe98851/68747470733a2f2f696d672e736869656c64732e696f2f7363727574696e697a65722f672f7468657068706c65616775652f6f61757468322d676f6f676c652e737667)](https://scrutinizer-ci.com/g/thephpleague/oauth2-google/)[![License](https://camo.githubusercontent.com/61a777322f593e21e4d6b9d4fe65ffc48688a66a6a5ef14a2cc08addf13376a4/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f6c2f6c65616775652f6f61757468322d676f6f676c652e737667)](https://github.com/thephpleague/oauth2-google/blob/master/LICENSE)[![Latest Stable Version](https://camo.githubusercontent.com/d367f2a617c861a9383411dab650e8c040306067907b60db19146b672bd42c9a/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f762f6c65616775652f6f61757468322d676f6f676c652e737667)](https://packagist.org/packages/league/oauth2-google)

This package provides Google 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) and [PSR-4](https://github.com/php-fig/fig-standards/blob/master/accepted/PSR-4-autoloader.md). If you notice compliance oversights, please send a patch via pull request.

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

[](#requirements)

The following versions of PHP are supported.

- PHP 7.0
- PHP 7.1
- PHP 7.2
- PHP 7.3

This package uses [OpenID Connect](https://developers.google.com/identity/protocols/OpenIDConnect) to authenticate users with Google accounts.

To use this package, it will be necessary to have a Google client ID and client secret. These are referred to as `{google-client-id}` and `{google-client-secret}`in the documentation.

Please follow the [Google instructions](https://developers.google.com/identity/protocols/OpenIDConnect#registeringyourapp) to create the required credentials.

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

[](#installation)

To install, use composer:

```
composer require league/oauth2-google
```

Usage
-----

[](#usage)

### Authorization Code Flow

[](#authorization-code-flow)

```
use League\OAuth2\Client\Provider\Google;

$provider = new Google([
    'clientId'     => '{google-client-id}',
    'clientSecret' => '{google-client-secret}',
    'redirectUri'  => 'https://example.com/callback-url',
    'hostedDomain' => 'example.com', // optional; used to restrict access to users on your G Suite/Google Apps for Business accounts
]);

if (!empty($_GET['error'])) {

    // Got an error, probably user denied access
    exit('Got error: ' . htmlspecialchars($_GET['error'], ENT_QUOTES, 'UTF-8'));

} elseif (empty($_GET['code'])) {

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

} elseif (empty($_GET['state']) || ($_GET['state'] !== $_SESSION['oauth2state'])) {

    // State is invalid, possible CSRF attack in progress
    unset($_SESSION['oauth2state']);
    exit('Invalid state');

} else {

    // 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 owner details
        $ownerDetails = $provider->getResourceOwner($token);

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

    } catch (Exception $e) {

        // Failed to get user details
        exit('Something went wrong: ' . $e->getMessage());

    }

    // Use this to interact with an API on the users behalf
    echo $token->getToken();

    // Use this to get a new access token if the old one expires
    echo $token->getRefreshToken();

    // Unix timestamp at which the access token expires
    echo $token->getExpires();
}
```

#### Available Options

[](#available-options)

The `Google` provider has the following [options](https://developers.google.com/identity/protocols/OpenIDConnect#authenticationuriparameters):

- `accessType` to use online or offline access
- `hostedDomain` to authenticate G Suite users
- `prompt` to modify the prompt that the user will see
- `scopes` to request access to additional user information

#### Accessing Token JWT

[](#accessing-token-jwt)

Google provides a [JSON Web Token](https://jwt.io/) (JWT) with all access tokens. This token [contains basic information](https://developers.google.com/identity/protocols/OpenIDConnect#obtainuserinfo) about the authenticated user. The JWT can be accessed from the `id_token` value of the access token:

```
/** @var League\OAuth2\Client\Token\AccessToken $token */
$values = $token->getValues();

/** @var string */
$jwt = $values['id_token'];
```

Parsing the JWT will require a [JWT parser](https://packagist.org/search/?q=jwt). Refer to parser documentation for instructions.

### Refreshing a Token

[](#refreshing-a-token)

Refresh tokens are only provided to applications which request offline access. You can specify offline access by setting the `accessType` option in your provider:

```
use League\OAuth2\Client\Provider\Google;

$provider = new Google([
    'clientId'     => '{google-client-id}',
    'clientSecret' => '{google-client-secret}',
    'redirectUri'  => 'https://example.com/callback-url',
    'accessType'   => 'offline',
]);
```

It is important to note that the refresh token is only returned on the first request after this it will be `null`. You should securely store the refresh token when it is returned:

```
$token = $provider->getAccessToken('authorization_code', [
    'code' => $code
]);

// persist the token in a database
$refreshToken = $token->getRefreshToken();
```

If you ever need to get a new refresh token you can request one by forcing the consent prompt:

```
$authUrl = $provider->getAuthorizationUrl(['prompt' => 'consent']);
```

Now you have everything you need to refresh an access token using a refresh token:

```
use League\OAuth2\Client\Provider\Google;
use League\OAuth2\Client\Grant\RefreshToken;

$provider = new Google([
    'clientId'     => '{google-client-id}',
    'clientSecret' => '{google-client-secret}',
    'redirectUri'  => 'https://example.com/callback-url',
]);

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

Scopes
------

[](#scopes)

Additional [scopes](https://developers.google.com/identity/protocols/googlescopes) can be set by using the `scope` parameter when generating the authorization URL:

```
$authorizationUrl = $provider->getAuthorizationUrl([
    'scope' => [
        'scope-url-here'
    ],
]);
```

Testing
-------

[](#testing)

Tests can be run with:

```
composer test
```

Style checks can be run with:

```
composer check
```

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

[](#contributing)

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

Credits
-------

[](#credits)

- [Woody Gilk](https://github.com/shadowhand)
- [All Contributors](https://github.com/thephpleague/oauth2-google/contributors)

License
-------

[](#license)

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

###  Health Score

35

—

LowBetter than 79% of packages

Maintenance20

Infrequent updates — may be unmaintained

Popularity18

Limited adoption so far

Community19

Small or concentrated contributor base

Maturity71

Established project with proven stability

 Bus Factor2

2 contributors hold 50%+ of commits

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 ~111 days

Recently: every ~90 days

Total

14

Last Release

2623d ago

Major Versions

v0.2.0 → 1.0.0-beta12015-08-03

1.0.1 → 2.0.02017-01-24

2.2.0 → 3.0.02018-12-23

### Community

Maintainers

![](https://www.gravatar.com/avatar/2e224d3b6e1219ac079a44a1a2ac885fdfe3ec529a365a46555cfe5fb5fb9c5c?d=identicon)[guangzhonghedd01](/maintainers/guangzhonghedd01)

---

Top Contributors

[![shadowhand](https://avatars.githubusercontent.com/u/38203?v=4)](https://github.com/shadowhand "shadowhand (75 commits)")[![ramsey](https://avatars.githubusercontent.com/u/42941?v=4)](https://github.com/ramsey "ramsey (51 commits)")[![alexbilbie](https://avatars.githubusercontent.com/u/77991?v=4)](https://github.com/alexbilbie "alexbilbie (29 commits)")[![philsturgeon](https://avatars.githubusercontent.com/u/67381?v=4)](https://github.com/philsturgeon "philsturgeon (10 commits)")[![TomHAnderson](https://avatars.githubusercontent.com/u/493920?v=4)](https://github.com/TomHAnderson "TomHAnderson (6 commits)")[![aripringle](https://avatars.githubusercontent.com/u/1278449?v=4)](https://github.com/aripringle "aripringle (5 commits)")[![tpavlek](https://avatars.githubusercontent.com/u/782576?v=4)](https://github.com/tpavlek "tpavlek (4 commits)")[![jamesmills](https://avatars.githubusercontent.com/u/557096?v=4)](https://github.com/jamesmills "jamesmills (4 commits)")[![pradtke](https://avatars.githubusercontent.com/u/932934?v=4)](https://github.com/pradtke "pradtke (4 commits)")[![rakeev](https://avatars.githubusercontent.com/u/1861570?v=4)](https://github.com/rakeev "rakeev (4 commits)")[![bencorlett](https://avatars.githubusercontent.com/u/181919?v=4)](https://github.com/bencorlett "bencorlett (4 commits)")[![jildertmiedema](https://avatars.githubusercontent.com/u/3383186?v=4)](https://github.com/jildertmiedema "jildertmiedema (4 commits)")[![GrahamCampbell](https://avatars.githubusercontent.com/u/2829600?v=4)](https://github.com/GrahamCampbell "GrahamCampbell (3 commits)")[![msurguy](https://avatars.githubusercontent.com/u/585833?v=4)](https://github.com/msurguy "msurguy (3 commits)")[![dhrrgn](https://avatars.githubusercontent.com/u/149921?v=4)](https://github.com/dhrrgn "dhrrgn (2 commits)")[![jaylinski](https://avatars.githubusercontent.com/u/1668766?v=4)](https://github.com/jaylinski "jaylinski (2 commits)")[![jamesgraham](https://avatars.githubusercontent.com/u/934542?v=4)](https://github.com/jamesgraham "jamesgraham (2 commits)")[![Zaksh](https://avatars.githubusercontent.com/u/357642?v=4)](https://github.com/Zaksh "Zaksh (2 commits)")[![zot24](https://avatars.githubusercontent.com/u/678498?v=4)](https://github.com/zot24 "zot24 (1 commits)")[![benjisg](https://avatars.githubusercontent.com/u/308887?v=4)](https://github.com/benjisg "benjisg (1 commits)")

---

Tags

clientgoogleAuthenticationoauthoauth2authorization

###  Code Quality

TestsPHPUnit

Code StylePHP\_CodeSniffer

### Embed Badge

![Health badge](/badges/guangzhonghedd01-oauth2-google/health.svg)

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

###  Alternatives

[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)
