handle server to server auth
Using google JWT.
i.e. in node js googleapis it works like that:
var google = require('googleapis');
var analytics = google.analytics({
version: 'v3'
});
var jwtClient = new google.auth.JWT(
config.ga.client_email,
null,
config.ga.private_key, ['https://www.googleapis.com/auth/analytics.readonly'],
null)
Then you can access your data as follow:
analytics.get({
'ids': 'ga:123456789',
'start-date': timestamp_start,
'end-date': timestamp_start,
'metrics': 'ga:sessions',
'dimensions': 'ga:socialActivityContentUrl',
'sort': '-ga:sessions',
'max-results': 10000,
auth: jwtClient
})
Therefore, you only need an email and private key and it does the rest for you (no need to auth via a webpage).
I'm aiming to use the googleAnalyticsR package as the back-end API client for ganalytics. This will offer added benefits from that package including service account authentication.
@MarkEdmondson1234 and @zippeurfou , now that ganalytics is becoming more closely integrated with googleAnalyticsR, I think looking for ways to incorporate support for googleAuthR into ganalytics would be a sensible next step. It would be great to get your help with that.
The token created is the same as via httr, just via the gar_service_auth() function - http://code.markedmondson.me/googleAuthR/reference/gar_auth_service.html
The dev branch now has support for service account authentication. Here is a link to the commit with the necessary changes: https://github.com/jdeboer/ganalytics/commit/4fb97382fe207e8bf7af14751ce0f6a4ac3a7e12
I'll merge this into the master branch at some later point as I may be making some further improvements around this.
Here's a demo, if you would like to test it out, of using a service account to access the Real Time reporting API:
# It is recommended that you restart your R session before continuing with
# the following.
# Install the dev version of ganalytics from GitHub - be patient as this may
# take around 5 minutes to complete.
install.packages("remotes")
remotes::install_github("jdeboer/ganalytics@dev")
# Load ganalytics
library(ganalytics)
# Set credentials - remember to change the secrets filepath to your own service
# account secrets json file. You should obtain this file from the API credentials
# manager in Google Cloud Conosle.
creds <- GoogleApiCreds(secrets = "~/api-service-account-secrets.json")
# Define your query - remember to set the view ID to your Google Analytics view
# that you want to query.
my_rt_query <- RtQuery(
view = 117987738,
metrics = "activeUsers",
dimensions = "userType"
)
# As the GA Real Time API is still in limited beta, you need to sign up for
# access via this form before you execute your query:
# https://docs.google.com/forms/d/1qfRFysCikpgCMGqgF3yXdUyQW4xAlLyjKuOoOEFN2Uw/viewform
# Execute the query with the supplied credentials.
GetGaData(my_rt_query, creds = creds)