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()
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')
In [36]:
r = oauth.get('https://www.googleapis.com/oauth2/v1/userinfo')
r
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')
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")
In [42]:
token = oauth.fetch_token(
'https://accounts.google.com/o/oauth2/token',
authorization_response=authorization_response,
client_secret=client_secret)
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)
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')
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]:
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']
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)