0

I'm trying to build a simple script to import page view counts for articles published via my CMS. I easily constructed my query using the Google Analytics API query builder which quickly returns the desired result. A scheduled job on my web server will run the query once per day and update and page view counts.

Because I'm only pulling in pageviews, I believe it wasn't necessary to go through the entire oAuth process. This Google account has only one web property and only one profile, so there isn't a routine needed to derive that.

I registered an app and created an API key. I have ensured that Google Analytics is turned on for this profile. Based on my reading of the API, I believe I can pass this key as an http parameter to properly authorize the query.

When I run the query via http, I get an authorization error (401). The query is included below:

https://www.googleapis.com/analytics/v3/data/ga?ids=ga%3A[MY ID]&metrics=ga%3Apageviews&start-date=2012-08-09&end-date=2012-08-23&max-results=50&key=[MY API KEY]

I've Googled many examples of this, but they all seemed to implementing a very elaborate (and in my use case unnecessary) authentication routine. But maybe I'm missing something.

Many thanks in advance.

  • Kris, frustrated Googler
ronalchn
  • 12,225
  • 10
  • 51
  • 61
Kris
  • 407
  • 1
  • 5
  • 9

1 Answers1

1

Use this example to fix 401 error http://dumitruglavan.com/ganalytics-class-access-google-analytics-data-api-with-php/

You need to authorize:

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "https://www.google.com/accounts/ClientLogin");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POST, true);

$data = array(
    'accountType' => 'GOOGLE',
    'Email' => $email,
    'Passwd' => $password,
    'service' => 'analytics',
    'source' => ''
);

curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
$output = curl_exec($ch);
$info = curl_getinfo($ch);
curl_close($ch);

$auth = '';
if($info['http_code'] == 200) {
    preg_match('/Auth=(.*)/', $output, $matches);
    if(isset($matches[1])) {
        $auth = $matches[1];
    } else {
        throw new Exception('Login failed with message: ' . $output);
    }
}

And after authorize send authorization token in headers:

$headers = array("Authorization: GoogleLogin auth=$auth");

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
$output = curl_exec($ch);
$info = curl_getinfo($ch);
curl_close($ch);
pirogtm
  • 90
  • 7
  • 1
    Lone link is considered a poor answer (see [faq#deletion]) since it is meaningless by itself and **target resource is not guaranteed to be alive in the future**. [It would be preferable](http://meta.stackexchange.com/q/8259) to include the essential parts of the answer here, and provide the link for reference. – j0k Feb 22 '13 at 09:47
  • Thanks for advise. I improved my answer – pirogtm Feb 22 '13 at 13:21