In [21]:
import argparse

from apiclient.discovery import build
from oauth2client.service_account import ServiceAccountCredentials

import httplib2
from oauth2client import client
from oauth2client import file
from oauth2client import tools

service_account_email = "mn-557@mn-test-167313.iam.gserviceaccount.com"
key_file_location = "data/MN_test_key.p12"
scope = "https://www.googleapis.com/auth/analytics"
api_name = "Core Reporting API"
api_version = "3.0"

def get_service(api_name, api_version, scope, key_file_location, service_account_email):
    
    """Get a service that communicates to a Google API.

  Args:
    api_name: The name of the api to connect to.
    api_version: The api version to connect to.
    scope: A list auth scopes to authorize for the application.
    key_file_location: The path to a valid service account p12 key file.
    service_account_email: The service account email address.

    Returns:
    A service that is connected to the specified API.
    """

    credentials = ServiceAccountCredentials.from_p12_keyfile(service_account_email, key_file_location, scopes=scope)

    http = credentials.authorize(httplib2.Http())

    # Build the service object.
    service = build(api_name, api_version, http=http)

    return service

def get_first_profile_id(service):
# Use the Analytics service object to get the first profile id.

  # Get a list of all Google Analytics accounts for this user
    accounts = service.management().accounts().list().execute()

    if accounts.get('items'):
        # Get the first Google Analytics account.
        account = accounts.get('items')[0].get('id')

        # Get a list of all the properties for the first account.
        properties = service.management().webproperties().list(
        accountId=account).execute()

        if properties.get('items'):
        # Get the first property id.
          property = properties.get('items')[0].get('id')

        # Get a list of all views (profiles) for the first property.
          profiles = service.management().profiles().list(
              accountId=account,
              webPropertyId=property).execute()

        if profiles.get('items'):
            # return the first view (profile) id.
            return profiles.get('items')[0].get('id')

    return None

def get_results(service, profile_id):
# Use the Analytics Service Object to query the Core Reporting API
  # for the number of sessions within the past seven days.
    return service.data().ga().get(
      ids='ga:' + profile_id,
      start_date='7daysAgo',
      end_date='today',
      metrics='ga:sessions').execute()

def print_results(results):
# Print data nicely for the user.
    if results:
        print ('View (Profile): %s' % results.get('profileInfo').get('profileName'))
        print ('Total Sessions: %s' % results.get('rows')[0][0])

    else:
        print ('No results found')

def main():
# Define the auth scopes to request.
    scope = ['https://www.googleapis.com/auth/analytics.readonly']

    # Use the developer console and replace the values with your
      # service account email and relative location of your key file.
    service_account_email = '<Replace with your service account email address.>'
    key_file_location = '<Replace with /path/to/generated/client_secrets.p12>'

    # Authenticate and construct service.
    service = get_service('analytics', 'v3', scope, key_file_location, service_account_email)
    profile = get_first_profile_id(service)
    print_results(get_results(service, profile))

if __name__ == '__main__':
    main()


---------------------------------------------------------------------------
OSError                                   Traceback (most recent call last)
<ipython-input-21-31edc39d3692> in <module>()
    101 
    102 if __name__ == '__main__':
--> 103     main()

<ipython-input-21-31edc39d3692> in main()
     96 
     97     # Authenticate and construct service.
---> 98     service = get_service('analytics', 'v3', scope, key_file_location, service_account_email)
     99     profile = get_first_profile_id(service)
    100     print_results(get_results(service, profile))

<ipython-input-21-31edc39d3692> in get_service(api_name, api_version, scope, key_file_location, service_account_email)
     30     """
     31 
---> 32     credentials = ServiceAccountCredentials.from_p12_keyfile(service_account_email, key_file_location, scopes=scope)
     33 
     34     http = credentials.authorize(httplib2.Http())

C:\Users\Analytics\Anaconda3\lib\site-packages\oauth2client\service_account.py in from_p12_keyfile(cls, service_account_email, filename, private_key_password, scopes, token_uri, revoke_uri)
    327             active crypto library.
    328         """
