Google api php client 如何在php中使用Google Fit api获得步骤计数?

Google api php client 如何在php中使用Google Fit api获得步骤计数?,google-api-php-client,google-fit,Google Api Php Client,Google Fit,我在谷歌Api Php客户端和谷歌Fit上遇到问题 我想得到我一天内所做的步数总和 我找到了,但它不起作用(看要点) 我的php代码: // Retrive oauth data $clientData = json_decode(file_get_contents("../Devbook-87e2bafd84e6.json")); $client_email = $clientData->client_email; $private_key = $clientData->priv

我在谷歌Api Php客户端谷歌Fit上遇到问题

我想得到我一天内所做的步数总和

我找到了,但它不起作用(看要点)

我的php代码:

// Retrive oauth data
$clientData = json_decode(file_get_contents("../Devbook-87e2bafd84e6.json")); 
$client_email = $clientData->client_email;
$private_key = $clientData->private_key;
$scopes = array(Google_Service_Fitness::FITNESS_ACTIVITY_READ);
$credentials = new Google_Auth_AssertionCredentials(
     $client_email,
     $scopes,
     $private_key
);

$client = new Google_Client();
$client->setState('offline');
$client->setRedirectUri('urn:ietf:wg:oauth:2.0:oob');  // Used in hybrid flows
$client->setAssertionCredentials($credentials);
if ($client->getAuth()->isAccessTokenExpired()) {
     $client->getAuth()->refreshTokenWithAssertion();
}

$fitness_service = new Google_Service_Fitness($client);

$dataSources = $fitness_service->users_dataSources;
$dataSets = $fitness_service->users_dataSources_datasets;

$listDataSources = $dataSources->listUsersDataSources("me");

$timezone = "GMT+0100";
$today = date("Y-m-d");
$endTime = strtotime($today.' 00:00:00 '.$timezone);
$startTime = strtotime('-1 day', $endTime);

while($listDataSources->valid()) {
     $dataSourceItem = $listDataSources->next();
     if ($dataSourceItem['dataType']['name'] == "com.google.step_count.delta") {
            $dataStreamId = $dataSourceItem['dataStreamId'];
            $listDatasets = $dataSets->get("me", $dataStreamId, $startTime.'000000000'.'-'.$endTime.'000000000');

            $step_count = 0;
            while($listDatasets->valid()) {
                $dataSet = $listDatasets->next();
                $dataSetValues = $dataSet['value'];

                if ($dataSetValues && is_array($dataSetValues)) {
                   foreach($dataSetValues as $dataSetValue) {
                       $step_count += $dataSetValue['intVal'];
                   }
                }
            }
            print("STEP: ".$step_count."<br />");
     };
 }

第一件事:您使用的设备上有任何数据吗?我犯了这样的错误:试图从一个根本没有Google Fit数据的帐户获取数据。请不要重复我的错误

我使用了与您相同的示例,它对我有效。唯一的区别是我硬编码了客户端API,如下所示:

$APIKey = '1231231231231231231231231231123123';
$client_id = '12312312312-dkoasodiajsdaosdjh12h1kjakdahs.apps.googleusercontent.com';
$client_secret = '123123123-1231231-123123123';
$redirect_uri = 'http://localhost/fit/code.php';
也许你的证件有问题。 你开始上课了吗?在上述代码之后添加一个
会话\u start()

下面的代码对我有用。适应它,我希望它能帮助你

<?php
/*
 * This code is an adaptation of Google API URL Shortener example from Google PHP API github.
 * This was modified to work with Google Fit.
 * This example will count steps from a logged in user.
 */

// I created an Autoloader to load Google API classes
require_once(__DIR__ . '/Autoloader.php');

$APIKey = '1231231231231231231231231231123123';
$client_id = '12312312312-dkoasodiajsdaosdjh12h1kjakdahs.apps.googleusercontent.com';
$client_secret = '123123123-1231231-123123123';
$redirect_uri = 'http://localhost/fit/code.php';

//This template is nothing but some HTML. You can find it on github Google API example. 
include_once "templates/base.php";

//Start your session.
session_start();

$client = new Google_Client();
$client->setApplicationName('google-fit');
$client->setAccessType('online');
$client->setApprovalPrompt("auto");
$client->setClientId($client_id);
$client->setClientSecret($client_secret);
$client->setRedirectUri($redirect_uri);

