Implementing Firebase Analytics through Tealium iQ

Implementing Firebase Analytics through Tealium iQ

by Thursday - edited Friday (81 Views)

Purpose

This document describes how to integrate Google's Analytics for Firebase product (formerly Firebase Analytics) with Tealium's mobile libraries.

Use Case and Benefits

Tealium's mobile libraries provide a simple way to integrate multiple different marketing/analytics technologies into your apps. In most cases, these integrations can be achieved through either Tealium EventStream, which runs server-side, or Tealium iQ, which runs client-side, and sends data directly from your end-users' devices to 3rd party tools. In the case of Analytics for Firebase, there are currently no public APIs available, and the only way to get data into Firebase is using the Firebase native SDKs for Android and iOS.

Normally, this would mean that your app developers would have to manually set up the Firebase SDK outside of Tealium. To simplify the process, however, Tealium's Remote Commands feature can be used to make calls to the Firebase SDK, which means you can use your existing Data Layer and tracking calls, with minimal additional effort by your developers. Some configuration is still required, but the main benefit of using this method is that you can modify the behavior of the Firebase SDK after the app has been released to the App Store/Play Store, and new variables and events can be added, without any code changes to the app itself; this can all be managed through Tealium iQ.

Requirements

  1. You must already have the Firebase SDK available in your app, with Analytics enabled.
  2. You already have the Tealium Android or Tealium Swift/TealiumIOS(Objective-C) library integrated in your app.
  3. You must add the attached Tealium Remote Commands classes to your app. These classes provide the code to expose the Firebase Analytics API to Tealium iQ via the Remote Commands system.
  4. You must add the "TagBridge Custom Command" tag in Tealium iQ and configure it to trigger Firebase Analytics events (see configuration instructions below).

Remote Command Classes

 This section is intended primarily for App Developers

For all libraries, you will need to register the Firebase Analytics Remote Command before it can be used. This should be done when you initialize the library. The following sample code shows how you might set this up for each platform/language Tealium provides.

Android

// this code sets up a config object and creates a Tealium instance; you should already have this code in your app
Tealium.Config config = Tealium.Config.create(application, "tealiummobile", "firebase-analytics", "dev");
Tealium inst = Tealium.createInstance(TEALIUM_MAIN, config);

// the following is the new code to add the Firebase Analytics Remote Command
RemoteCommand firebase = new FirebaseRemoteCommand(application);
inst.addRemoteCommand(firebase);

Code: See attachment "FirebaseTealiumAndroid.java"

iOS (Objective-C)

Please note: this class is designed for use with Tealium's Objective-C library, but the code itself is written in Swift. You will need to have a Bridging Header in your Xcode project for this to work correctly.

/* this code sets up a config object and creates a Tealium instance
 you should already have this code in your app */
let config = TEALConfiguration(account: "tealiummobile",
                                   profile: "firebase-analytics",
                                   environment: "dev",
                                   datasource: "test12")
let tealium = Tealium.newInstance(forKey: "teal", configuration: config)

// the following is the new code to add the Firebase Analytics Remote Command
tealium.addRemoteCommandID("firebaseAnalytics", description: nil, targetQueue: DispatchQueue.main, responseBlock: FirebaseCommands.firebaseCommand())

Code: See attachment "FirebaseTealiumObjectiveC.swift"

iOS (Swift)

This class is designed for use with Tealium's Swift library for iOS (will not work with other platforms).

// class-level variable to hold reference to Tealium
var tealium : Tealium?

/* this code sets up a config object and creates a Tealium instance
 you should already have this code in your app */
let config = TealiumConfig(account: "tealiummobile",
                           profile: "firebase-analytics",
                           environment: "dev",
                           datasource: "test12",
                           optionalData: nil)
                       
self.tealium = Tealium(config: config,
                  completion: { (responses) in
          
          // be sure to set up remoteCommands inside the Tealium initialization completion block, to ensure the API is ready        
			guard let remoteCommands = self.tealium?.remoteCommands() else {
				return
			}
	
			let firebaseCommand = FirebaseCommands.firebaseCommand()
			remoteCommands.add(firebaseCommand)        
})

Code: See attachment "FirebaseTealiumSwift.swift"

General Information

Some events are automatically collected by the Firebase SDK. See here for details: https://support.google.com/firebase/answer/6317485?hl=en

Tealium iQ Configuration

 This section is intended for anyone configuring the Firebase Remote Command tag in Tealium iQ, and may not be of interest to app developers without Tealium iQ access.

TagBridge Custom Command Tag

