Google Analytics for Firebase Triggers

Google Analytics for Firebase provides event reports that help you understand how users interact with your app. With Cloud Functions, you can access logged conversion events and trigger functions based on these events.

Only conversion events are supported by Cloud Functions. You can specify which events are conversion events in the Events tab of the Firebase console's Analytics pane.

Event types

Google Analytics for Firebase triggers the log event. This is a powerful event type, since any action that a user takes in your app can be logged and in turn trigger a function.

Event Type Trigger
providers/google.firebase.analytics/eventTypes/event.log Triggered when a conversion event is logged.

Cloud Functions can respond to the logging of a Google Analytics for Firebase conversion event. For instance, if a user makes an in-app purchase, an in_app_purchase conversion event is logged and can be consumed by Cloud Functions.

Event structure

This trigger invokes your function with an event similar to the one shown below:

{
    "eventDim": [ // Contains a single event
        {
            "date": "20090213",
            "name": "screen_view",
            "params": {
                "firebase_conversion": {
                    "intValue": "1"
                },
                "firebase_event_origin": {
                    "stringValue": "auto"
                },
                "firebase_previous_class": {
                    "stringValue": "MainActivity"
                },
                "firebase_previous_id": {
                    "intValue": "1928209043426257906"
                },
                "firebase_previous_screen": {
                    "stringValue": "id-D-D"
                },
                "firebase_screen": {
                    "stringValue": "id-C-C"
                },
                "firebase_screen_class": {
                    "stringValue": "MainActivity"
                },
                "firebase_screen_id": {
                    "intValue": "1234567890000"
                }
            },
            "previousTimestampMicros": "1234567890000",
            "timestampMicros": "1234567890000"
        }
    ],
    "userDim": {
        // A UserDimensions object
    }
}

User information such as application information or device information can be found in the userDim property. Information about the logged event can be found in the eventDim array. The objects contained in that array include a name field that holds the conversion event name (such as in_app_purchase). Custom fields set up in Google Analytics for Firebase also appear here.

Code sample

Use the following snippet to process this response:

Node.js 8/10

/**
 * Triggered by a Google Analytics for Firebase log event.
 *
 * @param {object} data The event payload.
 * @param {object} context The event metadata.
 */
exports.helloAnalytics = (data, context) => {
  const {resource} = context;
  console.log(`Function triggered by the following event: ${resource}`);

  const analyticsEvent = data.eventDim[0];
  console.log(`Name: ${analyticsEvent.name}`);
  console.log(`Timestamp: ${new Date(analyticsEvent.timestampMicros / 1000)}`);

  const userObj = data.userDim;
  console.log(`Device Model: ${userObj.deviceInfo.deviceModel}`);
  console.log(`Location: ${userObj.geoInfo.city}, ${userObj.geoInfo.country}`);
};

Node.js 6 (Deprecated)

/**
 * Triggered by a Google Analytics for Firebase log event.
 *
 * @param {!Object} event The Cloud Functions event.
 */
exports.helloAnalytics = event => {
  const resource = event.resource;
  console.log(`Function triggered by the following event: ${resource}`);

  const analyticsEvent = event.data.eventDim[0];
  console.log(`Name: ${analyticsEvent.name}`);
  console.log(`Timestamp: ${new Date(analyticsEvent.timestampMicros / 1000)}`);

  const userObj = event.data.userDim;
  console.log(`Device Model: ${userObj.deviceInfo.deviceModel}`);
  console.log(`Location: ${userObj.geoInfo.city}, ${userObj.geoInfo.country}`);
};

Python

from datetime import datetime
def hello_analytics(data, context):
    """ Triggered by a Google Analytics for Firebase log event.
     Args:
            data (dict): The event payload.
            context (google.cloud.functions.Context): Metadata for the event.
    """
    trigger_resource = context.resource
    print(f'Function triggered by the following event: {trigger_resource}')

    event = data["eventDim"][0]
    print(f'Name: {event["name"]}')

    event_timestamp = int(event["timestampMicros"][:-6])
    print(f'Timestamp: {datetime.utcfromtimestamp(event_timestamp)}')

    user_obj = data["userDim"]
    print(f'Device Model: {user_obj["deviceInfo"]["deviceModel"]}')

    geo_info = user_obj["geoInfo"]
    print(f'Location: {geo_info["city"]}, {geo_info["country"]}')

Go


// Package p contains a Google Analytics for Firebase Cloud Function.
package p

import (
	"context"
	"fmt"
	"log"

	"cloud.google.com/go/functions/metadata"
)

// AnalyticsEvent is the payload of an Analytics log event.
type AnalyticsEvent struct {
	EventDimensions []EventDimensions `json:"eventDim"`
	UserDimensions  interface{}       `json:"userDim"`
}

// EventDimensions holds Analytics event dimensions.
type EventDimensions struct {
	Name                    string      `json:"name"`
	Date                    string      `json:"date"`
	TimestampMicros         string      `json:"timestampMicros"`
	PreviousTimestampMicros string      `json:"previousTimestampMicros"`
	Params                  interface{} `json:"params"`
}

// HelloAnalytics handles Firebase Mobile Analytics log events.
func HelloAnalytics(ctx context.Context, e AnalyticsEvent) error {
	meta, err := metadata.FromContext(ctx)
	if err != nil {
		return fmt.Errorf("metadata.FromContext: %v", err)
	}
	log.Printf("Function triggered by Google Analytics event: %v", meta.Resource)
	log.Printf("%+v", e)
	return nil
}

Deploying your function

To deploy your function, specify the event type and the project in which you have Firebase Auth configured. In the console, there is a field for Event Type which contains log—the only option—and Log Event Name, which is the conversion event that will trigger the function.

On the command line, specific strings must be used to specify these parameters. The following gcloud command deploys a function that triggers when a user makes an in-app purchase:

gcloud functions deploy YOUR_ANALYTICS_FUNCTION \
  --trigger-event providers/google.firebase.analytics/eventTypes/event.log \
  --trigger-resource projects/YOUR_PROJECT_ID/events/in_app_purchase \
  --runtime RUNTIME
Argument Description
--trigger-event NAME The name of the event type that the function wishes to receive. For Google Analytics for Firebase, this is always providers/google.firebase.analytics/eventTypes/event.log.
--trigger-resource NAME The fully qualified Google Analytics event name, including your project information. This should take the form: projects/YOUR_PROJECT_ID/events/CONVERSION_EVENT_NAME
--runtime RUNTIME The name of the runtime you are using. For a complete list, see the gcloud reference.
Was deze pagina nuttig? Laat ons weten hoe goed we u hebben geholpen:

Feedback verzenden over...

Cloud Functions Documentation