Google Analytics for Firebase 触发器

Google Analytics for Firebase 提供事件报告,帮助您了解用户如何与应用进行互动。借助 Cloud Functions,您可以访问从 Apple 和 Android 设备记录的转化事件,并根据这些事件触发函数。

事件类型

Google Analytics for Firebase 会触发 log 事件。这是一种强大的事件类型,因为用户在您的应用中进行的任何操作都将被记录,从而触发函数。

事件类型 触发器
providers/google.firebase.analytics/eventTypes/event.log 记录转化事件时触发。

Cloud Functions 函数可以响应 Google Analytics for Firebase 转化事件的日志记录。例如,如果用户进行了应用内购买,则会记录一个 in_app_purchase 转化事件,并可供 Cloud Functions 函数使用。

事件结构

当发生类似于如下所示的事件时,此触发器会调用您的函数:

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

userDim 属性中包含应用信息或设备信息等用户信息。eventDim 数组中包含有关所记录事件的信息。该数组包含的对象包括提供转化事件名称的 name 字段(例如 in_app_purchase)。在 Google Analytics for Firebase 中设置的自定义字段也会显示在此处。

代码示例

使用以下代码段处理此响应:

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"]}')

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: %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);
}

部署函数

要部署函数,请指定事件类型以及配置了 Firebase 身份验证的项目。在控制台中,有事件类型字段,它提供 log 这一唯一选项,以及日志事件名称字段,这是将触发函数的转化事件。

在命令行中,必须使用特定的字符串来指定这些参数。以下 gcloud 命令将部署一个函数,每次用户进行应用内购买时,都会触发此函数:

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
参数 说明
FUNCTION_NAME 您要部署的 Cloud Functions 函数的注册名称。 这可以是源代码中函数的名称,也可以是任意字符串。如果 FUNCTION_NAME 是任意字符串,则必须添加 --entry-point 标志。
--entry-point ENTRY_POINT 源代码中函数或类的名称。可选,除非您未使用 FUNCTION_NAME 指定源代码中要在部署期间执行的函数。在这种情况下,您必须使用 --entry-point 提供可执行函数的名称。
--trigger-event NAME 函数希望接收的事件类型的名称。对于 Google Analytics for Firebase,此值始终为 providers/google.firebase.analytics/eventTypes/event.log.
--trigger-resource NAME 完全限定的 Google Analytics 事件名称,包括项目信息。其格式应为:projects/YOUR_PROJECT_ID/events/CONVERSION_EVENT_NAME
--runtime RUNTIME 您使用的运行时的名称。如需完整列表,请参阅 gcloud 参考文档