Service account on Analytics

992 views
Skip to first unread message

Masta

unread,
Aug 30, 2012, 12:29:36 PM8/30/12
to oauth...@googlegroups.com
hi,
I read that "some" Google API services do not allow Service Accounts to connect.
QUESTION: Can we use a service account to connect to Analytics? The documentation ain't so clear to me on that point.

Can you point to the best PHP code implementation of this for a quick start?
thanks for your insight!

Mark Eggers

unread,
Aug 30, 2012, 12:45:39 PM8/30/12
to oauth...@googlegroups.com
Masta,

Google Analytics does work with a service account. You'll need to create one, and then make sure to add the generated email address as a user to your Google Analytics account.

I don't have any PHP code since I write in Java. I've posted in this list on how I obtain the credential with Java. Basically, you have to read the private key and provide the service account email address when building the credential. Set the service account scope to ANALYTICS_READONLY (however you do that in PHP).

Use the created credential in your queries and you should be good to go.

Warning, I'm just writing my first Google Analytics / OAuth2 code, so please investigate before following blindly.

/mde/

Jimmy

unread,
Sep 1, 2012, 6:46:57 AM9/1/12
to oauth...@googlegroups.com
Hello,

  I'm trying to do the same thing !

 I have understood that

1. You must create a project on https://code.google.com/apis/console with a service account.
This operation will give you a client_id, a service account name and a private key.
 (  https://developers.google.com/console/help/#service_accounts )

2. Then, you have to give access to your analytics data for your service account (like XX...@developer.gserviceaccount.com).

3. Finaly, you have to develop a script that authenticate and get your analytics data.

I m blocked in the authentication.
The example located in the page https://code.google.com/p/google-api-php-client/wiki/OAuth2?hl=fr doesnt work on my server.

I got
Fatal error: Uncaught exception 'Google_AuthException' with message 'Error refreshing the OAuth2 token, message: '{
  "error" : "invalid_grant"
}'' in google-api-php-client-read-only/src/auth/Google_OAuth2.php:283

I invite you to try that and tell us if it works !
Does anyone successfully authenticate with a service account in PHP ?

Jimmy

Isaac

unread,
Sep 1, 2012, 6:06:04 PM9/1/12
to oauth...@googlegroups.com
Hi Mark,

I have read that you have some code in java, I am trying to learn OAUTH I have understood till the accessToken, but I have stuck there. Could you please provide me any code that works, please. My email is omeg...@hotmail.com. Many Thanks,

Eric Haskins

unread,
Sep 1, 2012, 7:30:25 PM9/1/12
to oauth...@googlegroups.com

Unless they changed something service accounts do not work with any data that is tied to a user and analytics is one.  You need to use oAuth and get a refresh_token then use that on your system to request an access token before every request

Eric
sent from my Samsung Galaxy S2

--
 
 

ciny

unread,
Sep 3, 2012, 9:56:15 AM9/3/12
to oauth...@googlegroups.com
according to this thread on stackoverflow analytics should now support login using service accounts. However when I tried to implement it following the examples and guide on stackoverflow I wasn't able to get it running 

response:

GoogleJsonResponseException: 403 Forbidden
{
"code" : 403,
"errors" : [ {
"domain" : "global",
"message" : "User does not have permission to perform this operation",
"reason" : "insufficientPermissions"
} ],
"message" : "User does not have permission to perform this operation"
}

I have added the SERVICE_EMAIL as a user to my analytics (tried both user and administrator), checked that I have analytics api enabled and everything checks out. It seems (I presume) I successfully auth against the oauth service but fails to request data from google :/ any idea what the problem might be?  

ciny

unread,
Sep 4, 2012, 11:35:23 AM9/4/12
to oauth...@googlegroups.com
UPDATE:

So I managed to get it working. I was passing the wrong table id to the .get() method. I had to do this

Analytics analytics new Analytics.Builder(HTTP_TRANSPORTJSON_FACTORYcredentials)
.setApplicationName("Google-Analytics")
.build();

println analytics.management().profiles().list("~all","~all").execute()

to find the id in the output of the command above. 

Antonio Saladini

unread,
Sep 4, 2012, 11:59:21 AM9/4/12
to oauth...@googlegroups.com
 I'm trying to run service account for google analytics with php.
The error is invalid_grant and return responseHTTPcode = 400
when I call
$ client-> refreshTokenWithAssertion ($ assertion);

Any idea?

A.

Mark Eggers

unread,
Sep 5, 2012, 2:23:14 PM9/5/12
to oauth...@googlegroups.com
Hi,

I do get a credential, but unfortunately I have an open question about getting and using a refresh token. I cannot seem to determine how much time I have left (it's always null).

I'm using a service account, so what you see below reflects that.

    private static final HttpTransport HTTP_TRANSPORT = new NetHttpTransport();
    private static final JsonFactory JSON_FACTORY = new JacksonFactory();
    private static final String SERVICE_ACCOUNT_EMAIL = "some-email-address";
    private static final String PKI_FILE = ".some-file";

    private static Analytics initializeAnalytics() throws Exception {
        if (log.isInfoEnabled()) {
            log.info("Creating Google Analytics Service Object");
        }
        // Authorization.
        File pki = new File(PKI_FILE);
        if (!pki.canRead()) {
            if (log.isErrorEnabled()) {
                log.error("Cannot read file");
            }
        } else {
            if (log.isInfoEnabled()) {
                log.info("File available at: " + PKI_FILE);
            }
        }
        GoogleCredential credential = new GoogleCredential.Builder().setTransport(HTTP_TRANSPORT)
                .setJsonFactory(JSON_FACTORY)
                .setServiceAccountId(SERVICE_ACCOUNT_EMAIL)
                .setServiceAccountScopes(AnalyticsScopes.ANALYTICS_READONLY)
                // .setServiceAccountPrivateKeyFromP12File(pki)
                .setServiceAccountPrivateKeyFromP12File(new File(App.class.getResource("somewhere-in-the-classpath").toURI()))
                .build();
        // Set up and return Google Analytics API client.
        return new Analytics.Builder(HTTP_TRANSPORT, JSON_FACTORY, credential)
                .setApplicationName("NGAnalytics")
                .build();
    }

You'll need to get a private key, and a service account email address. This is basically what's posted in Mercurial, with some logging and reading the PK file out of a JAR file.

This works fine on the command line.

Once you get the Analytics object, you can get a profile ID, and then do the query. The code from Mercurial works as is. One big help is working from Maven.

I'm now having fun lacing this all together with JSF 2 / Primefaces, and MySQL for some post-processing.

Mark
/mde/

Ketan Dangi

unread,
Sep 10, 2012, 12:15:57 PM9/10/12
to oauth...@googlegroups.com
Hi Mark,

I am trying to built java program which read data from Google Analytics through API using service account method but not able to get the same, can you please send me the Mercurial link  or working sample example for the same. 

Thank you in advance
Ketan

smi

unread,
Sep 13, 2012, 10:10:15 AM9/13/12
to oauth...@googlegroups.com
Hi

We are trying to fetch data from GA.
we tried a lot and got the code, it gives data from GA . For that, it asks me to grant(allow) access manually.
need to have java code without the user being involved to give (allow access) access.

while run the code which we got, it redirects to Request URI and ask me to grant access....

but i need to have automatically authourize itself without user manually grant access.....

anyone know the above.... kindly send the link or source.... and steps to do...

Thank you.
Reply all
Reply to author
Forward
0 new messages