Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

OAuth 2.0 with Google Analytics API v3

I used to be able to query the Google Analytics API with my account's login & password. Google is now using OAuth for authentication which is great... The only issue is that I only need ONE access token. I don't wanna allow other users to fetch THEIR analytics data.

I just wanna be able to fetch MY data. Is there a way I can generate an access token only for my app or my analytics account?

I know such solutions exists... For instance, Twitter provides what they call a "single-user oauth" for apps that don't require a specific user to sign in.

One again, all I'm trying to accomplish here is to fetch MY OWN analytics data via the API.

Is there a way to properly do that?

like image 840
lpdahito Avatar asked Apr 07 '12 20:04

lpdahito


People also ask

How does OAuth 2.0 work in REST API?

In OAuth 2.0, the following three parties are involved: The user, who possesses data that is accessed through the API and wants to allow the application to access it. The application, which is to access the data through the API on the user's behalf. The API, which controls and enables access to the user's data.

What is difference between OAuth and OAuth2?

OAuth 2.0 promises to simplify things in following ways: Once the token was generated, OAuth 1.0 required that the client send two security tokens on every API call, and use both to generate the signature. OAuth 2.0 has only one security token, and no signature is required.


4 Answers

I'm adding a PHP answer - you may be able to adjust or convert it to garb / ruby code.

You should be able to use Analytics with service accounts now. You will indeed have to use a private key instead of an access token.

Create an app in the API Console
Basically, you go to the Google API Console and create an App.
Enable Google Analytics in the services tab.
In the API Access tab, create a new OAuth ID (Create another client ID... button), select service account and download your private key (Generate new key... link). You'll have to upload the key to your web server later.

On the API Access page, in the Service account section, copy the email address (@developer.gserviceaccount.com) and add a new user with this email address to your Google Analytics profile. If you do not do this, you'll get some nice errors

Code
Download the latest Google PHP Client off SVN (from the command line svn checkout http://google-api-php-client.googlecode.com/svn/trunk/ google-api-php-client-read-only).

You can now access the Analytics API in code:

require_once 'Google_Client.php';              
require_once 'contrib/Google_AnalyticsService.php';

$keyfile = 'dsdfdss0sdfsdsdfsdf44923dfs9023-privatekey.p12';

// Initialise the Google Client object
$client = new Google_Client();
$client->setApplicationName('Your product name');

$client->setAssertionCredentials(
    new Google_AssertionCredentials(
        '[email protected]',
        array('https://www.googleapis.com/auth/analytics.readonly'),
        file_get_contents($keyfile)
    )
);

// Get this from the Google Console, API Access page
$client->setClientId('11122233344.apps.googleusercontent.com');
$client->setAccessType('offline_access');
$analytics = new Google_AnalyticsService($client);

// We have finished setting up the connection,
// now get some data and output the number of visits this week.

// Your analytics profile id. (Admin -> Profile Settings -> Profile ID)
$analytics_id   = 'ga:1234';
$lastWeek       = date('Y-m-d', strtotime('-1 week'));
$today          = date('Y-m-d');

try {
    $results = $analytics->data_ga->get($analytics_id,
                        $lastWeek,
                        $today,'ga:visits');
    echo '<b>Number of visits this week:</b> ';
    echo $results['totalsForAllResults']['ga:visits'];
} catch(Exception $e) {
    echo 'There was an error : - ' . $e->getMessage();
}
like image 177
Terry Seidler Avatar answered Oct 18 '22 19:10

Terry Seidler


Terry Seidler answered this nicely for php. I want to add a java code example.

Api console setup

Start by doing the required steps in the google api console as Terry explained:

Basically, you go to the Google API Console and create an App. Enable Google Analytics in the services tab. In the API Access tab, create a new OAuth ID (Create another client ID... button), select service account and download your private key (Generate new key... link). You'll have to upload the key to your web server later. On the API Access page, in the Service account section, copy the email address (@developer.gserviceaccount.com) and add a new user with this email address to your Google Analytics profile. If you do not do this, you'll get some nice errors

Get the necessary libraries

Download the google analytics java client from: https://developers.google.com/api-client-library/java/apis/analytics/v3

Or add the following maven dependencies:

    <dependency>
        <groupId>com.google.apis</groupId>
        <artifactId>google-api-services-analytics</artifactId>
        <version>v3-rev94-1.18.0-rc</version>
    </dependency>
    <dependency>
        <groupId>com.google.http-client</groupId>
        <artifactId>google-http-client-jackson</artifactId>
        <version>1.18.0-rc</version>
    </dependency>

Now for the code:

public class HellowAnalyticsV3Api {

private static final HttpTransport HTTP_TRANSPORT = new NetHttpTransport();
private static final JsonFactory JSON_FACTORY = new JacksonFactory();

public void analyticsExample() {

    // This is the .p12 file you got from the google api console by clicking generate new key
    File analyticsKeyFile = new File(<p12FilePath>);

    // This is the service account email address that you can find in the api console
    String apiEmail = <[email protected]>;

    GoogleCredential credential = new GoogleCredential.Builder()
        .setTransport(HTTP_TRANSPORT)
        .setJsonFactory(JSON_FACTORY)
        .setServiceAccountId(apiEmail)
        .setServiceAccountScopes(Arrays.asList(AnalyticsScopes.ANALYTICS_READONLY))
        .setServiceAccountPrivateKeyFromP12File(analyticsPrivateKeyFile).build();

    Analytics analyticsService = new Analytics.Builder(HTTP_TRANSPORT, JSON_FACTORY, credential)
        .setApplicationName(<your application name>)
        .build();


    String startDate = "2014-01-03";
    String endDate = "2014-03-03";
    String mertrics = "ga:sessions,ga:timeOnPage";

    // Use the analytics object build a query
    Get get = analyticsService.data().ga().get(tableId, startDate, endDate, mertrics);
    get.setDimensions("ga:city");
    get.setFilters("ga:country==Canada");
    get.setSort("-ga:sessions");

    // Run the query
    GaData data = get.execute();

    // Do something with the data
    if (data.getRows() != null) {
        for (List<String> row : data.getRows()) {
            System.out.println(row);
        }
    }

}
like image 25
brafdlog Avatar answered Oct 18 '22 18:10

brafdlog


You can use a refresh token. Store the refresh token in a db or secure config file, then use it to show the stats.

Google API Offline Access Using OAuth 2.0 Refresh Token will give you an idea of how to capture then store your refresh token.

See also Using OAuth 2.0 for Web Server Applications - Offline Access

like image 3
jk. Avatar answered Oct 18 '22 20:10

jk.


Hello I found a solution, it works for me

you have to change this one

immediate: true 

to

immediate: false

and it looks like

function checkAuth() {
  gapi.auth.authorize({
    client_id: clientId, scope: scopes, immediate: false}, handleAuthResult);
}
like image 1
AlohaCC Avatar answered Oct 18 '22 20:10

AlohaCC