GoogleFit Google_Service_Exception: 401 Требуется вход в систему - PullRequest
0 голосов
/ 13 января 2020

Я пытаюсь получить сведения о зарегистрированных пользователях на предыдущую дату из хранилища данных 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

1 Ответ

0 голосов
/ 14 января 2020

Итак, я исправил ошибку: я обнаружил, что пропустил шаг, на котором не установил токен доступа ($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");
     .....
     .....
     .....
...