Service Applications and Google Analytics API V3: Server-To-Server Oauth2 Authentication

Service Applications and Google Analytics API V3: Server-to-server OAuth2 authentication?

UPDATE July 21st, 2012

Google Analytics API V3 now supports OAuth2 tokens returned by a .p12-signed JWT request. That is, we can now use the Analytics API w/ service accounts.

Currently pulling 4 years of day-by-day metrics, just for the hell of it.

Here's a quick 'n' dirty step-by-step:

  1. Go to the Google API Console and create a new app

  2. In the Services tab, flip the Google Analytics switch

  3. In the API Access tab, click Create an OAuth2.0 Client ID

    • enter your name, upload a logo, and click Next

    • select the Service account option and press Create client ID

    • download your private key

  4. Now you're back on the API Access page. You'll see a section called Service account with a Client ID and Email address

    • Copy the email address (something like ####@developer.gserviceaccount.com)

    • Visit your GA Admin and add this email as a user to your properties

    • This is a must; you'll get cryptic errors otherwise.

  5. Get the latest Google PHP Client API via Github

    git submodule add https://github.com/google/google-api-php-client.git google-api-php-client-read-only
  6. Rock 'n' roll (thanks all for tips on updated class names):

    // api dependencies
    require_once(PATH_TO_API . 'Google/Client.php');
    require_once(PATH_TO_API . 'Google/Service/Analytics.php');

    // create client object and set app name
    $client = new Google_Client();
    $client->setApplicationName(APP_NAME); // name of your app

    // set assertion credentials
    $client->setAssertionCredentials(
    new Google_Auth_AssertionCredentials(

    APP_EMAIL, // email you added to GA

    array('https://www.googleapis.com/auth/analytics.readonly'),

    file_get_contents(PATH_TO_PRIVATE_KEY_FILE) // keyfile you downloaded

    ));

    // other settings
    $client->setClientId(CLIENT_ID); // from API console
    $client->setAccessType('offline_access'); // this may be unnecessary?

    // create service and get data
    $service = new Google_Service_Analytics($client);
    $service->data_ga->get($ids, $startDate, $endDate, $metrics, $optParams);

 

original workaround below


It seems that, despite ambiguous documentation, most Google APIs do
not support service accounts yet, including Google Analytics. They
cannot digest OAuth2 tokens returned by a .p12 signed JWT request. So,
as of right now, you cannot use Google Analytics API V3 with a
service account
.

Workaround:

  1. In the Google API console, create a client application.

  2. Follow the steps in the Google PHP Client API examples to generate a client_auth_url using your client_id, client_secret,
    and redirect_uri

  3. Login to Google using cURL. (Be sure to use a cookie file!)

  4. Open the client_auth_url in cURL and complete the form. Make sure you set curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 0); and
    curl_setopt($ch, CURLOPT_HEADER, 1); as the authorization_code
    will be in the Location: header of the response.

  5. Using your client_id, client_secret, redirect_uri, and the activation code from Step 4, post a request to the Google's OAuth2
    Token machine. Make sure you include grant_type =
    "authorization_code"
    in your post fields.

  6. Hurray, you now have a refresh_token that never expires, and a working access_token! Post a request to the Google's OAuth2 Token
    machine with your client_id, client_secret, redirect_uri,
    and refresh_token when your access_token expires and you'll get a
    new one.

Server to server OAuth2

have you checked out the OAuth2 package? I've used it for user-authorised calls, and hacked it around a bit to allow it to handle multiple authorisation sources.

I haven't tested it with pure server-to-server comms, but you should be able to hack the transport code to get it to do what it needs...

Google analytics API: what is the difference between a 'service application' and an 'installed application'

service application https://developers.google.com/identity/protocols/OAuth2#serviceaccount.
installed application https://developers.google.com/identity/protocols/OAuth2#installed.

basically it's saying service application is server to server communication and installed application is your mobile/web apps making request to GA through oauth.

Service Applications and Google Analytics API V3: Error 101 (net::ERR_CONNECTION_RESET)

One thing for starters you should change:

You instantiate the AnalyticsService twice. Take out the one you're not using:

$service = new Google_AnalyticsService($client);

See if that helps your problem at all.

Server side authentication for Google Analytics API in PHP

Yes you can use service accounts with the Google analytics reporting api v4. You can use Hello Analytics Reporting API v4; PHP quickstart for service accounts

<?php

// Load the Google API PHP Client Library.
require_once __DIR__ . '/vendor/autoload.php';

$analytics = initializeAnalytics();
$response = getReport($analytics);
printResults($response);

/**
* Initializes an Analytics Reporting API V4 service object.
*
* @return An authorized Analytics Reporting API V4 service object.
*/
function initializeAnalytics()
{

// Use the developers console and download your service account
// credentials in JSON format. Place them in this directory or
// change the key file location if necessary.
$KEY_FILE_LOCATION = __DIR__ . '/service-account-credentials.json';

// Create and configure a new client object.
$client = new Google_Client();
$client->setApplicationName("Hello Analytics Reporting");
$client->setAuthConfig($KEY_FILE_LOCATION);
$client->setScopes(['https://www.googleapis.com/auth/analytics.readonly']);
$analytics = new Google_Service_AnalyticsReporting($client);

return $analytics;
}

/**
* Queries the Analytics Reporting API V4.
*
* @param service An authorized Analytics Reporting API V4 service object.
* @return The Analytics Reporting API V4 response.
*/
function getReport($analytics) {

// Replace with your view ID, for example XXXX.
$VIEW_ID = "<REPLACE_WITH_VIEW_ID>";

// Create the DateRange object.
$dateRange = new Google_Service_AnalyticsReporting_DateRange();
$dateRange->setStartDate("7daysAgo");
$dateRange->setEndDate("today");

// Create the Metrics object.
$sessions = new Google_Service_AnalyticsReporting_Metric();
$sessions->setExpression("ga:sessions");
$sessions->setAlias("sessions");

// Create the ReportRequest object.
$request = new Google_Service_AnalyticsReporting_ReportRequest();
$request->setViewId($VIEW_ID);
$request->setDateRanges($dateRange);
$request->setMetrics(array($sessions));

$body = new Google_Service_AnalyticsReporting_GetReportsRequest();
$body->setReportRequests( array( $request) );
return $analytics->reports->batchGet( $body );
}

/**
* Parses and prints the Analytics Reporting API V4 response.
*
* @param An Analytics Reporting API V4 response.
*/
function printResults($reports) {
for ( $reportIndex = 0; $reportIndex < count( $reports ); $reportIndex++ ) {
$report = $reports[ $reportIndex ];
$header = $report->getColumnHeader();
$dimensionHeaders = $header->getDimensions();
$metricHeaders = $header->getMetricHeader()->getMetricHeaderEntries();
$rows = $report->getData()->getRows();

for ( $rowIndex = 0; $rowIndex < count($rows); $rowIndex++) {
$row = $rows[ $rowIndex ];
$dimensions = $row->getDimensions();
$metrics = $row->getMetrics();
for ($i = 0; $i < count($dimensionHeaders) && $i < count($dimensions); $i++) {
print($dimensionHeaders[$i] . ": " . $dimensions[$i] . "\n");
}

for ($j = 0; $j < count($metrics); $j++) {
$values = $metrics[$j]->getValues();
for ($k = 0; $k < count($values); $k++) {
$entry = $metricHeaders[$k];
print($entry->getName() . ": " . $values[$k] . "\n");
}
}
}
}
}


Related Topics



Leave a reply



Submit