The Custom Command tag is a special tag that contains an implementation of the API required to trigger custom native code blocks you have registered with the Tealium mobile libraries. There are 3 important parts to the configuration:

  • Command ID: For this integration, the command ID should be firebaseAnalytics
  • Mappings: See reference table below for applicable mappings
  • Extensions: See reference table below for recommended extensions

Tag Mappings

The following mappings are available

Mapping Name Firebase Documentation Example Value Data Type
firebase_session_timeout_seconds https://firebase.google.com/docs/reference/swift/firebasecore/api/reference/Classes/AnalyticsConfigu...: 3600 Integer as String
firebase_session_minimum_seconds https://firebase.google.com/docs/reference/swift/firebasecore/api/reference/Classes/AnalyticsConfigu...: 10 Integer as String
firebase_analytics_enabled https://firebase.google.com/docs/reference/swift/firebasecore/api/reference/Classes/AnalyticsConfigu...: true Boolean as String
firebase_log_level https://firebase.google.com/docs/reference/swift/firebasecore/api/reference/Classes/FirebaseConfigur...: debug String
firebase_event_name https://firebase.google.com/docs/reference/swift/firebaseanalytics/api/reference/Classes/Analytics#/...: add_payment_info String
firebase_event_params https://firebase.google.com/docs/reference/swift/firebaseanalytics/api/reference/Classes/Analytics#/...: {"param_transaction_id": "A123456789"} JSON
firebase_screen_name https://firebase.google.com/docs/reference/swift/firebaseanalytics/api/reference/Classes/Analytics#/...: Homescreen String
firebase_screen_class https://firebase.google.com/docs/reference/swift/firebaseanalytics/api/reference/Classes/Analytics#/...: Home String
firebase_property_name https://firebase.google.com/docs/reference/swift/firebaseanalytics/api/reference/Classes/Analytics#/...: user_name String
firebase_property_value https://firebase.google.com/docs/reference/swift/firebaseanalytics/api/reference/Classes/Analytics#/...: john_doe String
firebase_user_id https://firebase.google.com/docs/reference/swift/firebaseanalytics/api/reference/Classes/Analytics#/...: john.doe@provider.com String
command_name This is the firebase command you wish to execute (config, logEvent, setScreenName, setUserProperty, setUserId) logEvent Comma-separated String

Event Names

Firebase Documentation References:

Tealium String Value Firebase (Swift) Constant Firebase (Android - Java) Constant
add_payment_info AnalyticsEventAddPaymentInfo ADD_PAYMENT_INFO
add_to_cart AnalyticsEventAddToCart ADD_TO_CART
add_to_wishlist AnalyticsEventAddToWishlist ADD_TO_WISHLIST
app_open AnalyticsEventAppOpen APP_OPEN
event_begin_checkout AnalyticsEventBeginCheckout BEGIN_CHECKOUT
event_campaign_details AnalyticsEventCampaignDetails CAMPAIGN_DETAILS
event_checkout_progress AnalyticsEventCheckoutProgress CHECKOUT_PROGRESS
event_earn_virtual_currency AnalyticsEventEarnVirtualCurrency EARN_VIRTUAL_CURRENCY
event_ecommerce_purchase AnalyticsEventEcommercePurchase ECOMMERCE_PURCHASE
event_generate_lead AnalyticsEventGenerateLead GENERATE_LEAD
event_join_group AnalyticsEventJoinGroup JOIN_GROUP
event_level_up AnalyticsEventLevelUp LEVEL_UP
event_login AnalyticsEventLogin LOGIN
event_post_score AnalyticsEventPostScore POST_SCORE
event_present_offer AnalyticsEventPresentOffer PRESENT_OFFER
event_purchase_refund AnalyticsEventPurchaseRefund PURCHASE_REFUND
event_remove_cart AnalyticsEventRemoveFromCart REMOVE_FROM_CART
event_search AnalyticsEventSearch SEARCH
event_select_content AnalyticsEventSelectContent SELECT_CONTENT
event_set_checkout_option AnalyticsEventSetCheckoutOption SET_CHECKOUT_OPTION
event_share AnalyticsEventShare SHARE
event_signup AnalyticsEventSignUp SIGN_UP
event_spend_virtual_currency AnalyticsEventSpendVirtualCurrency SPEND_VIRTUAL_CURRENCY
event_tutorial_begin AnalyticsEventTutorialBegin TUTORIAL_BEGIN
event_tutorial_complete AnalyticsEventTutorialComplete TUTORIAL_COMPLETE
event_unlock_achievement AnalyticsEventUnlockAchievement UNLOCK_ACHIEVEMENT
event_view_item AnalyticsEventViewItem VIEW_ITEM
event_view_item_list AnalyticsEventViewItemList VIEW_ITEM_LIST
event_view_search_results AnalyticsEventViewSearchResults VIEW_SEARCH_RESULTS

