3

I am using a PHP library (https://github.com/djchen/oauth2-fitbit) to retreive a users Fitbit data via Oauth2. I am getting the data correctly but I am not sure how to grab a specific item from the multidimensional array response.

I am using code below but doesnt work

$response = $provider->getResponse($request);
        var_dump($response['encodedId'][0]);

Full PHP code

  $provider = new djchen\OAuth2\Client\Provider\Fitbit([
        'clientId'          => 'xxx',
        'clientSecret'      => 'xxx',
        'redirectUri'       => 'http://xxx-env.us-east-1.elasticbeanstalk.com/a/fitbitapi'
    ]);

    // 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']) || ($_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(
                'GET',
                'https://api.fitbit.com/1/user/-/profile.json',
                $accessToken
            );
            // Make the authenticated API request and get the response.
            $response = $provider->getResponse($request);
            var_dump($response['encodedId'][0]);

Response data

eyJhbGciOiJIUzI1NiJ9.eyJleHAiOjE0NjAzNzgxOTYsInNjb3BlcyI6InJ3ZWkgcnBybyByaHIgcmxvYyByc2xlIHJzZXQgcmFjdCByc29jIiwic3ViIjoiNEg4NU5WIiwiYXVkIjoiMjI3UUNXIiwiaXNzIjoiRml0Yml0IiwidHlwIjoiYWNjZXNzX3Rva2VuIiwiaWF0IjoxNDYwMzc0NTk2fQ.NN9OOx--3YLvwai0hl0ZRJ4MNWXlaMwcEJ_xxxxxb2382a930144c3a76e69567dcbf0d9834c574919fff8c268b378e635735f1bbf 1460378196 not expired array ( 'encodedId' => '4545NV', 'displayName' => 'dan', )...

fire
  • 21,383
  • 17
  • 79
  • 114
drew
  • 105
  • 10

1 Answers1

0

I am using the same PHP library for FitBit API integration. The response you have pasted with the question is the data that is coming because of the following part of your code:

     // 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());

When you try to get the user profile from FitBit, you make the below request :

        $request = $provider->getAuthenticatedRequest(
            'GET',
            'https://api.fitbit.com/1/user/-/profile.json',
            $accessToken
        );
        // Make the authenticated API request and get the response.
        $response = $provider->getResponse($request);

The $response comes in the below format and you can see there that "encodeId" is not the direct key there. Below is the example of var_dump($response); -

Array(
[user] => Array
    (
        [age] => 27
        [avatar] => https://static0.fitbit.com/images/profile/defaultProfile_100_male.gif
        [avatar150] => https://static0.fitbit.com/images/profile/defaultProfile_150_male.gif
        [averageDailySteps] => 3165
        [corporate] => 
        [dateOfBirth] => 1991-04-02
        [displayName] => Avtar
        [distanceUnit] => METRIC
        [encodedId] => 478ZBH
        [features] => Array
            (
                [exerciseGoal] => 1
            )

        [foodsLocale] => en_GB
        [fullName] => Avtar Gaur
        [gender] => MALE
        [glucoseUnit] => METRIC
        [height] => 181
        [heightUnit] => METRIC
        [locale] => en_IN
        [memberSince] => 2016-01-17
        [offsetFromUTCMillis] => 19800000
        [startDayOfWeek] => MONDAY
        [strideLengthRunning] => 94.2
        [strideLengthRunningType] => default
        [strideLengthWalking] => 75.1
        [strideLengthWalkingType] => default
        [timezone] => Asia/Colombo
        [topBadges] => Array
            (
                [0] => Array
                    (
                    )

                [1] => Array
                    (
                    )

                [2] => Array
                    (
                    )

            )

        [waterUnit] => METRIC
        [waterUnitName] => ml
        [weight] => 80
        [weightUnit] => METRIC
    )

)

In order to access anything in there you need to access it in this manner -

$encodedId = $response['user']['encodedId];

I hope this was helpful to you. You can ask more questions related to fitbit API as I have got it all working, including the Fitbit Subscriver API and Notifications.

Avtar Gaur
  • 31
  • 4