UMA MAHESWAR
UMA MAHESWAR

Reputation: 177

access_token for Google Analytics API

I want to get a access_token to get information from Google Analytics API by passing it in the browser . I am not able to find the correct documentation anywhere. I have tried multiple ways but nothing seems to work. As of now, I got tokens via Google Analytics Query Explorer and it works for 60 minutes. I am looking for a permanent token or a token which is valid for a more period of time.

Upvotes: 1

Views: 1769

Answers (1)

Linda Lawton - DaImTo
Linda Lawton - DaImTo

Reputation: 116958

In order to access private Google analytics data you need to be authorized. In order to be authorized you use something called Oauth2

The initial request will look something like this. It will allow the user to consent to your applications access to their data

GET https://accounts.google.com/o/oauth2/auth?client_id={clientid}.apps.googleusercontent.com&redirect_uri=urn:ietf:wg:oauth:2.0:oob&scope=https://www.googleapis.com/auth/analytics.readonly&response_type=code

Once the user has consented to your accessing their data, you will be given an authorization code.

Once you have the authorization code you can exchange it for an access token. This is a http post request.

POST https://accounts.google.com/o/oauth2/token
code=4/X9lG6uWd8-MMJPElWggHZRzyFKtp.QubAT_P-GEwePvB8fYmgkJzntDnaiAI&client_id={ClientId}.apps.googleusercontent.com&client_secret={ClientSecret}&redirect_uri=urn:ietf:wg:oauth:2.0:oob&grant_type=authorization_code

The response should then look something like this.

{
"access_token" : "ya29.1.AADtN_VSBMC2Ga2lhxsTKjVQ_ROco8VbD6h01aj4PcKHLm6qvHbNtn-_BIzXMw",
"token_type" : "Bearer",
"expires_in" : 3600,
"refresh_token" : "1/J-3zPA8XR1o_cXebV9sDKn_f5MTqaFhKFxH-3PUPiJ4"
}

The access token will work for one hour.

I recommend looking for a sample and a client library in your chosen programming language so that you dont have to do all this manually most of the libraries are designed to handle authentication and authorization for you.

Upvotes: 2

Related Questions