【问题标题】:Fitbit API response handling in PHPPHP 中的 Fitbit API 响应处理
【发布时间】:2016-08-01 13:25:12
【问题描述】:

我正在使用 PHP 库 (https://github.com/djchen/oauth2-fitbit) 通过 Oauth2 检索用户 Fitbit 数据。我正在正确获取数据,但我不确定如何从多维数组响应中获取特定项目。

我正在使用下面的代码,但不起作用

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

完整的 PHP 代码

  $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]);

响应数据

eyJhbGciOiJIUzI1NiJ9.eyJleHAiOjE0NjAzNzgxOTYsInNjb3BlcyI6InJ3ZWkgcnBybyByaHIgcmxvYyByc2xlIHJzZXQgcmFjdCByc29jIiwic3ViIjoiNEg4NU5WIiwiYXVkIjoiMjI3UUNXIiwiaXNzIjoiRml0Yml0IiwidHlwIjoiYWNjZXNzX3Rva2VuIiwiaWF0IjoxNDYwMzc0NTk2fQ.NN9OOx - 3YLvwai0hl0ZRJ4MNWXlaMwcEJ_xxxxxb2382a930144c3a76e69567dcbf0d9834c574919fff8c268b378e635735f1bbf 1460378196未过期数组( 'encodedId'=> '4545NV', '的displayName' => 'dan', )...

【问题讨论】:

    标签: php json fitbit


    【解决方案1】:

    我使用同一个 PHP 库进行 FitBit API 集成。您粘贴问题的回复是由于您的代码的以下部分而出现的数据:

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

    当您尝试从 FitBit 获取用户个人资料时,您提出以下请求:

            $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);
    

    $response 采用以下格式,您可以在那里看到“encodeId”不是直接键。下面是 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
        )
    

    )

    要访问其中的任何内容,您需要以这种方式访问​​它 -

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

    我希望这对您有所帮助。您可以提出更多与 fitbit API 相关的问题,因为我已经完成了所有工作,包括 Fitbit Subscriver API 和通知。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-09-28
      • 2023-03-30
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多