--> 329         with open(filename, 'rb') as file_obj:
    330             private_key_pkcs12 = file_obj.read()
    331         return cls._from_p12_keyfile_contents(

OSError: [Errno 22] Invalid argument: '<Replace with /path/to/generated/client_secrets.p12>'

In [ ]:


In [ ]:


In [38]:
from oauth2client.client import OAuth2Session

client_id = '301497635683-49vo2tj7g3lj5rra1ureggsu7ok3jqk8.apps.googleusercontent.com'
client_secret = 'aPCX8YD0oYxpwYSiAeJ6qbTp'
redirect_uri = 'https://your.callback/uri'

scope = ['https://www.googleapis.com/auth/userinfo.email',
             'https://www.googleapis.com/auth/userinfo.profile']
oauth = OAuth2Session(client_id, redirect_uri=redirect_uri,
                          scope=scope)
authorization_url, state = oauth.authorization_url(
        'https://accounts.google.com/o/oauth2/auth',
        # access_type and approval_prompt are Google specific extra
        # parameters.
        access_type="offline", approval_prompt="force")

#print 'Please go to %s and authorize access.' % authorization_url 
authorization_response = raw_input('Enter the full callback URL')


---------------------------------------------------------------------------
ImportError                               Traceback (most recent call last)
<ipython-input-38-5802085a0a57> in <module>()
----> 1 from oauth2client.client import OAuth2Session
      2 
      3 client_id = '301497635683-49vo2tj7g3lj5rra1ureggsu7ok3jqk8.apps.googleusercontent.com'
      4 client_secret = 'aPCX8YD0oYxpwYSiAeJ6qbTp'
      5 redirect_uri = 'https://your.callback/uri'

ImportError: cannot import name 'OAuth2Session'

In [36]:
r = oauth.get('https://www.googleapis.com/oauth2/v1/userinfo')
r


---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
<ipython-input-36-64e299b32ce2> in <module>()
----> 1 r = oauth.get('https://www.googleapis.com/oauth2/v1/userinfo')
      2 r

NameError: name 'oauth' is not defined

In [53]:
import requests
from requests_oauthlib import OAuth2Session

oauth = OAuth2Session(client_id='615971725291-80293f88sc1iknsg705loom9q4n0b8vq.apps.googleusercontent.com',
                           client_secret='WMkLWDdkJ_hJu2LqgHze7lna',
                           scope='https://www.googleapis.com/auth/analytics',
                           redirect_uri='http://example.com/auth_return')


---------------------------------------------------------------------------
ModuleNotFoundError                       Traceback (most recent call last)
<ipython-input-53-e148fb60fd5a> in <module>()
      1 import requests
----> 2 from requests_oauthlib import OAuth2Session
      3 
      4 oauth = OAuth2Session(client_id='301497635683-49vo2tj7g3lj5rra1ureggsu7ok3jqk8.apps.googleusercontent.com',
      5                            client_secret='aPCX8YD0oYxpwYSiAeJ6qbTp',

ModuleNotFoundError: No module named 'requests_oauthlib'

In [45]:
authorization_url, state = oauth.authorization_url(
        'https://accounts.google.com/o/oauth2/auth',
        # access_type and approval_prompt are Google specific extra
        # parameters.
        access_type="offline", approval_prompt="force")


---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
<ipython-input-45-09b81da45b59> in <module>()
----> 1 authorization_url, state = oauth.authorization_url(
      2         'https://accounts.google.com/o/oauth2/auth',
      3         # access_type and approval_prompt are Google specific extra
      4         # parameters.
      5         access_type="offline", approval_prompt="force")

AttributeError: 'OAuth2WebServerFlow' object has no attribute 'authorization_url'

In [42]:
token = oauth.fetch_token(
        'https://accounts.google.com/o/oauth2/token',
        authorization_response=authorization_response,
        client_secret=client_secret)


---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
<ipython-input-42-2a16cf3a6ed2> in <module>()
----> 1 token = oauth.fetch_token(
      2         'https://accounts.google.com/o/oauth2/token',
      3         authorization_response=authorization_response,
      4         # Google specific extra parameter used for client
      5         # authentication

AttributeError: 'OAuth2WebServerFlow' object has no attribute 'fetch_token'

In [10]:
import requests

# Credentials you get from registering a new application
client_id = '615971725291-80293f88sc1iknsg705loom9q4n0b8vq.apps.googleusercontent.com'
client_secret = 'WMkLWDdkJ_hJu2LqgHze7lna'
redirect_uri = 'http://app.skein.co'

# OAuth endpoints given in the Google API documentation
authorization_base_url = "https://accounts.google.com/o/oauth2/v2/auth"
token_url = "https://www.googleapis.com/oauth2/v4/token"
scope = [
    "https://www.googleapis.com/auth/userinfo.email",
    "https://www.googleapis.com/auth/userinfo.profile",
    "https://www.googleapis.com/auth/analytics"
]

from requests_oauthlib import OAuth2Session
google = OAuth2Session(client_id, scope=scope, redirect_uri=redirect_uri)

# Redirect user to Google for authorization
authorization_url, state = google.authorization_url(authorization_base_url,
     # offline for refresh token
     # force to always make user click authorize
    access_type="offline", approval_prompt="force")
print('Please go here and authorize,', authorization_url)

# Fetch the access token
google.fetch_token(token_url, client_secret=client_secret,)

# Fetch a protected resource, i.e. user profile
r = google.get('https://www.googleapis.com/oauth2/v1/userinfo')
print(r.content)


Please go here and authorize, https://accounts.google.com/o/oauth2/v2/auth?response_type=code&client_id=615971725291-80293f88sc1iknsg705loom9q4n0b8vq.apps.googleusercontent.com&redirect_uri=http%3A%2F%2Fapp.skein.co&scope=https%3A%2F%2Fwww.googleapis.com%2Fauth%2Fuserinfo.email+https%3A%2F%2Fwww.googleapis.com%2Fauth%2Fuserinfo.profile+https%3A%2F%2Fwww.googleapis.com%2Fauth%2Fanalytics&state=sga5UbmzAyH56hps4rMMLVTGjIyNR2&access_type=offline&approval_prompt=force
---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-10-b953484b403b> in <module>()
     26 
     27 # Fetch the access token
---> 28 google.fetch_token(token_url, client_secret=client_secret,)
     29 
     30 # Fetch a protected resource, i.e. user profile

C:\Users\Analytics\Anaconda3\lib\site-packages\requests_oauthlib\oauth2_session.py in fetch_token(self, token_url, code, authorization_response, body, auth, username, password, method, timeout, headers, verify, proxies, **kwargs)
    190             code = self._client.code
    191             if not code:
--> 192                 raise ValueError('Please supply either code or '
    193                                  'authorization_response parameters.')
    194 

ValueError: Please supply either code or authorization_response parameters.

In [ ]:


In [11]:
client_id = '615971725291-80293f88sc1iknsg705loom9q4n0b8vq.apps.googleusercontent.com'
client_secret = 'WMkLWDdkJ_hJu2LqgHze7lna'
redirect_uri = 'http://app.skein.co'

In [12]:
scope = ['https://www.googleapis.com/auth/userinfo.email',
             'https://www.googleapis.com/auth/userinfo.profile']
oauth = OAuth2Session(client_id, redirect_uri=redirect_uri,
                          scope=scope)
authorization_url, state = oauth.authorization_url(
        'https://accounts.google.com/o/oauth2/auth',
        # access_type and approval_prompt are Google specific extra
        # parameters.
        access_type="offline", approval_prompt="force")

print('Please go to %s and authorize access.' % authorization_url)
authorization_response = raw_input('Enter the full callback URL')


Please go to https://accounts.google.com/o/oauth2/auth?response_type=code&client_id=615971725291-80293f88sc1iknsg705loom9q4n0b8vq.apps.googleusercontent.com&redirect_uri=http%3A%2F%2Fapp.skein.co&scope=https%3A%2F%2Fwww.googleapis.com%2Fauth%2Fuserinfo.email+https%3A%2F%2Fwww.googleapis.com%2Fauth%2Fuserinfo.profile&state=6wJM8s5ir7kBHWMmORLvSpAOwdLOE7&access_type=offline&approval_prompt=force and authorize access.
---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
<ipython-input-12-baa5c4c03fac> in <module>()
     10 
     11 print('Please go to %s and authorize access.' % authorization_url)
---> 12 authorization_response = raw_input('Enter the full callback URL')

NameError: name 'raw_input' is not defined

In [23]:
import requests
from requests_oauthlib import OAuth1

url="https://www.googleapis.com/analytics/v3/data/ga?ids=ga%3A93735856&start-date=2017-04-04&end-date=2017-04-20&metrics=ga%3Asessions&dimensions=ga%3Adate" 
auth=OAuth1('615971725291-80293f88sc1iknsg705loom9q4n0b8vq.apps.googleusercontent.com', 'WMkLWDdkJ_hJu2LqgHze7lna')

r = requests.get(url, auth=auth)

r.json()


Out[23]:
{'error': {'code': 401,
  'errors': [{'domain': 'global',
    'location': 'Authorization',
    'locationType': 'header',
    'message': 'Invalid Credentials',
    'reason': 'authError'}],
  'message': 'Invalid Credentials'}}

In [ ]:


In [30]:
client_id = '615971725291-80293f88sc1iknsg705loom9q4n0b8vq.apps.googleusercontent.com'
client_secret = 'WMkLWDdkJ_hJu2LqgHze7lna'
token = 'ya29.GltHBEer6RL1iLcOoFYk7Qb_xt8S_XUFZuHVbfio3iro0x9yAWHrMZwwrEHlvfv4g9ea0nBuwcsvcMxfIXEvz5g8UcIbyEjEPN7x8sBERQXvS8bhKdciYLFSZlOW'

In [31]:
from oauth2client import client, crypt

# (Receive token by HTTPS POST)


try:
    idinfo = client.verify_id_token(token, client_id)

    # Or, if multiple clients access the backend server:
    #idinfo = client.verify_id_token(token, None)
    #if idinfo['aud'] not in [CLIENT_ID_1, CLIENT_ID_2, CLIENT_ID_3]:
    #    raise crypt.AppIdentityError("Unrecognized client.")

    if idinfo['iss'] not in ['accounts.google.com', 'https://accounts.google.com']:
        raise crypt.AppIdentityError("Wrong issuer.")

    # If auth request is from a G Suite domain:
    #if idinfo['hd'] != GSUITE_DOMAIN_NAME:
    #    raise crypt.AppIdentityError("Wrong hosted domain.")
except crypt.AppIdentityError:
    # Invalid token
    userid = idinfo['sub']


---------------------------------------------------------------------------
AppIdentityError                          Traceback (most recent call last)
<ipython-input-31-142225f5a4e6> in <module>()
      6 try:
----> 7     idinfo = client.verify_id_token(token, client_id)
      8 

C:\Users\Analytics\Anaconda3\lib\site-packages\oauth2client\_helpers.py in positional_wrapper(*args, **kwargs)
    132                     logger.warning(message)
--> 133             return wrapped(*args, **kwargs)
    134         return positional_wrapper

C:\Users\Analytics\Anaconda3\lib\site-packages\oauth2client\client.py in verify_id_token(id_token, audience, http, cert_uri)
   1551         certs = json.loads(_helpers._from_bytes(content))
-> 1552         return crypt.verify_signed_jwt_with_certs(id_token, certs, audience)
   1553     else:

C:\Users\Analytics\Anaconda3\lib\site-packages\oauth2client\crypt.py in verify_signed_jwt_with_certs(jwt, certs, audience)
    227         raise AppIdentityError(
--> 228             'Wrong number of segments in token: {0}'.format(jwt))
    229 

AppIdentityError: Wrong number of segments in token: b'ya29.GltHBEer6RL1iLcOoFYk7Qb_xt8S_XUFZuHVbfio3iro0x9yAWHrMZwwrEHlvfv4g9ea0nBuwcsvcMxfIXEvz5g8UcIbyEjEPN7x8sBERQXvS8bhKdciYLFSZlOW'

During handling of the above exception, another exception occurred:

NameError                                 Traceback (most recent call last)
<ipython-input-31-142225f5a4e6> in <module>()
     20 except crypt.AppIdentityError:
     21     # Invalid token
---> 22     userid = idinfo['sub']

NameError: name 'idinfo' is not defined

In [ ]:


In [26]:
from oauthlib.oauth2 import BackendApplicationClient

client = BackendApplicationClient(client_id=client_id)
oauth = OAuth2Session(client=client)
token = oauth.fetch_token(token_url='https://accounts.google.com/o/oauth2/auth', client_id=client_id, client_secret=client_secret)


---------------------------------------------------------------------------
MissingTokenError                         Traceback (most recent call last)
<ipython-input-26-0462c6667e40> in <module>()
      2 client = BackendApplicationClient(client_id=client_id)
      3 oauth = OAuth2Session(client=client)
----> 4 token = oauth.fetch_token(token_url='https://accounts.google.com/o/oauth2/auth', client_id=client_id, client_secret=client_secret)

C:\Users\Analytics\Anaconda3\lib\site-packages\requests_oauthlib\oauth2_session.py in fetch_token(self, token_url, code, authorization_response, body, auth, username, password, method, timeout, headers, verify, proxies, **kwargs)
    242             r = hook(r)
    243 
--> 244         self._client.parse_request_body_response(r.text, scope=self.scope)
    245         self.token = self._client.token
    246         log.debug('Obtained token %s.', self.token)

C:\Users\Analytics\Anaconda3\lib\site-packages\oauthlib\oauth2\rfc6749\clients\base.py in parse_request_body_response(self, body, scope, **kwargs)
    407         .. _`Section 7.1`: http://tools.ietf.org/html/rfc6749#section-7.1
    408         """
--> 409         self.token = parse_token_response(body, scope=scope)
    410         self._populate_attributes(self.token)
    411         return self.token

C:\Users\Analytics\Anaconda3\lib\site-packages\oauthlib\oauth2\rfc6749\parameters.py in parse_token_response(body, scope)
    374 
    375     params = OAuth2Token(params, old_scope=scope)
--> 376     validate_token_parameters(params)
    377     return params
    378 

C:\Users\Analytics\Anaconda3\lib\site-packages\oauthlib\oauth2\rfc6749\parameters.py in validate_token_parameters(params)
    384 
    385     if not 'access_token' in params:
--> 386         raise MissingTokenError(description="Missing access token parameter.")
    387 
    388     if not 'token_type' in params:

MissingTokenError: (missing_token) Missing access token parameter.