$client->addScope(Google_Service_Fitness::FITNESS_ACTIVITY_READ);
$service = new Google_Service_Fitness($client);

/************************************************
If we're logging out we just need to clear our
local access token in this case
 ************************************************/
if (isset($_REQUEST['logout'])) {
    unset($_SESSION['access_token']);
}
/************************************************
If we have a code back from the OAuth 2.0 flow,
we need to exchange that with the authenticate()
function. We store the resultant access token
bundle in the session, and redirect to ourself.
 ************************************************/
if (isset($_GET['code'])) {
    $client->authenticate($_GET['code']);
    $_SESSION['access_token'] = $client->getAccessToken();
    $redirect = 'http://' . $_SERVER['HTTP_HOST'] . $_SERVER['PHP_SELF'];
    header('Location: ' . filter_var($redirect, FILTER_SANITIZE_URL));
    echo "EXCHANGE";
}
/************************************************
If we have an access token, we can make
requests, else we generate an authentication URL.
 ************************************************/
if (isset($_SESSION['access_token']) && $_SESSION['access_token']) {
    $client->setAccessToken($_SESSION['access_token']);
    echo "GOT IT";
    echo "<pre>";

    // Same code as yours
    $dataSources = $service->users_dataSources;
    $dataSets = $service->users_dataSources_datasets;

    $listDataSources = $dataSources->listUsersDataSources("me");

    $timezone = "GMT+0100";
    $today = date("Y-m-d");
    $endTime = strtotime($today.' 00:00:00 '.$timezone);
    $startTime = strtotime('-1 day', $endTime);

    while($listDataSources->valid()) {
        $dataSourceItem = $listDataSources->next();
        if ($dataSourceItem['dataType']['name'] == "com.google.step_count.delta") {
            $dataStreamId = $dataSourceItem['dataStreamId'];
            $listDatasets = $dataSets->get("me", $dataStreamId, $startTime.'000000000'.'-'.$endTime.'000000000');

            $step_count = 0;
            while($listDatasets->valid()) {
                $dataSet = $listDatasets->next();
                $dataSetValues = $dataSet['value'];

                if ($dataSetValues && is_array($dataSetValues)) {
                    foreach($dataSetValues as $dataSetValue) {
                        $step_count += $dataSetValue['intVal'];
                    }
                }
            }
            print("STEP: ".$step_count."<br />");
        };
    }
    echo "</pre>";
} else {
    $authUrl = $client->createAuthUrl();
}

/************************************************
If we're signed in and have a request to shorten
a URL, then we create a new URL object, set the
unshortened URL, and call the 'insert' method on
the 'url' resource. Note that we re-store the
access_token bundle, just in case anything
changed during the request - the main thing that
might happen here is the access token itself is
refreshed if the application has offline access.
 ************************************************/
if ($client->getAccessToken() && isset($_GET['url'])) {
    $_SESSION['access_token'] = $client->getAccessToken();
}

//Dumb example. You don't have to use the code below.
echo pageHeader("User Query - URL Shortener");
if (strpos($client_id, "googleusercontent") == false) {
    echo missingClientSecretsWarning();
    exit;
}
?>
<div class="box">
    <div class="request">
        <?php
        if (isset($authUrl)) {
            echo "<a class='login' href='" . $authUrl . "'>Connect Me!</a>";
        } else {
            echo <<<END
    <form id="url" method="GET" action="{$_SERVER['PHP_SELF']}">
      <input name="url" class="url" type="text">
      <input type="submit" value="Shorten">
    </form>
    <a class='logout' href='?logout'>Logout</a>
END;
        }
        ?>
    </div>

    <div class="shortened">
        <?php
        if (isset($short)) {
            var_dump($short);
        }
        ?>
    </div>
</div>

<?php
/*
 * This code is an adaptation of Google API URL Shortener example from Google PHP API github.
 * This was modified to work with Google Fit.
 * This example will count steps from a logged in user.
 */

// I created an Autoloader to load Google API classes
require_once(__DIR__ . '/Autoloader.php');

$APIKey = '1231231231231231231231231231123123';
$client_id = '12312312312-dkoasodiajsdaosdjh12h1kjakdahs.apps.googleusercontent.com';
$client_secret = '123123123-1231231-123123123';
$redirect_uri = 'http://localhost/fit/code.php';

