我试图使用google fit API从google fit数据存储中获取覆盖前一日期注册用户的步骤,当我手动运行它时,此解决方案工作得很好,但一旦我将其插入调度程序以运行automate,它就会抛出错误。下面是我的代码:
public static function fetch(){
$client = Helper::getProvider();
#$client->setScopes('https://www.googleapis.com/auth/fitness.location.read https://www.googleapis.com/auth/fitness.activity.read');
$client->addScope(\Google_Service_Fitness::FITNESS_ACTIVITY_READ);
$service = new \Google_Service_Fitness($client);
#$client->addScope(\Google_Service_Fitness::FITNESS_ACTIVITY_READ);
$service = new \Google_Service_Fitness($client);
// 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);
$step_count = 0;
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');
while($listDatasets->valid()) {
$dataSet = $listDatasets->next();
$dataSetValues = $dataSet['value'];
if ($dataSetValues && is_array($dataSetValues)) {
foreach($dataSetValues as $dataSetValue) {
$step_count += $dataSetValue['intVal'];
}
}
}
}
}
return $step_count;
}
public static function getProvider(){
$client = new \Google_Client();
$client->setApplicationName('google-fit');
$client->setAccessType('offline');
$client->setApprovalPrompt("auto");
$client->setClientId('XX.apps.googleusercontent.com');
$client->setClientSecret('XYV');
return $client;
}我在尝试运行此命令时遇到的错误是:
Google_Service_Exception: {
"error": {
"errors": [
{
"domain": "global",
"reason": "required",
"message": "Login Required",
"locationType": "header",
"location": "Authorization"
}
],
"code": 401,
"message": "Login Required"
}
}
in ........./vendor/google/apiclient/src/Google/Http/REST.php:118发布于 2020-01-14 16:21:53
所以我修复了这个bug:我发现我跳过了一个没有在客户端变量上设置访问令牌($client->setAccessToken())的步骤。下面是我所做的:
.....
.....
$client = Helper::getProvider();
$client->setAccessToken([
'access_token' => 'XYZ',
'expires_in' => 3600,
]);
$client->addScope(\Google_Service_Fitness::FITNESS_ACTIVITY_READ);
$service = new \Google_Service_Fitness($client);
$dataSources = $service->users_dataSources;
$dataSets = $service->users_dataSources_datasets;
$listDataSources = $dataSources->listUsersDataSources("me");
.....
.....
.....https://stackoverflow.com/questions/59722031
复制相似问题