Lenwood
Lenwood

Reputation: 1404

Google Analytics API 401 Invalid Credentials

I'm wracking my brain trying to figure out how to use the Google API PHP Client to access Google Analytics. Specifically, I want to upload cost data from other campaigns. My code does work to get information from GA, I can view traffic data for profiles, but I cannot figure out how to upload.

Here's the code that I'm using for auth:

require_once 'google-api-php-client/src/Google_Client.php';
require_once 'google-api-php-client/src/contrib/Google_AnalyticsService.php';
session_start();

$client = new Google_Client();
$client->setApplicationName("GA-Tester");
$client->setClientId('xxx.apps.googleusercontent.com');
$client->setClientSecret('xxx');
$client->setRedirectUri('http://www.site.com/indext.php');
$client->setDeveloperKey('xxx');

$analyticsService = new Google_AnalyticsService($client);
$dailyUploads = $analyticsService->management_dailyUploads;

if (isset($_GET['logout'])) {
  unset($_SESSION['token']);
}
if (isset($_GET['code'])) {
  $client->authenticate();
  $_SESSION['token'] = $client->getAccessToken();
  $redirect = 'http://' . $_SERVER['HTTP_HOST'] . $_SERVER['PHP_SELF'];
  header('Location: ' . filter_var($redirect, FILTER_SANITIZE_URL));
}
if (isset($_SESSION['token'])) {
  $client->setAccessToken($_SESSION['token']);
}
if (!$client->getAccessToken()) {
  header ('Location:http://www.site.com/indext.php');
} else {...

This code does work for requesting data. I can get a list of accounts, profiles, download traffic data for a specific profile, etc. No errors or issues.

When I try to upload my CSV file containing cost data I get a '401 Invalid Credentials' error. Here's the code that sends the file:

$send = $dailyUploads->upload(
  $accountId,
  $webPropertyId,
  $customDataSourceId,
  $start_date,
  1, 
 'cost',
  array(
   "reset" => true, 
   "data" => $cont,
   "mimeType" => "application/octet-stream", 
   "uploadType" => "media"));

I've double checked all of my variables that I'm passing, they're sending the correct information.

So here's my question. If all of my GET requests work without issue, why would my POST request throw an error? I can't tell if this is an error with my code, or with settings in the API console. Can anyone steer me in the right direction?

EDIT: Here's the error code generated (minus identifiable bits).

Fatal error: Uncaught exception 'Google_ServiceException' with message 
'Error calling POST https://www.googleapis.com/upload/analytics/v3/man
agement/accounts/1234567/webproperties/UA-1234567-1/customDataSources/
xXxXxX/dailyUploads/2013-01-17/uploads?appendNumber=1&type=cost&reset=
true&uploadType=media&key=xXxXxX: (401) Invalid Credentials' in /../pub
lic_html/proj/google-api-php-client/src/io/Google_REST.php:66 Stack tra
ce: #0 /../public_html/proj/google-api-php-client/src/io/Google_REST.ph
p(36): Google_REST::decodeHttpResponse(Object(Google_HttpRequest)) #1 /
../public_html/proj/google-api-php-client/src/service/Google_ServiceRes
ource.php(186): Google_REST::execute(Object(Google_HttpRequest)) #2 /..
/public_html/proj/google-api-php-client/src/contrib/Google_AnalyticsSer
vice.php(82): Google_ServiceResource->__call('upload', Array) #3 /../pu
blic_html/proj/dailyUpload_send.php(60): Google_ManagementDailyUploadsS
erviceResource->upload('1234567', 'UA-1234567-1', 'xXxXxXxXxXxXxXx...',
 ' in /../public_html/proj/google-api-php-client/src/io/Google_REST.php
  on line 66

Upvotes: 2

Views: 7722

Answers (2)

Aldekein
Aldekein

Reputation: 3715

I kept geting this error until I went to Google Console -> APIs & auth -> APIs and turned on this API usage.

Upvotes: 0

Lenwood
Lenwood

Reputation: 1404

I just successfully uploaded cost data for the first time. In trading comments with Nicholas Pickering I came across the documentation for Management API Authorization which states that:

You will get a 401 status code if your access_token has expired or if you are using the wrong scope for the API.

The default for scope is read only, which is why all of my GET requests were working without difficulty, but I couldn't complete any POST requests through the API. I can't remember how I found it, but the way to accomplish this within the PHP client library is to append the following line to the client declaration:

$client->setScopes('https://www.googleapis.com/auth/analytics');

As soon as I added that line to my project, I was able to successfully upload cost data. I'm really glad to have cleared this hurdle. I still have a long way to go to complete my project, but at least I know that it's going to work.

Upvotes: 5

Related Questions