Attivatori di Google Analytics per Firebase

Google Analytics for Firebase fornisce report sugli eventi che ti aiutano a capire in che modo gli utenti interagiscono con la tua app. Con Cloud Functions, può accedere agli eventi di conversione che hai registrato da dispositivi Apple e Android. e attivare funzioni basate su questi eventi.

Tipi di evento

Google Analytics for Firebase attiva l'evento log. Questo è un potente tipo di evento, poiché qualsiasi azione eseguita da un utente nella tua app può essere registrati e a sua volta attivano una funzione.

Tipo di evento Trigger
providers/google.firebase.analytics/eventTypes/event.log Si attiva quando viene registrato un evento di conversione.

Cloud Functions può rispondere al logging di un account Google Analytics un evento di conversione Firebase. Ad esempio, se un utente effettua un acquisto in-app, in_app_purchase evento di conversione viene registrato e può essere utilizzato da di Cloud Functions.

Struttura evento

Questo trigger richiama la tua funzione con un evento simile a quello mostrato di seguito:

{
    "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
    }
}

Informazioni sugli utenti, ad esempio informazioni sulle applicazioni o sul dispositivo, possono essere presenti nella proprietà userDim. Informazioni sui disponibile nell'array eventDim. Gli oggetti contenuti in quell'array Includi un campo name contenente il nome dell'evento di conversione (ad esempio in_app_purchase). Campi personalizzati configurati in Google Analytics for Firebase vengono visualizzati anche qui.

Esempio di codice

Utilizza il seguente snippet per elaborare questa risposta:

Node.js

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

  const [analyticsEvent] = event.data.eventDim;
  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"]}')

Vai


// 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: %w", err)
	}
	log.Printf("Function triggered by Google Analytics event: %v", meta.Resource)
	log.Printf("%+v", e)
	return nil
}

C#

using CloudNative.CloudEvents;
using Google.Cloud.Functions.Framework;
using Google.Events.Protobuf.Firebase.Analytics.V1;
using Microsoft.Extensions.Logging;
using System;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;

namespace FirebaseAnalytics;

public class Function : ICloudEventFunction<AnalyticsLogData>
{
    private readonly ILogger _logger;

    public Function(ILogger<Function> logger) =>
        _logger = logger;

    public Task HandleAsync(CloudEvent cloudEvent, AnalyticsLogData data, CancellationToken cancellationToken)
    {
        _logger.LogInformation("Event source: {source}", cloudEvent.Source);
        _logger.LogInformation("Event count: {count}", data.EventDim.Count);

        var firstEvent = data.EventDim.FirstOrDefault();
        if (firstEvent is object)
        {
            _logger.LogInformation("First event name: {name}", firstEvent.Name);
            DateTimeOffset timestamp = DateTimeOffset.FromUnixTimeMilliseconds(firstEvent.TimestampMicros / 1000);
            _logger.LogInformation("First event timestamp: {timestamp:u}", timestamp);
        }

        var userObject = data.UserDim;
        if (userObject is object)
        {
            _logger.LogInformation("Device model: {device}", userObject.DeviceInfo?.DeviceModel);
            _logger.LogInformation("Location: {city}, {country}", userObject.GeoInfo?.City, userObject.GeoInfo.Country);
        }
        // In this example, we don't need to perform any asynchronous operations, so the
        // method doesn't need to be declared async.
        return Task.CompletedTask;
    }
}

Ruby

require "functions_framework"

# Triggered by a Google Analytics for Firebase log event.
FunctionsFramework.cloud_event "hello_analytics" do |event|
  # Event-triggered Ruby functions receive a CloudEvents::Event::V1 object.
  # See https://cloudevents.github.io/sdk-ruby/latest/CloudEvents/Event/V1.html
  # The Analytics event payload can be obtained from the `data` field.
  payload = event.data

  logger.info "Function triggered by the following event: #{event.source}"

  event = payload["eventDim"].first
  logger.info "Name: #{event['name']}"

  event_timestamp = Time.at(event["timestampMicros"].to_i / 1_000_000).utc
  logger.info "Timestamp: #{event_timestamp.strftime '%Y-%m-%dT%H:%M:%SZ'}"

  user_obj = payload["userDim"]
  logger.info "Device Model: #{user_obj['deviceInfo']['deviceModel']}"

  geo_info = user_obj["geoInfo"]
  logger.info "Location: #{geo_info['city']}, #{geo_info['country']}"
end

PHP


use Google\CloudFunctions\CloudEvent;

function firebaseAnalytics(CloudEvent $cloudevent): void
{
    $log = fopen(getenv('LOGGER_OUTPUT') ?: 'php://stderr', 'wb');

    $data = $cloudevent->getData();

    fwrite($log, 'Function triggered by the following event:' . $data['resource'] . PHP_EOL);

    $analyticsEvent = $data['eventDim'][0];
    $unixTime = $analyticsEvent['timestampMicros'] / 1000;

    fwrite($log, 'Name: ' . $analyticsEvent['name'] . PHP_EOL);
    fwrite($log, 'Timestamp: ' . gmdate("Y-m-d\TH:i:s\Z", $unixTime) . PHP_EOL);

    $userObj = $data['userDim'];
    fwrite($log, sprintf(
        'Location: %s, %s' . PHP_EOL,
        $userObj['geoInfo']['city'],
        $userObj['geoInfo']['country']
    ));

    fwrite($log, 'Device Model: %s' . $userObj['deviceInfo']['deviceModel'] . PHP_EOL);
}

esegui il deployment della funzione

Per eseguire il deployment della funzione, specifica il tipo di evento e il progetto in cui in cui è configurato Firebase Auth. Nella console è presente il campo Evento Type (Tipo), che contiene log (l'unica opzione) e Log Event Name (Nome evento di log), evento di conversione che attiverà la funzione.

Nella riga di comando, è necessario utilizzare stringhe specifiche per specificare questi parametri. Il seguente comando Google Cloud CLI esegue il deployment di una funzione che si attiva quando un l'utente effettua un acquisto in-app:

gcloud functions deploy FUNCTION_NAME \
  --entry-point ENTRY_POINT \
  --trigger-event providers/google.firebase.analytics/eventTypes/event.log \
  --trigger-resource projects/YOUR_PROJECT_ID/events/in_app_purchase \
  --runtime RUNTIME
Argomento Descrizione
FUNCTION_NAME Il nome registrato della Cloud Function di cui esegui il deployment. Può essere il nome di una funzione nel del codice sorgente o una stringa arbitraria. Se FUNCTION_NAME è un stringa arbitraria, devi includere Flag --entry-point.
--entry-point ENTRY_POINT Il nome di una funzione o classe nel codice sorgente. Facoltativo, a meno che non hai utilizzato FUNCTION_NAME per specificare nel codice sorgente da eseguire durante il deployment. In questo devi utilizzare --entry-point per indicare il nome del una funzione eseguibile.
--trigger-event NAME Il nome del tipo di evento che la funzione vuole ricevere. Per Google Analytics for Firebase, è sempre providers/google.firebase.analytics/eventTypes/event.log.
--trigger-resource NAME Il nome completo dell'evento Google Analytics, incluso il progetto informazioni. Dovrebbe avere il seguente formato: projects/YOUR_PROJECT_ID/events/CONVERSION_EVENT_NAME
--runtime RUNTIME Il nome del runtime che stai utilizzando. Per un elenco completo, vedi Riferimento gcloud.