Requirements
- A Displayr document.
- A Google service account with a JSON credentials file.
- The Google Property ID of the website you want to monitor using Google Analytics 4, found in your Google Analytics account under Admin > Property Settings > Property Details > Property ID.
Please note these steps require a Displayr license.
Method - Set up your Google Service account
A. Create a New Google Service account
If you have never used the Google Analytics API before then you will need to first set up a Google Service account. To do this:
- Go to the Google service accounts page.
- Select Create Project to start setting up your Google Cloud Platform project if you do not already have one.
- Give it a suitable project name then press Create again. You will be given a unique project account ID
- Click on the 3 bars to expand the Google Cloud menu () and go to APIs and Services > Enabled APIs & services.
- Type "Google Analytics" in the search bar and click on the box for Google Analytics Reporting API.
- Click Enable.
Now that the API has been enabled for this project, we need to set up the service account and JSON key:
- Click Credentials on the left pane (it will look like a key).
- Click CREATE CREDENTIALS > Service account.
- Select New service account, give it an appropriate name and assign the role (e.g. Project > Owner).
- Ensure JSON is selected for the Key type and press Create.
The JSON file will now be downloaded to your browser.
B. Use an existing Google Service account
If you already have an existing Google Service account then the following section applies.
- Go to the Google service accounts page.
- Click Select.
- Choose your project.
- Click the icon under the Actions column for your service account and select Create Key.
- In the next window, make sure the Key type is JSON and click Create.
The JSON file will now be downloaded to your browser.
C. Give permission to the Service account email address
The service account we created will also provide an email address linked to your project ID which will appear in this format: xxxx@yyyyyy.iam.gserviceaccount.com. In order for access to work via this service account, you'll need to add the generated email address to your Google Analytics account as a user with appropriate access to view the data. To do this:
- Log in to your Google Analytics account.
- Go to Admin > Property Settings > Property Access Management.
- Click the Plus (+) button and select Add users.
- Enter the email address for your service account.
- Ensure you've ticked Viewer for this email address.
- Click Add.
Method - Set up your API call
A. Authentication
1. In Displayr, select Data Sets > Plus (+) > R or Calculation > Custom Code depending on whether you wish to store your data as a data set or just use it as a calculation within your document. Note, that the latter option allows for troubleshooting.
2. If using the data set option, enter a Name.
3. Paste in the below R code but replace the 12 lines of code below secret.txt = ' with the contents of the JSON file that you downloaded previously. Be sure to keep the braces ({}) and single quotation marks as per the example.
library(googleAuthR)
scope = "https://www.googleapis.com/auth/analytics.readonly"
secret.txt = '
{
"type": "service_account",
"project_id": "XXXXX",
"private_key_id": "XXXXXX",
"private_key": "-----BEGIN PRIVATE KEY-----XXXXXXX-----END PRIVATE KEY-----",
"client_email": "XXXXXX.iam.gserviceaccount.com",
"client_id": "XXXXXX",
"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": "https://www.googleapis.com/robot/v1/metadata/x509/XXXXXX.iam.gserviceaccount.com"
}'
secrets = jsonlite::fromJSON(gsub("\n", "", secret.txt))
secrets
endpoint = httr::oauth_endpoints("google")
secrets$private_key = gsub("-----BEGIN PRIVATE KEY-----", "-----BEGIN PRIVATE KEY-----\n", secrets$private_key)
secrets$private_key = gsub("-----END PRIVATE KEY-----", "\n-----END PRIVATE KEY-----\n", secrets$private_key)
google_token = httr::oauth_service_token(endpoint, secrets, scope)
googleAuthR:::.auth$set_cred(google_token)
token <- googleAuthR:::.auth$get_cred()
4. Click Calculate.
In this example, we first set the scope so that it's pointing to the API. We then use jsonlite's fromJSON function to parse the text from JSON to a recognizable R format before authenticating the connection using httr's oauth and googleAuthR's auth functions.
B. Call your website traffic
1. Add the below R code after the authentication code:
library(googleAnalyticsR)
property_id = 'your_property_id'
df = ga_data(property_id,
date_range = c("2023-10-01", "2023-10-28"),
metrics = c("totalUsers", "newUsers", "sessions", "screenPageViews"),
dimensions = c("date"),
max = -1)
Here, we use googleAnalyticsR's ga_data function to call four different metrics - total users, new users, sessions, and screen page views – based on our website's Property ID for all records in the provided date range split by date. We have used max = -1
so that it will pull all the data, but you can also cap this at a specific number if you wish. Date shortcuts such as "90daysAgo" or "yesterday" can also be used for either the start or end date.
2. OPTIONAL: If you wish to make this call take place daily, you can add the below lines to the top of your R code - see How to Automatically Update Calculations, Variables and Data Sets Using R for more detail on other available settings.
library(flipTime)
UpdateEvery(1, "days", options = "wakeup")
3. Things to consider:
- For standard Google Analytics accounts, data sampling occurs when you reach the quota limit at the property level for the specified date range (see data sampling) in order to fetch results faster. This means that if your API call is requesting more than this limit, some of the rows will be estimates rather than measured values.
- If you are using a wide date range with millions of events, it may be prudent to split the date ranges into separate calls to avoid hitting the session sampling threshold and then combine them together later using a simple rbind command, for example.
- For a list of all the metrics and dimensions, you can call via the API (see API names).
Next
How to Enable Google Analytics Tracking on Documents