Sivabalan
Sivabalan

Reputation: 1131

How to show google analytics of my website in my backend

I want to show my google analytics on my admin panel. I have followed the google analytics api . I created service side authorization and downloaded the json data

{
    "type": "service_account",
    "project_id": "xxxx",
    "private_key_id": "xxxxxxxxxxxxxxxxx",
    "private_key": "-----BEGIN PRIVATE KEY-----xxxxxxxxx-----END PRIVATE KEY-----\n",
     "client_email": "xxxxxxxxxxxxxx",
     "client_id": "xxxxxxxxxxxxxxx",
     "auth_uri": "https://accounts.google.com/o/oauth2/auth",
     "token_uri": "https://accounts.google.com/o/oauth2/token",
     "auth_provider_x509_cert_url":"https://www.googleapis.com/oauth2/v1/certs",
     "client_x509_cert_url":"xxxxxx"
}

After creating above json and copied js code mentioned in that tutorial.

In the js code its asked for the

   gapi.analytics.auth.authorize({
      'serverAuth': {
      'access_token': '{{ ACCESS_TOKEN_FROM_SERVICE_ACCOUNT }}'
      }
   });

Here the problem is i can't find the ACCESS_TOKEN. I just replaced with private key, client id, private key id and tried but it shows 401 error.

May be its silly problem. but i don't know how to get this. Please someone help me.

Upvotes: 3

Views: 1066

Answers (2)

Matt
Matt

Reputation: 5168

Unfortunatly you skipped step 3 from the linked documentation.

Step 3: Use the JSON key data to request an access token

The access token is obtained from running the python code:

# service-account.py

import json
from oauth2client.client import SignedJwtAssertionCredentials

# The scope for the OAuth2 request.
SCOPE = 'https://www.googleapis.com/auth/analytics.readonly'

# The location of the key file with the key data.
KEY_FILEPATH = 'path/to/json-key.json'

# Load the key file's private data.
with open(KEY_FILEPATH) as key_file:
  _key_data = json.load(key_file)

# Construct a credentials objects from the key data and OAuth2 scope.
_credentials = SignedJwtAssertionCredentials(
    _key_data['client_email'], _key_data['private_key'], SCOPE)

# Defines a method to get an access token from the credentials object.
# The access token is automatically refreshed if it has expired.
def get_access_token():
  return _credentials.get_access_token().access_token

The example you have linked to is opensource and this method is called on the server side and the access token is returned through a web application template variable.

Upvotes: 0

crmpicco
crmpicco

Reputation: 17181

Did you call getAuthResponse? This method returns the access token which you need to use.

getAuthResponse()

Returns: Object

Gets authentication data returned by the original authorization request. The returned object includes the access token, which can be usually to manually make authenticated requests.

See here https://developers.google.com/analytics/devguides/reporting/embed/v1/component-reference?hl=en

Upvotes: 1

Related Questions