PHP code example of jmitchell38488 / oauth2-fitbit

1. Go to this page and download the library: Download jmitchell38488/oauth2-fitbit library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

jmitchell38488 / oauth2-fitbit example snippets


session_start();
use Jmitchell38488\OAuth2\Client\Provider\FitBitAuthorization;
m_fitbit,
    'clientSecret'  => $my_client_secret_from_fitbit,
    'redirectUri'   => $my_callback_url,
]);

// 1st step: Has the user authorised yet?
if (!isset($_SESSION['oauth2state'])) {
    $authorizationUrl = $provider->getAuthorizationUrl([
        'prompt' => FitBitAuthorization::PROMPT_CONSENT,
        'response_type' => FitBitAuthorization::RESPONSETYPE_CODE,
        'scope' => $provider->getAllScope(),
    ]);
    
    // Set the session state to validate in the callback
    $_SESSION['oauth2state'] = $provider->getState();
    
    header('Location: ' . $authorizationUrl);
    exit;
    
// 2nd step: User has authorised, now lets get the refresh & access tokens
} else if (isset($_GET['state']) && $_GET['state'] == $_SESSION['oauth2state'] && isset($_GET['code']) && !isset($_SESSION['fitbit']['oauth'])) {
    try {
        $token = base64_encode(sprintf('%s:%s', $my_client_id_from_fitbit, $my_client_secret_from_fitbit));
        $accessToken = $provider->getAccessToken('authorization_code', [
            'code'  => $_GET['code'],
            'access_token' => $_GET['code'],
            'token' => $token,
        ]);
        
        unset($_SESSION['oauth2state']);
        $_SESSION['fitbit']['oauth2'] = array(
            'accessToken' => $accessToken->getToken(),
            'expires' => $accessToken->getExpires(),
            'refreshToken' => $accessToken->getRefreshToken(),
        );
    } catch (Exception $ex) {
        print $ex->getMessage();
    }

// 3rd step: Authorised, have tokens, but session needs to be refreshed
} else if (time() > $_SESSION['fitbit']['oauth2']['expires']) {
    try {
        $token = base64_encode(sprintf('%s:%s', $my_client_id_from_fitbit, $my_client_secret_from_fitbit));
        $accessToken = $provider->getAccessToken('refresh_token', [
            'grant_type'    => FitBitAuthorization::GRANTTYPE_REFRESH,
            'access_token'  => $_SESSION['fitbit']['oauth2']['accessToken'],
            'refresh_token'  => $_SESSION['fitbit']['oauth2']['refreshToken'],
            'token'         => $token,
        ]);

        unset($_SESSION['oauth2state']);
        $_SESSION['fitbit']['oauth2'] = array(
            'accessToken' => $accessToken->getToken(),
            'expires' => $accessToken->getExpires(),
            'refreshToken' => $accessToken->getRefreshToken(),
        );
    } catch (Exception $ex) {
        print $ex->getMessage();
    }
}

session_start();
use Jmitchell38488\OAuth2\Client\Provider\FitBitImplicit;
m_fitbit,
    'clientSecret'  => $my_client_secret_from_fitbit,
    'redirectUri'   => $my_callback_url,
]);

// 1st step: Has the user authorised yet? Or do we need to refresh?
if (!isset($_SESSION['oauth2state'])) {
    $authorizationUrl = $provider->getAuthorizationUrl([
        'prompt' => FitBitImplicit::PROMPT_CONSENT,
        'response_type' => FitBitImplicit::RESPONSETYPE_TOKEN,
        'scope' => $provider->getAllScope(),
        'expires_in' => FitBitImplicit::EXPIRES_IN_DAY // This can be set to 1, 7 or 30 days
    ]);
    
    // Set the session state to validate in the callback
    $_SESSION['oauth2state'] = $provider->getState();
    
    header('Location: ' . $authorizationUrl);
    exit;
    
// 2nd step: User has authorised, now lets get the refresh & access tokens
// The return URL uses fragments, so you will need to implement front-end logic to redirect the 
// user back to the server with the relevant information, since the URL will look like:
// my_callback_uri#scope=nutrition+weight+location+social+heartrate+settings+sleep+activity+profile&state=abcdef1234567890&user_id=ABC123&token_type=Bearer&expires_in=86400&access_token=abcdefghijklmnopqrstuvwxyz1234567890abcdefghijklmnopqrstuvwxyz1234567890abcdefghijklmnopqrstuvwxyz1234567890
} else if (isset($_GET['state']) && $_GET['state'] == $_SESSION['oauth2state'] && isset($_GET['access_token']) && !isset($_SESSION['fitbit']['oauth'])) {
    unset($_SESSION['oauth2state']);
    $_SESSION['fitbit']['oauth2'] = array(
        'accessToken' => $_GET['access_token'],
        'expires' => $_GET['expires_in'],
        'refreshToken' => null,
    );
} 


$endpoint = $provider->getBaseApiUrl() . "user/-/profile." . FitBit::FORMAT_JSON;
$provider = new FitBit([
    'clientId'      => $my_client_id_from_fitbit,
    'clientSecret'  => $my_client_secret_from_fitbit,
    'redirectUri'   => $my_callback_url,
]);

$request = $provider->getAuthenticatedRequest(
    FitBit::METHOD_GET,
    $endpoint,
    $_SESSION['fitbit']['oauth2']['accessToken']
);

$response = $provider->getResponse($request);