//This template is nothing but some HTML. You can find it on github Google API example. 
include_once "templates/base.php";

//Start your session.
session_start();

$client = new Google_Client();
$client->setApplicationName('google-fit');
$client->setAccessType('online');
$client->setApprovalPrompt("auto");
$client->setClientId($client_id);
$client->setClientSecret($client_secret);
$client->setRedirectUri($redirect_uri);

$client->addScope(Google_Service_Fitness::FITNESS_ACTIVITY_READ);
$service = new Google_Service_Fitness($client);

/************************************************
If we're logging out we just need to clear our
local access token in this case
 ************************************************/
if (isset($_REQUEST['logout'])) {
    unset($_SESSION['access_token']);
}
/************************************************
If we have a code back from the OAuth 2.0 flow,
we need to exchange that with the authenticate()
function. We store the resultant access token
bundle in the session, and redirect to ourself.
 ************************************************/
if (isset($_GET['code'])) {
    $client->authenticate($_GET['code']);
    $_SESSION['access_token'] = $client->getAccessToken();
    $redirect = 'http://' . $_SERVER['HTTP_HOST'] . $_SERVER['PHP_SELF'];
    header('Location: ' . filter_var($redirect, FILTER_SANITIZE_URL));
    echo "EXCHANGE";
}
/************************************************
If we have an access token, we can make
requests, else we generate an authentication URL.
 ************************************************/
if (isset($_SESSION['access_token']) && $_SESSION['access_token']) {
    $client->setAccessToken($_SESSION['access_token']);
    echo "GOT IT";
    echo "<pre>";

    // Same code as yours
    $dataSources = $service->users_dataSources;
    $dataSets = $service->users_dataSources_datasets;

    $listDataSources = $dataSources->listUsersDataSources("me");

    $timezone = "GMT+0100";
    $today = date("Y-m-d");
    $endTime = strtotime($today.' 00:00:00 '.$timezone);
    $startTime = strtotime('-1 day', $endTime);

    while($listDataSources->valid()) {
        $dataSourceItem = $listDataSources->next();
        if ($dataSourceItem['dataType']['name'] == "com.google.step_count.delta") {
            $dataStreamId = $dataSourceItem['dataStreamId'];
            $listDatasets = $dataSets->get("me", $dataStreamId, $startTime.'000000000'.'-'.$endTime.'000000000');

            $step_count = 0;
            while($listDatasets->valid()) {
                $dataSet = $listDatasets->next();
                $dataSetValues = $dataSet['value'];

                if ($dataSetValues && is_array($dataSetValues)) {
                    foreach($dataSetValues as $dataSetValue) {
                        $step_count += $dataSetValue['intVal'];
                    }
                }
            }
            print("STEP: ".$step_count."<br />");
        };
    }
    echo "</pre>";
} else {
    $authUrl = $client->createAuthUrl();
}

/************************************************
If we're signed in and have a request to shorten
a URL, then we create a new URL object, set the
unshortened URL, and call the 'insert' method on
the 'url' resource. Note that we re-store the
access_token bundle, just in case anything
changed during the request - the main thing that
might happen here is the access token itself is
refreshed if the application has offline access.
 ************************************************/
if ($client->getAccessToken() && isset($_GET['url'])) {
    $_SESSION['access_token'] = $client->getAccessToken();
}

//Dumb example. You don't have to use the code below.
echo pageHeader("User Query - URL Shortener");
if (strpos($client_id, "googleusercontent") == false) {
    echo missingClientSecretsWarning();
    exit;
}
?>
<div class="box">
    <div class="request">
        <?php
        if (isset($authUrl)) {
            echo "<a class='login' href='" . $authUrl . "'>Connect Me!</a>";
        } else {
            echo <<<END
    <form id="url" method="GET" action="{$_SERVER['PHP_SELF']}">
      <input name="url" class="url" type="text">
      <input type="submit" value="Shorten">
    </form>
    <a class='logout' href='?logout'>Logout</a>
END;
        }
        ?>
    </div>

    <div class="shortened">
        <?php
        if (isset($short)) {
            var_dump($short);
        }
        ?>
    </div>
</div>