When implementing Ecommerce using Firebase Analytics, handling issues related to the items array becomes crucial, especially when working within a WebView environment.
Ecommerce Data Layer Structure
The typical Ecommerce data layer has the following structure:
dataLayer.push({ ecommerce: null }); // Clear the previous ecommerce object.
dataLayer.push({
event: "view_item",
ecommerce: {
currency: "USD",
value: 7.77,
items: [
{
item_id: "SKU_12345",
item_name: "Stan and Friends Tee",
affiliation: "Google Merchandise Store",
coupon: "SUMMER_FUN",
discount: 2.22,
index: 0,
item_brand: "Google",
item_category: "Apparel",
item_category2: "Adult",
item_category3: "Shirts",
item_category4: "Crew",
item_category5: "Short sleeve",
item_list_id: "related_products",
item_list_name: "Related Products",
item_variant: "green",
location_id: "ChIJIQBpAG2ahYAR_6128GcTUEo",
price: 9.99,
quantity: 1
}
]
}
});
While this code works on the web, issues may arise when implementing it within a WebView, as indicated by the log:
11-10 10:49:26.413 V/FA-SVC (23664): Logging event: origin=app,name=view_item,params=Bundle[{ ga_event_origin(_o)=app, ga_screen_class(_sc)=MainActivity, ga_screen_id(_si)=-5730677743255200711, event=view_item}]
The log indicates that, during event logging on Android, the items is not visible, causing the mentioned issue
Solution
Android and iOS developers need to perform additional steps to address this issue.
- Update SDK Versions
- Convert the Items Array to a JSON String
- Android - Using JSONArray and JSONObject to Convert the Items Array
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.os.Bundle
import com.google.firebase.analytics.FirebaseAnalytics
val ecommerceObject = dataLayer.lastOrNull { it["ecommerce"] != null }?.get("ecommerce") as? JSONObject
val itemsArray = ecommerceObject?.getJSONArray("items")
if (itemsArray != null) {
val itemsJsonString = itemsArray.toString()
val bundle = Bundle().apply {
putString("itemsJsonString", itemsJsonString)
...
}
FirebaseAnalytics.getInstance(context).logEvent("view_item", bundle)
}
2. iOS - Using JSONSerialization to Convert the Items Array
import Foundation
import FirebaseAnalytics
let ecommerceObject = dataLayer.last { $0["ecommerce"] != nil }?["ecommerce"] as? [String: Any]
let itemsArray = ecommerceObject?["items"] as? [[String: Any]]
if let itemsArray = itemsArray {
do {
let itemsJsonData = try JSONSerialization.data(withJSONObject: itemsArray, options: [])
let itemsJsonString = String(data: itemsJsonData, encoding: .utf8)
Analytics.logEvent("view_item", parameters: ["itemsJsonString": itemsJsonString ?? ""])
...
}
}
Solved