The Perl Toolchain Summit needs more sponsors. If your company depends on Perl, please support this very important event.

NAME

Net::Google::Analytics - Simple interface to the Google Analytics Core Reporting API

VERSION

version 3.05

SYNOPSIS

    use Net::Google::Analytics;
    use Net::Google::Analytics::OAuth2;

    # Insert your numeric Analytics profile ID here. You can find it under
    # profile settings. DO NOT use your account or property ID (UA-nnnnnn).
    my $profile_id    = "1234567";

    # See GETTING STARTED for how to get a client id, client secret, and
    # refresh token
    my $client_id     = "123456789012.apps.googleusercontent.com";
    my $client_secret = "rAnDoMsEcReTrAnDoMsEcReT";
    my $refresh_token = "RaNdOmSeCrEtRaNdOmSeCrEt";

    my $analytics = Net::Google::Analytics->new;

    # Authenticate
    my $oauth = Net::Google::Analytics::OAuth2->new(
        client_id     => $client_id,
        client_secret => $client_secret,
    );
    my $token = $oauth->refresh_access_token($refresh_token);
    $analytics->token($token);

    # Build request
    my $req = $analytics->new_request(
        ids         => "ga:$profile_id",
        dimensions  => "ga:medium,ga:source",
        metrics     => "ga:bounces,ga:visits",
        filters     => "ga:medium==referral",
        sort        => "-ga:visits",
        start_date  => "2011-10-01",
        end_date    => "2011-10-31",
        max_results => 5,
    );

    # Send request
    my $res = $analytics->retrieve($req);
    die("GA error: " . $res->error_message) if !$res->is_success;

    # Print results

    print
        "Results: 1 - ", $res->num_rows,
        " of ", $res->total_results, "\n\n";

    for my $row (@{ $res->rows }) {
        print
            $row->get_source,  ": ",
            $row->get_visits,  " visits, ",
            $row->get_bounces, " bounces\n";
    }

    print
        "\nTotal: ",
        $res->totals("visits"),  " visits, ",
        $res->totals("bounces"), " bounces\n";

DESCRIPTION

This module provides a simple, straight-forward interface to the Google Analytics Core Reporting API, Version 3.

See http://code.google.com/apis/analytics/docs/gdata/home.html for the complete API documentation.

WARNING: This module is not API compatible with the 0.x releases which target the legacy v2 API.

GETTING STARTED

This module uses Google Analytics' API from a single Google User Account. This means you will need a Google account user that has (at least) read access to the Google Analytics profile you want to query. What we'll do is, through OAuth2, have that user grant Analytics access to your Perl app.

First, you have to register your project through the Google Developers Console.

Next, on your project's API Manager page, go over to "credentials" and click on the "Create credentials" button. When the drop down menu appears, click on "Help me choose".

screenshot of Google's API Manager menu

Select "Analytics API" under "Which API are you using?", and select "Other UI (CLI)" under "Where will you be calling the API from?". Finally, when they ask you "What data will you be accessing?", choose "User data".

screenshot of Google's API options

At the end of this process, you will receive a client id and a client secret for your application in the API Manager Console.

The final step is to get a refresh token. This is required because OAuth access is granted only for a limited time, and the refresh token allows your app to renew that access whenever it needs.

You can obtain a refresh token for your application by running the following script with your client id and secret:

    use Net::Google::Analytics::OAuth2;

    my $oauth = Net::Google::Analytics::OAuth2->new(
        client_id     => 'Your client id',
        client_secret => 'Your client secret',
    );

    $oauth->interactive;

The script will display a URL and prompt for a code. Visit the URL in a browser and follow the directions to grant access to your application. You will be shown the code that you should enter in the Perl script. Then the script retrieves and prints a refresh token which can be used for non-interactive access.

You also have to provide the view ID (formerly profile ID) of your Analytics view with every request. You can find this decimal number under "Admin > View Settings" in Google Analytics. Note that this ID is different from your tracking ID of the form UA-nnnnnn-n. Prepend your view ID with "ga:" and pass it as "ids" parameter to the request object.

The "ids", "metrics", "start_date", and "end_date" parameters are required for every request.

For the exact parameter syntax and a list of supported dimensions and metrics you should consult the Google API documentation.

CONSTRUCTOR

new

    my $analytics = Net::Google::Analytics->new;

The constructor doesn't take any arguments.

METHODS

auth_params

    $analytics->auth_params(@auth_params);

Set the raw authentication parameters as key/value pairs. These will we sent as HTTP headers.

token

    $analytics->token($token);

Authenticate using a token returned from Net::Google::Analytics::OAuth2.

new_request

    my $req = $analytics->new_request(param => $value, ...);

Creates and returns a new Net::Google::Analytics::Request object.

retrieve

    my $res = $analytics->retrieve($req);

Sends the request. $req must be a Net::Google::Analytics::Request object. This method returns a Net::Google::Analytics::Response object.

retrieve_http

    my $res = $analytics->retrieve_http($req);

Sends the request and returns an HTTP::Response object. $req must be a Net::Google::Analytics::Request object.

retrieve_paged

    my $res = $analytics->retrieve_paged($req);

Works like retrieve but works around the max-results limit. This method concatenates the results of multiple requests if necessary.

uri

    my $uri = $analytics->uri($req);

Returns the URI of the request. $req must be a Net::Google::Analytics::Request object. This method returns a URI object.

user_agent

    $analytics->user_agent($ua);

Sets the LWP::UserAgent object to use for HTTP(S) requests. You only have to call this method if you want to provide your own user agent.

AUTHOR

Nick Wellnhofer <wellnhofer@aevum.de>

COPYRIGHT AND LICENSE

This software is copyright (c) 2016 by Nick Wellnhofer.

This is free software; you can redistribute it and/or modify it under the same terms as the Perl 5 programming language system itself.