Jose-Xavier Morin
Jose-Xavier Morin

Reputation: 111

Google Analytics API - oAuth2 authenfication failure

I'm trying to retrieve information from Analytics and Youtube Analytics with little success. I'm using the PHP API.

I've tried to connect with service account and it is working fine.

Unfortunately, I'm forced to use oAuth2 protocol since I have to retrieve data from Youtube Analytics as well and it requires using oAuth2 authentification.

Here is the code I'm using:

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);

Here is the error message:

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"}}'

I've been trying for hours to solve this error, but I can not find why. My first thought was that setAuthConfig does not automatically logged me but I've seen many example on the web using the exact same method, including in the API documentation.

What am I missing?

Thank you a lot for reading and maybe for answering!

Upvotes: 2

Views: 858

Answers (1)

Nick
Nick

Reputation: 3281

Error 401 means

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

You should get a new auth token.

Source

Upvotes: 1

Related Questions