PHPackages                             waytohealth/oauth2-fitbit - 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. waytohealth/oauth2-fitbit

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

waytohealth/oauth2-fitbit
=========================

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

1.0.0(1y ago)01.7k—0%MITPHPPHP &gt;=5.6.0

Since Aug 13Pushed 1y agoCompare

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

READMEChangelog (3)Dependencies (6)Versions (5)Used By (0)

Fitbit Provider for OAuth 2.0 Client
====================================

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

This package provides Fitbit 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.

Developers can register applications to use the Fitbit API at .

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

[](#requirements)

The following versions of PHP are supported.

- PHP 5.6
- PHP 7.0
- PHP 7.1
- HHVM

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

[](#installation)

To install, use composer:

```
composer require waytohealth/oauth2-fitbit

```

Usage
-----

[](#usage)

### Authorization Code Grant

[](#authorization-code-grant)

```
use waytohealth\OAuth2\Client\Provider\Fitbit;

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

// start the session
session_start();

// If we don't have an authorization code then get one
if (!isset($_GET['code'])) {

    // Fetch the authorization URL from the provider; this returns the
    // urlAuthorize option and generates and applies any necessary parameters
    // (e.g. state).
    $authorizationUrl = $provider->getAuthorizationUrl();

    // Get the state generated for you and store it to the session.
    $_SESSION['oauth2state'] = $provider->getState();

    // Redirect the user to the authorization URL.
    header('Location: ' . $authorizationUrl);
    exit;

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

} else {

    try {

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

        // We have an access token, which we may use in authenticated
        // requests against the service provider's API.
        echo $accessToken->getToken() . "\n";
        echo $accessToken->getRefreshToken() . "\n";
        echo $accessToken->getExpires() . "\n";
        echo ($accessToken->hasExpired() ? 'expired' : 'not expired') . "\n";

        // Using the access token, we may look up details about the
        // resource owner.
        $resourceOwner = $provider->getResourceOwner($accessToken);

        var_export($resourceOwner->toArray());

        // The provider provides a way to get an authenticated API request for
        // the service, using the access token; it returns an object conforming
        // to Psr\Http\Message\RequestInterface.
        $request = $provider->getAuthenticatedRequest(
            Fitbit::METHOD_GET,
            Fitbit::BASE_FITBIT_API_URL . '/1/user/-/profile.json',
            $accessToken,
            ['headers' => [Fitbit::HEADER_ACCEPT_LANG => 'en_US', Fitbit::HEADER_ACCEPT_LOCALE => 'en_US']]
            // Fitbit uses the Accept-Language for setting the unit system used
            // and setting Accept-Locale will return a translated response if available.
            // https://dev.fitbit.com/docs/basics/#localization
        );
        // Make the authenticated API request and get the parsed response.
        $response = $provider->getParsedResponse($request);

        // If you would like to get the response headers in addition to the response body, use:
        //$response = $provider->getResponse($request);
        //$headers = $response->getHeaders();
        //$parsedResponse = $provider->parseResponse($response);

    } catch (\League\OAuth2\Client\Provider\Exception\IdentityProviderException $e) {

        // Failed to get the access token or user details.
        exit($e->getMessage());

    }

}
```

### Refreshing a Token

[](#refreshing-a-token)

Once your application is authorized, you can refresh an expired token using a refresh token rather than going through the entire process of obtaining a brand new token. To do so, simply reuse this refresh token from your data store to request a refresh.

```
$provider = new waytohealth\OAuth2\Client\Provider\Fitbit([
    'clientId'          => '{fitbit-oauth2-client-id}',
    'clientSecret'      => '{fitbit-client-secret}',
    'redirectUri'       => 'https://example.com/callback-url'
]);

$existingAccessToken = getAccessTokenFromYourDataStore();

if ($existingAccessToken->hasExpired()) {
    $newAccessToken = $provider->getAccessToken('refresh_token', [
        'refresh_token' => $existingAccessToken->getRefreshToken()
    ]);

    // Purge old access token and store new access token to your data store.
}
```

Testing
-------

[](#testing)

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

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

[](#contributing)

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

License
-------

[](#license)

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

###  Health Score

32

—

LowBetter than 72% of packages

Maintenance47

Moderate activity, may be stable

Popularity20

Limited adoption so far

Community14

Small or concentrated contributor base

Maturity42

Maturing project, gaining track record

 Bus Factor1

Top contributor holds 54.7% 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 ~309 days

Total

3

Last Release

392d ago

Major Versions

v0.1.0 → 1.0.02025-04-22

### Community

Maintainers

![](https://www.gravatar.com/avatar/3735b69d141bc99aa32600e9a0493cf1f592c27097407b8755717783fee409b9?d=identicon)[mcgrogan91](/maintainers/mcgrogan91)

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

---

Top Contributors

[![djchen](https://avatars.githubusercontent.com/u/826556?v=4)](https://github.com/djchen "djchen (29 commits)")[![acleitner](https://avatars.githubusercontent.com/u/3340567?v=4)](https://github.com/acleitner "acleitner (14 commits)")[![ElusiveMind](https://avatars.githubusercontent.com/u/195676?v=4)](https://github.com/ElusiveMind "ElusiveMind (4 commits)")[![m4olivei](https://avatars.githubusercontent.com/u/191049?v=4)](https://github.com/m4olivei "m4olivei (2 commits)")[![zembrowski](https://avatars.githubusercontent.com/u/2451083?v=4)](https://github.com/zembrowski "zembrowski (1 commits)")[![bpedroza](https://avatars.githubusercontent.com/u/3336238?v=4)](https://github.com/bpedroza "bpedroza (1 commits)")[![javaongsan](https://avatars.githubusercontent.com/u/911853?v=4)](https://github.com/javaongsan "javaongsan (1 commits)")[![jrquick17](https://avatars.githubusercontent.com/u/7435558?v=4)](https://github.com/jrquick17 "jrquick17 (1 commits)")

---

Tags

clientAuthenticationoauthoauth2authorizationfitbit

###  Code Quality

TestsPHPUnit

Code StylePHP CS Fixer

### Embed Badge

![Health badge](/badges/waytohealth-oauth2-fitbit/health.svg)

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

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