Firebase 向け Google アナリティクス トリガー

Firebase 向け Google アナリティクスは、ユーザーによるアプリの利用状況の把握に役立つイベント レポートを提供します。Cloud Functions を使用すると、Apple デバイスまたは Android デバイスで生成されたコンバージョン イベントにアクセスし、それらのイベントに基づいて関数をトリガーできます。

イベントタイプ

Firebase 向け Google アナリティクスが log イベントをトリガーします。これは強力なイベントタイプです。ユーザーがアプリで行った操作がログに記録され、関数がトリガーされます。

イベントタイプ トリガー
providers/google.firebase.analytics/eventTypes/event.log コンバージョン イベントが記録されたときにトリガーされます。

Cloud Functions は、Google アナリティクスでの 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 配列に格納されます。この配列に含まれるオブジェクトには、コンバージョン イベント名(in_app_purchase など)を格納する name フィールドがあります。Firebase 向け Google アナリティクスで設定したカスタム フィールドもここに含まれます。

コードサンプル

このレスポンスを処理するには、次のスニペットを使用します。

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 Authentication が構成されているイベントタイプとプロジェクトを指定します。コンソールには、イベントタイプのフィールドが表示されます。このフィールドには 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 関数が受信するイベントタイプの名前。Firebase 向け Google アナリティクスの場合、これは常に providers/google.firebase.analytics/eventTypes/event.log. になります。
--trigger-resource NAME プロジェクト情報を含む Google アナリティクス イベントの完全修飾名。次の形式を使用します。 projects/YOUR_PROJECT_ID/events/CONVERSION_EVENT_NAME
--runtime RUNTIME 使用しているランタイムの名前。網羅的なリストについては、gcloud リファレンスをご覧ください。