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

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

brulath/fitbit-php-oauth2
=========================

FitBit OAuth 2.0 Client Library based heavily upon djchen/oauth2-fitbit &amp; heyitspavel/fitbitphp

2.0.1(9y ago)37.3k1MITPHP

Since Aug 2Pushed 4y ago1 watchersCompare

[ Source](https://github.com/Brulath/fitbit-php-oauth2)[ Packagist](https://packagist.org/packages/brulath/fitbit-php-oauth2)[ RSS](/packages/brulath-fitbit-php-oauth2/feed)WikiDiscussions master Synced today

READMEChangelogDependencies (1)Versions (10)Used By (0)

Not maintained, archived.
=========================

[](#not-maintained-archived)

Unofficial Fitbit Client Library for PHP using OAuth2
=====================================================

[](#unofficial-fitbit-client-library-for-php-using-oauth2)

Wholesale borrows large portions of [djchen/OAuth2-Fitbit](https://github.com/djchen/oauth2-fitbit) (minor change to error checking and scope handling) and [pavelrisenberg/fitbitphp](https://github.com/pavelrisenberg/fitbitphp).

Sets a fitbit-php-oauth2-state cookie during auth flow to prevent CSRF attacks. A session must be started beforehand.

Not guaranteed to work under any circumstances, but it's nice when it does.

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

[](#installation)

To install, use composer:

`composer require brulath/fitbit-php-oauth2`

Usage
-----

[](#usage)

### Initialization

[](#initialization)

All below examples will assume a $fitbit is available. It currently is stateful, so you must set the correct token before using it to make a request.

```
$fitbit = new brulath\fitbit\FitbitPHPOAuth2([
    'client_id' => 'your_client_id',
    'client_secret' => 'your_client_secret',
    'redirect_uri' => 'https://www.example.com/fitbit/auth',  // must match URI specified in your app on the Fitbit Developer website
    'logger' => $log,
    'auto_request' => true,  // automatically redirect the user to the Fitbit OAuth process if a token doesn't exist
    'auto_refresh' => true,  // automatically refresh expired tokens
]);
$json_encoded_oauth2_token_for_user = getOAuth2TokenForUserFromMyDatabase();
$fitbit->setToken($json_encoded_oauth2_token_for_user);
$profile = $fitbit->getProfile();  // read warning below about token refreshes
print_r($profile);
```

### Token Refreshing Warning

[](#token-refreshing-warning)

OAuth2 tokens expire; sometimes they expire very quickly. In order to avoid having to manually acquire an updated token from Fitbit, the library does so for you when it detects you attempting to perform an action on an expired token. The good news is that this means you can be lazy regarding keeping tokens fresh, but the less good news is that you need to be vigilant and grab the updated token when it changes.

There are two options for capturing token acquisitions:

#### Subscribe to a token-change event:

[](#subscribe-to-a-token-change-event)

```
$fitbit->on('obtain-token', function( [ $token ] ) {
    print("Acquired first token {$token} for the user; I'll save this to the database.");
});
$fitbit->on('refresh-token', function( [ $token ] ) {
    print("Acquired refresh token {$token} so I should update the database with this user's new OAuth2 token.");
});
```

#### Check post-request for token changes

[](#check-post-request-for-token-changes)

If you do not wish to use events for some reason, you can check for the token after **every** call you make to the API:

```
$token = $fitbit->getToken();
if ($old_token != $token) {
    print("Acquired token {$token}.");
}
```

I'm lazy, so I've made this library automatically refresh oauth details whenever they've expired mid-call. That means after any call the oauth token may have changed, which you will need to check for (and save the new token). I figure it's probably easier to check for changed tokens than catching token expiration exceptions and handling those. Soz brah.

You have two options: checking `$fitbit->getToken()` after **every** call, or subscribing to [events](http://sabre.io/event/).

```
$fitbit->on('obtain-token', );
$fitbit->on('refresh-token', );
```

### Logging

[](#logging)

If you want to follow automated events for debugging, grab MonoLog (or other) and pass an instance as 'logger' during initialization.

```
composer require monolog/monolog
```

```
use Monolog\Logger;
use Monolog\Handler\StreamHandler;

$log = new Logger('name');
$log->pushHandler(new StreamHandler('path/to/your.log', Logger::WARNING));

$fitbit = new brulath\fitbit\FitbitPHPOAuth2([
    'logger' => $log,
    // etc.
]);
```

### Authorization

[](#authorization)

Authorization obtains OAuth2 keys for the Fitbit account in question. You must have a valid client id, client secret, and redirect uri from the Fitbit developer website to use this library. You must specify all of the scopes you wish to use here; you will need to re-authorize the user if you want to expand your scopes later.

#### Automated Authorization Flow

[](#automated-authorization-flow)

If you're lazy (hi!) you can have the library redirect the user to the Fitbit website for you.

```
// A session is required to prevent CSRF
session_start();

$json_encoded_oauth2_token_for_user = $fitbit->getToken();  // will redirect user to fitbit ($fitbit->doAuthFlow()). the cookie it sets must survive.

echo "My Fitbit access token is: {$json_encoded_oauth2_token_for_user}";
```

#### Manual Authorization Flow

[](#manual-authorization-flow)

If you're lazy (hi!) you can have the library redirect the user to the Fitbit website for you.

Authorization involves sending the user to Fitbit's website with a 'state' code so we can verify the request came from us. Store the state and send the user off to the uri.

```
$auth = $fitbit->getAuthUrlAndState();
saveStateSoWeCanCheckItLater($auth['state']);  // $_SESSION['fitbit-php-oauth2-state'] = $auth['state']
redirectUserToFitbit($auth['uri']);
```

When the user returns to the redirect\_uri specified on the Fitbit developer website, there will be a query ($\_GET) parameter set with the state we stored above; check they match to ensure the request originated with us.

```
$state = retrieveQueryString('state');  // $_GET['state']
$storedState = retrieveStoredState();  // $_SESSION['fitbit-php-oauth2-state']
if ($state != $storedState) {
    throw \Exception("Invalid auth request");
}

$code = retrieveQueryString('code');  // $_GET['code']
$fitbit->handleAuthResponse($code);  // emits obtain-token event
$token = $this->getToken();

echo "My Fitbit access token is: {$token}";
```

### Restoring access

[](#restoring-access)

```
// If token has expired, the first request you make will additionally make a refresh request
$fitbit->setToken(getAccessTokenJsonAsArrayFromMyDatabase());
```

### Making a request

[](#making-a-request)

Inspect the FitbitPHPOAuth2 class to find the appropriate method. In this case, I want all activities on a date:

```
$activities = $fitbit->getActivities('2016-02-20');
print_r($activities);
```

License
-------

[](#license)

The MIT License (MIT).

###  Health Score

34

—

LowBetter than 75% of packages

Maintenance20

Infrequent updates — may be unmaintained

Popularity22

Limited adoption so far

Community10

Small or concentrated contributor base

Maturity69

Established project with proven stability

 Bus Factor1

Top contributor holds 98% 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 ~10 days

Recently: every ~18 days

Total

9

Last Release

3545d ago

Major Versions

1.0.2 → 2.0.02016-08-06

2.0.1 → 3.0.0-beta12016-08-14

### Community

Maintainers

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

---

Top Contributors

[![bjvandrews](https://avatars.githubusercontent.com/u/8130887?v=4)](https://github.com/bjvandrews "bjvandrews (50 commits)")[![mycodecrafting](https://avatars.githubusercontent.com/u/545742?v=4)](https://github.com/mycodecrafting "mycodecrafting (1 commits)")

### Embed Badge

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

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

###  Alternatives

[tempest/framework

The PHP framework that gets out of your way.

2.2k34.4k15](/packages/tempest-framework)[thenetworg/oauth2-azure

Azure Active Directory OAuth 2.0 Client Provider for The PHP League OAuth2-Client

25310.7M83](/packages/thenetworg-oauth2-azure)[league/oauth2-google

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

42223.4M176](/packages/league-oauth2-google)[stevenmaguire/oauth2-keycloak

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

2306.4M45](/packages/stevenmaguire-oauth2-keycloak)[civicrm/civicrm-core

Open source constituent relationship management for non-profits, NGOs and advocacy organizations.

751291.4k43](/packages/civicrm-civicrm-core)[patrickbussmann/oauth2-apple

Sign in with Apple OAuth 2.0 Client Provider for The PHP League OAuth2-Client

1152.8M12](/packages/patrickbussmann-oauth2-apple)

PHPackages © 2026

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