php - GoogleFit Google_Service_Exception:401 需要登录
问题描述
我正在尝试使用 google fit API 从 google fit 数据存储中获取先前日期的注册用户的步骤,当我手动运行此解决方案时效果很好,但是一旦我将其插入调度程序以自动运行它就会引发错误. 这是我的代码:
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
解决方案
所以我修复了这个错误:我发现我跳过了一个步骤,我没有$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");
.....
.....
.....
推荐阅读
- javascript - 重新调整窗口大小
- mysql - 迭代数据集并插入 MySQL 表
- java - 为什么我的 Java 程序只返回 ArrayList 中的最后一个字符串
- azure-devops - 如何从持续部署中排除测试项目
- sql - sql server 2017 - 如何创建唯一值并将列与这些相关联
- php - 提取外部网站的 Content-Type 并将 JSON 文件中的值保存为“Null”
- spring-boot - 是否有将 Kafka 数据发送到 AMQP/MQTT 的桥接器?
- google-sheets - 汇总 Google 表格中的合并单元格
- exchangewebservices - 更改的项目 ID 和附件 ID
- git - 如何删除前 N 个提交?