Parameter Values

Firebase Documentation References:

Tealium String Value Firebase (Swift) Constant Firebase (Android - Java) Constant
param_achievement_id AnalyticsParameterAchievementID ACHIEVEMENT_ID
param_ad_network_click_id AnalyticsParameterAdNetworkClickID ACLID
param_affiliation AnalyticsParameterAffiliation AFFILIATION
param_cp1 AnalyticsParameterCP1 CP1
param_campaign AnalyticsParameterCampaign CAMPAIGN
param_character AnalyticsParameterCharacter CHARACTER
param_checkout_option AnalyticsParameterCheckoutOption CHECKOUT_OPTION
param_checkout_step AnalyticsParameterCheckoutStep CHECKOUT_STEP
param_content AnalyticsParameterContent CONTENT
param_content_type AnalyticsParameterContentType CONTENT_TYPE
param_coupon AnalyticsParameterCoupon COUPON
param_creative_name AnalyticsParameterCreativeName CREATIVE_NAME
param_creative_slot AnalyticsParameterCreativeSlot CREATIVE_SLOT
param_currency AnalyticsParameterCurrency CURRENCY
param_destination AnalyticsParameterDestination DESTINATION
param_end_date AnalyticsParameterEndDate END_DATE
param_flight_number AnalyticsParameterFlightNumber FLIGHT_NUMBER
param_group_id AnalyticsParameterGroupID GROUP_ID
param_index AnalyticsParameterIndex INDEX
param_item_brand AnalyticsParameterItemBrand ITEM_BRAND
param_item_category AnalyticsParameterItemCategory ITEM_CATEGORY
param_item_id AnalyticsParameterItemID ITEM_ID
param_item_list AnalyticsParameterItemList ITEM_LIST
param_item_location_id AnalyticsParameterItemLocationID ITEM_LOCATION_ID
param_item_name AnalyticsParameterItemName ITEM_NAME
param_item_variant AnalyticsParameterItemVariant ITEM_VARIANT
param_level AnalyticsParameterLevel LEVEL
param_location AnalyticsParameterLocation LOCATION
param_medium AnalyticsParameterMedium MEDIUM
param_number_nights AnalyticsParameterNumberOfNights NUMBER_OF_NIGHTS
param_number_pax AnalyticsParameterNumberOfPassengers NUMBER_OF_PASSENGERS
param_number_rooms AnalyticsParameterNumberOfRooms NUMBER_OF_ROOMS
param_origin AnalyticsParameterOrigin ORIGIN
param_price AnalyticsParameterPrice PRICE
param_quantity AnalyticsParameterQuantity QUANTITY
param_score AnalyticsParameterScore SCORE
param_search_term AnalyticsParameterSearchTerm SEARCH_TERM
param_shipping AnalyticsParameterShipping SHIPPING
param_signup_method AnalyticsParameterSignUpMethod SIGN_UP_METHOD
param_source AnalyticsParameterSource SOURCE
param_start_date AnalyticsParameterStartDate START_DATE
param_tax AnalyticsParameterTax TAX
param_term AnalyticsParameterTerm TERM
param_transaction_id AnalyticsParameterTransactionID TRANSACTION_ID
param_travel_class AnalyticsParameterTravelClass TRAVEL_CLASS
param_value AnalyticsParameterValue VALUE
param_virtual_currency_name AnalyticsParameterVirtualCurrencyName VIRTUAL_CURRENCY_NAME

Extensions

Extensions are required to tell the Firebase Analytics SDK what you want it to do. For example, you might be tracking a screen view using the Tealium SDK on the Order Confirmation screen, which you want to also log in the Firebase SDK. Here's an example of the call in Tealium:

// swift
tealium?.trackView("order_confirmation", ["order_id":"A123456", 
"user_id": "john.doe@someprovider.com", "user_loyalty_status":"vip", "travel_class" : "first"])

In the Firebase SDK, you may wish to log this as an event using the logEvent API call, and also set a user property called user_id. In Tealium iQ, this can be done in several different ways.

First of all, there is a special variable called "command_name", which is a comma-separated string of commands to execute, which can contain 5 possible values: config, logEvent, setScreenName, setUserProperty, setUserId. In this case, we are going to implement all of these methods.

