I wanted to fetch visitors and page views by month for the past year for our website, and quickly found the Net::Google::Analytics module. It and Net::Google::AuthSub installed easily. However, the snippet in the synopsis did not compile ($i was undefined) and was obviously missing a loop over the retrieved data. Anyway, here is a working snippet that retrieves and formats some data for easy loading into a spreadsheet.
The hardest thing for me was getting the correct profile number. I thought it was the number in the web page code that looked like UA-191234-1, but it's not. You have to go to account settings and thenedit the profile of the web site to see the magic number - it's the "Profle ID:" at the top of the page.
# Fetch some Google Analytics data
use strict;
use warnings;
use Net::Google::Analytics;
use Net::Google::AuthSub;
my $user = 'you@gmail.com'; # your account user id here
my $pass = 'xxxxxx'; # your password here!
my $profile = '14883391';
my $start_date = '2010-10-01';
my $end_date = '2011-09-30';
# Login
my $auth = Net::Google::AuthSub->new(service => 'analytics');
my $response = $auth->login($user, $pass);
if (!$response->is_success) {
die 'Login failed: ' . $response->error . "\n";
}
# Datafeed request
my $analytics = Net::Google::Analytics->new();
$analytics->auth_params($auth->auth_params);
my $data_feed = $analytics->data_feed;
my $req = $data_feed->new_request();
$req->ids("ga:$profile");
$req->dimensions('ga:year,ga:month,ga:visitorType');
$req->metrics('ga:visits,ga:pageviews');
$req->start_date($start_date);
$req->end_date($end_date);
my $res = $data_feed->retrieve($req);
if (($res->{is_success} || 0) ne 1) {
die "Lookup failed\n";
}
# Print tab separated header line
my $entry = $res->entries->[0];
for my $dimension (@{$entry->dimensions}) {
my $name = $dimension->name;
$name =~ s/^ga\://;
print "$name\t";
}
for my $metric (@{$entry->metrics}) {
my $name = $metric->name;
$name =~ s/^ga\://;
print "$name\t";
}
print "\n";
# Print tab separated values
for my $entry (@{$res->entries}) {
for my $dimension (@{$entry->dimensions}) {
my $value = $dimension->value;
print "$value\t";
}
for my $metric (@{$entry->metrics}) {
my $value = $metric->value;
print "$value\t";
}
print "\n";
}
exit 1;