Send app events to GA4 using Measurement Protocol

Last Updated: 2021-06-08

What you'll build

In this codelab, You will learn how to send external events to GA4 using Measurement Protocol.

This codelab assumes that you already have an App with Google Analytics for Firebase implemented. If you want to learn how to integrate with Google Analytics for Firebase, please refer to this codelab first. If you want to learn how to build an app with Firebase, please refer to Firebase Android Codelab-Build Friendly Chat.

What you'll learn

  • Steps to make your first MP call
  • Understand parameters required for the call
  • Send and validate your test call
  • Build a sample script in Python to make the call

What you'll need

  • Your Android or iOS App
  • Any IDE to make changes
  • GA4 Account
  • Optional - Python development environment (or Colab)

Create API Secret in GA4

Navigate to GA4 and create your new API secret by navigating to Admin > Data Streams > choose your stream > Measurement Protocol > Create

8dee89e850ae90bb.png

d0be19d8112435a2.png

de5a80a1445d3a14.png

You can provide any nickname, and the secret value will be displayed, which you can use in your call

In case you are not sure how to access GA4, you can visit your Firebase Project, check Project Settings > Integrations > Google Analytics, and click on "Manage". The Google Analytics connection should be visible, and you can navigate directly from there as well

f0feed0557420678.png

Collect app_instance_id

You can use any of the below methods to collect your app_instance_id.

  1. Using BigQuery Export
  2. Fetching Natively in your App Source Code

Both of these are explained in detail below

  1. Using BigQuery Export

If you have BigQuery export enabled, you can follow the below steps

  • Sign in to Firebase
  • Navigate to Project Settings > Integrations > BigQuery
  • Click on "View in BigQuery" near the dataset

Note : The dataset would be available only after the toggle has been enabled for about 24-48 hours

1dc4e93dee33316f.png

  • In BigQuery, you can check for user_pseudo_id in the table. This is the app_instance_id that you can use in your call

aa6d384e380a11e8.png

  1. Fetching Natively in your App Source Code

If your app is built using Java, you can use something like this to retrieve the app_instance_id

 FirebaseAnalytics.getInstance(this).getAppInstanceId().addOnCompleteListener(new OnCompleteListener<String>() {
        @Override
        public void onComplete(@NonNull Task<String> task) {
            if (task.isSuccessful()) {
                String user_pseudo_id = task.getResult();
            }
        }
    });

For Kotlin, you can try the below

Thread {
   Firebase.analytics.appInstanceId.addOnSuccessListener { user_pseudo_id ->
       Log.d("Firebase", "user_pseudo_id using appInstanceId is $user_pseudo_id")
       /*
       Store the value to your server or do something with the retrieved id
        */
   }
}.start()

If you have an iOS App, you can use the following in Swift

let user_pseudo_id = Analytics.appInstanceID()
print("user_pseudo_id = \(user_pseudo_id)")
/*
Store the value to your server or do something with the retrieved id
*/

Below are more links depending on your infrastructure

You can build a sample call using the Event Builder in GA4. (This requires you to login and have cookies enabled). Make sure the toggle is set to "firebase"

15440faa9ca6a1f1.png

You shall need to fill in the following fields

  • api_secret - Already created earlier on GA4
  • firebase_app_id - To get this, you can navigate to Admin > Data Streams > choose your stream . It should be displayed as below

71174b16f86ff03e.png

  • app_instance_id - You have already retrieved this value
  • user_id is not mandatory. You can leave it blank for now
  • Category - change this to "Custom" from the dropdown, and put in any event name of your choice (don't use any auto collected event). Here we are using "test_from_codelab"

cf580a708bb0a8a2.png

Optionally, you can also choose to provide event parameters and/or user properties by clicking on the buttons below

da59bb982f6f906a.png

Once you have filled in everything, you should see something like this, with a button to "Validate Event"

39676ab485d17dc0.png

Once you reach this, click on "VALIDATE EVENT" , the button highlighted in orange. It should display the message below, specifying that the event is valid, and you shall see a button to now "SEND TO GA". At this point, if the event comes up as invalid, the tool will tell you the exact field where there is an issue, and you can fix that and retry

1d63d1e067c46294.png

You can now click on the button, and it should send a test event to GA4

Once you have sent the event, you can navigate to your GA4 account and check Realtime. You should see the event come through

7b9e9a0f74b64757.png

It could take around 24 hours for the events to propagate from realtime view to the actual events reporting tab, so no need to worry if you don't see this in the regular event reporting immediately!

Now that you have tested it out, you can examine the API call, and the event payload to build a similar architecture in Python (or in any language of your choice) that can make this call. You can then schedule this at your desired frequency and operationalize it. For this part, you can either use any IDE of your choice that supports Python or just use a Google Colab notebook which does not require any installation on your device

Referring back to the GA4 Event Builder, you will see that the endpoint is as below

POST /mp/collect?firebase_app_id=XXXX&api_secret=XXXX 
HTTP/1.1
Host: www.google-analytics.com

The event payload was as below

{
  "app_instance_id": XXXX,
  "non_personalized_ads": false,
  "events": [
    {
      "name": "test_from_codelab",
      "params": {
        "test_param": "test_123"
      }
    }
  ]
}

You can translate this to python by using something like this

import requests
import json
url = "https://www.google-analytics.com/mp/collect?firebase_app_id=XXXX&api_secret=XXXX"
payload = {
  "app_instance_id": XXXX,
  "non_personalized_ads": False,
  "events": [
    {
      "name": "test_from_codelab",
      "params": {
        "test_param": "test_123"
      }
    }
  ]
}
r = requests.post(url,data=json.dumps(payload),verify=True)
print(r.status_code)

Once you execute this with the right values, you should similarly see the event reflect in realtime in GA4.

Congratulations, you've successfully used Measurement Protocol in GA4. Now you can build powerful solution architectures to send more meaningful data to Google Analytics and improve your marketing and business analytics. In order to make the most of this, we also suggest connecting to Google Ads, and importing these events as conversions. You can refer to step 6 in this codelab for detailed instructions on that. For conversion tracking purposes, Google Ads will only show data which is associated with IDFA or device IDs collected from the Firebase SDK within the last 60 days. Do bear in mind that this is still an alpha API and make sure to go through the limitations listed here which should be addressed before full launch

You've learned

  • How to collect the right variables to make MP calls
  • How to send and validate test events
  • How to build a script to send MP calls