For this example, it is important to understand the order of operations in Tealium iQ. Extensions with the same "scope" are guaranteed to execute in order, from top to bottom as you see them in the Extensions tab. Therefore, we can easily split logic into different extensions, but keep writing to a variable that was defined in an earlier extension. This will become clear in a moment.

  1. Create a new data layer variable called "firebase_command_name" in your Tealium iQ profile.
  2. Create a "Set Data Values" extension, select the new variable ("firebase_command_name") from the dropdown list, and leave the data entry field blank. This will initialize the variable to an empty string.
  3. Create the following list of "Set Data Values" extensions, with the settings listed in the tables below:

Configuration - should only be executed once per session

TiQ Variable Name Variable Type Value Notes
firebase_command_name Text config Mandatory, case-sensitive
firebase_minimum_session_length Text 10 Optional
firebase_session_timeout Text 3600 Optional
firebase_enabled Text true Optional, case-sensitive, default = true
firebase_loglevel Text error Optional, case-sensitive

This will produce the following call in the native Firebase API:

// Swift
let firConfig = FirebaseConfiguration.shared
let firAnalyticsConfig = AnalyticsConfiguration.shared()
firAnalyticsConfig.setSessionTimeoutInterval(3600)
firAnalyticsConfig.setMinimumSessionInterval(10)
firAnalyticsConfig.setAnalyticsCollectionEnabled(true)
firAnalyticsConfig.setLoggerLevel(FirebaseLoggerLevel.error)
firConfig.analyticsConfiguration = firAnalyticsConfig
FirebaseApp.configure()

// Android
mFirebaseAnalytics = FirebaseAnalytics.getInstance(mCurrentActivity.getApplicationContext());
mFirebaseAnalytics.setSessionTimeoutDuration(3600);
mFirebaseAnalytics.setMinimumSessionDuration(10);
mFirebaseAnalytics.setAnalyticsCollectionEnabled(true);

setUserId

TiQ Variable Name Variable Type Value Notes
firebase_command_name JS Code b.firebase_command_name + ",setUserId" Case-sensitive, comma-separated, no spaces
firebase_user_id Text john.doe@someprovider.com Mandatory. Any valid string

This will produce the following call in the native Firebase API:

// Swift
Analytics.setUserID("john.doe@someprovider.com")

// Android
FirebaseAnalytics.setUserId("john.doe@someprovider.com");

setScreenName

TiQ Variable Name Variable Type Value Notes
firebase_command_name JS Code b.firebase_command_name + ",setScreenName" Case-sensitive, comma-separated, no spaces
firebase_screen_name Text Order Confirmation Mandatory. Any valid string
firebase_screen_class Text Order Optional. Any valid string

This will produce the following call in the native Firebase API:

// Swift
Analytics.setScreenName("Order Confirmation", screenClass: "Order)

// Android
FirebaseAnalytics.setCurrentScreen(<current activity reference>, "Order Confirmation", "Order");

setUserProperty

TiQ Variable Name Variable Type Value Notes
firebase_command_name JS Code b.firebase_command_name + ",setUserProperty" Case-sensitive, comma-separated, no spaces
firebase_property_name Text user_loyalty_status Mandatory. Any valid string
firebase_property_value Text vip Mandatory. Any valid string. Set to empty string to clear previously-set value.

This will produce the following call in the native Firebase API:

// Swift
Analytics.setUserProperty("vip", forName: "user_loyalty_status")

// Android
FirebaseAnalytics.setUserProperty("user_loyalty_status", "vip");

logEvent

TiQ Variable Name Variable Type Value Notes
firebase_command_name JS Code b.firebase_command_name + ",logEvent" Case-sensitive, comma-separated, no spaces
firebase_event_name Text event_ecommerce_purchase Mandatory. Any valid string. Use one of the recommended event types listed above for best results (https://firebase.google.com/docs/reference/swift/firebaseanalytics/api/reference/Constants).
firebase_event_params JS Code {"param_travel_class" : b.travel_class, "param_transaction_id": b.order_id}; Optional. Any valid JSON object. Use one of the recommended default parameters listed above for best results. Custom parameters must be defined in the Firebase console before they will show in reports.

This will produce the following call in the native Firebase API:

// Swift
Analytics.logEvent(AnalyticsEventEcommercePurchase, parameters: [AnalyticsParameterTravelClass: "first", AnalyticsParameterTransactionID: "A123456"])

// Android
Bundle b = new Bundle();
b.putString("param_travel_class", "first");
b.putString("param_transaction_id", "A123456");

FirebaseAnalytics.logEvent(FirebaseAnalytics.Event.ECOMMERCE_PURCHASE, b);

Video Example

For a full walk-through of this implementation, please see: https://youtu.be/fWb_saoWl9Q

Attachment
Attachment