Google 分析 API - oAuth2 身份验证失败

Google Analytics API - oAuth2 authenfication failure

我正在尝试从 Analytics 和 Youtube Analytics 检索信息,但收效甚微。我正在使用 PHP API.

我已尝试连接服务帐户,但一切正常。

不幸的是,我不得不使用 oAuth2 协议,因为我还必须从 Youtube Analytics 检索数据,并且它需要使用 oAuth2 身份验证。

这是我使用的代码:

require_once 'vendor/autoload.php';

// create the client and connect
$client = new Google_Client();
$client->setAuthConfig('client_secrets.json');
$client->setScopes(['https://www.googleapis.com/auth/analytics.readonly']);

// send the query
$service = new Google_Service_Analytics($client);
$id = 'ga:XXXXXX';
$start_date = '2016-09-01';
$end_date = '2016-09-10';
$metrics = 'ga:visitors';
$data = $service->data_ga->get($id, $start_date, $end_date, $metrics);

错误信息如下:

Fatal error: Uncaught exception 'Google_Service_Exception' with message '{"error":{"errors":[{"domain":"global","reason":"required","message":"Login Required","locationType":"header","location":"Authorization"}],"code":401,"message":"Login Required"}}'

我已经尝试了几个小时来解决这个错误,但我找不到原因。我的第一个想法是 setAuthConfig 不会自动记录我,但我在网上看到很多使用完全相同方法的示例,包括在 API 文档中。

我错过了什么?

非常感谢您的阅读和回答!

错误401表示

Invalid Credentials Indicates that the auth token is invalid or has expired.

您应该获得一个新的授权令牌。

Source