Parcourir la source

增加firebase

PPPPPPP il y a 1 an
Parent
commit
df3215025a
2 fichiers modifiés avec 195 ajouts et 67 suppressions
  1. 83 0
      src/tracking/FirebaseAnalytics.js
  2. 112 67
      src/tracking/TrackAll.js

+ 83 - 0
src/tracking/FirebaseAnalytics.js

@@ -0,0 +1,83 @@
+// FirebaseAnalytics.js
+let firebaseAnalyticsInstance = null;
+
+class FirebaseAnalytics {
+    /**
+     * @param {Object} config
+     * @param {string} config.measurementId - Measurement ID (例如:G-XXXXXXXXXX)
+     * @param {string} config.apiSecret - API Secret
+     * @param {string} config.firebaseAppId - Firebase App ID
+     * @param {string} config.clientId - 客户端ID,通常来自客户端 cookie 或设备唯一标识
+     */
+    constructor({ measurementId, apiSecret, firebaseAppId, clientId }) {
+        this.measurementId = measurementId;
+        this.apiSecret = apiSecret;
+        this.firebaseAppId = firebaseAppId;
+        this.clientId = clientId;
+        // 构造上报的 URL,参考 Measurement Protocol 规范
+        this.endpoint = `https://www.google-analytics.com/mp/collect?measurement_id=${this.measurementId}&api_secret=${this.apiSecret}`;
+    }
+
+    /**
+     * 上报事件到 Firebase Analytics
+     * @param {string} eventName - 事件名称,例如 "user_sign_in"
+     * @param {Object} params - 事件参数(键值对),例如 { page: 'home', duration: 123 }
+     * @returns {Promise<Response>} 返回 fetch 的响应结果
+     */
+    async sendEvent(eventName, params = {}) {
+        // 构造 Measurement Protocol 所要求的 payload
+        const payload = {
+            app_instance_id: this.clientId,
+            // 可选:将 firebaseAppId 传递给后端(注意:文档中可能以 app_instance_id 标识)
+            firebase_app_id: this.firebaseAppId,
+            events: [
+                {
+                    name: eventName,
+                    params: params
+                }
+            ]
+        };
+
+        try {
+            const response = await fetch(this.endpoint, {
+                method: 'POST',
+                headers: {
+                    'Content-Type': 'application/json'
+                },
+                body: JSON.stringify(payload)
+            });
+            if (!response.ok) {
+                throw new Error(`事件上报失败,状态码:${response.status}`);
+            }
+            return response;
+        } catch (error) {
+            console.error('FirebaseAnalytics 上报错误:', error);
+            throw error;
+        }
+    }
+}
+
+// Initialize Firebase Analytics
+const initializeFirebaseAnalytics = (measurementId, apiSecret, firebaseAppId='',clientId='') => {
+    if (!firebaseAnalyticsInstance) {
+        firebaseAnalyticsInstance = new FirebaseAnalytics(measurementId, apiSecret, firebaseAppId,clientId);
+        console.log('Firebase Analytics initialized');
+    } else {
+        console.warn('Firebase Analytics is already initialized');
+    }
+};
+
+// Interface function for external calls
+const fa_trackEvent = (eventName, eventParams) => {
+    if (!firebaseAnalyticsInstance) {
+        console.error('Firebase Analytics is not initialized. Please call initializeFirebaseAnalytics first.');
+        return;
+    }
+    firebaseAnalyticsInstance.sendEvent(eventName, eventParams);
+};
+
+// Example usage
+// initializeFirebaseAnalytics('YOUR_MEASUREMENT_ID', 'YOUR_API_SECRET', 'YOUR_FIREBASE_APP_ID');
+// fa_trackEvent('example_event', { param1: 'value1', param2: 'value2' });
+
+export { initializeFirebaseAnalytics, fa_trackEvent };

+ 112 - 67
src/tracking/TrackAll.js

@@ -1,119 +1,164 @@
-import {fb_trackEvent,fb_trackPageView,fb_setPixelID} from "./FacebookPixel";
-import {gg_setTagID,gtrack} from "./GoogleAnalytics";
-import {kwai_setPixelID,kwai_trackEvent} from "./KwaiPixel";
-import {loadInfoNew} from "./ApkPromote"
-export const initTrackAll = (pf_type,pf_id,ex_id) => {
-    if(pf_type==="fb"){
-        fb_setPixelID(pf_id,ex_id)
-    }else if(pf_type==="kw"){
-        kwai_setPixelID(pf_id,ex_id)
-    }else if(pf_type==="gg"){
-        pf_id=pf_id.split("|")
-        gg_setTagID(pf_id[0],pf_id[1]);
-    }else if(pf_type==='apk'){
-        //apk下载需要再进行一步
-        loadInfoNew(pf_id,ex_id);
+import { fb_trackEvent, fb_trackPageView, fb_setPixelID } from "./FacebookPixel";
+import { gg_setTagID, gtrack } from "./GoogleAnalytics";
+import { kwai_setPixelID, kwai_trackEvent } from "./KwaiPixel";
+import { loadInfoNew } from "./ApkPromote";
+import { initializeFirebaseAnalytics, fa_trackEvent } from "./FirebaseAnalytics"; // Import Firebase functions
+
+export const initTrackAll = (pf_type, pf_id, ex_id) => {
+    if (pf_type === "fb") {
+        fb_setPixelID(pf_id, ex_id);
+    } else if (pf_type === "kw") {
+        kwai_setPixelID(pf_id, ex_id);
+    } else if (pf_type === "gg") {
+        pf_id = pf_id.split("|");
+        gg_setTagID(pf_id[0], pf_id[1]);
+    } else if (pf_type === 'apk') {
+        // apk下载需要再进行一步
+        loadInfoNew(pf_id, ex_id);
         return;
-    }
-    window.addEventListener('installready', function(){
-        //Show your own installation UI
-        if(pf_type==="fb"){
-            trackEvent("InstallPWA")
-        }else if(pf_type==="kw"){
-            trackEvent("download")
-        }else if(pf_type==="gg"){
-            trackEvent("file_download")
+    } else if (pf_type === 'fire') {
+        // Initialize Firebase Analytics
+        let vars=global.getUrlvars()
+        if(typeof vars=="string")vars=JSON.parse(vars)
+        if(!!vars.measurement_id) {
+            const measurementId = vars.measurement_id; // Assuming pf_id is measurementId
+            const apiSecret = vars.api_secret; // Assuming ex_id is apiSecret
+            const firebaseAppId = vars.firebase_app_id; // Replace with your Firebase App ID
+            const clientId = vars.app_instance_id; // Replace with your Firebase App ID
+            initializeFirebaseAnalytics(measurementId, apiSecret, firebaseAppId, clientId);
         }
+    }
 
+    window.addEventListener('installready', function () {
+        // Show your own installation UI
+        if (pf_type === "fb") {
+            trackEvent("InstallPWA");
+        } else if (pf_type === "kw") {
+            trackEvent("download");
+        } else if (pf_type === "gg") {
+            trackEvent("file_download");
+        } else if (pf_type === "fire") {
+            fa_trackEvent("install_ready", {}); // Example event for Firebase
+        }
     });
 }
 
 export const trackPageView = () => {
-    if (window.fbq&&global.pf&&global.pf.type==='fb') {
+    if (window.fbq && global.pf && global.pf.type === 'fb') {
         fb_trackEvent();
     }
 };
 
 export const trackEvent = (eventName, params) => {
-    if (window.gtag&&global.pf&&global.pf.type==='gg') {
-        if(eventName==="pay"){
-            let data=params;
-            if(data.first) {
-                if (!!data.isd0) {
-                    gtrack("d0", {currency:'BRL',value:data.golds,transaction_id:data.order_sn})
+    const pf_type = global.pf && global.pf.type; // Get the platform type
 
+    // Handle Google Analytics events
+    if (pf_type === 'gg') {
+        if (eventName === "pay") {
+            let data = params;
+            if (data.first) {
+                if (!!data.isd0) {
+                    gtrack("d0", { currency: global.currency, value: data.golds, transaction_id: data.order_sn });
                 }
-                gtrack("d1", {currency:'BRL',value:data.golds,transaction_id:data.order_sn})
-
-            }else if(!data.isd0){
-                gtrack("repay", {currency:'BRL',value:data.golds,transaction_id:data.order_sn})
+                gtrack("d1", { currency: global.currency, value: data.golds, transaction_id: data.order_sn });
+            } else if (!data.isd0) {
+                gtrack("repay", { currency: global.currency, value: data.golds, transaction_id: data.order_sn });
             }
-
-            gtrack('purchase', {currency:'BRL',value:data.golds,transaction_id:data.order_sn});
-        }else{
+            gtrack('purchase', { currency: global.currency, value: data.golds, transaction_id: data.order_sn });
+        } else {
             gtrack(eventName, params);
         }
     }
-    if (window.fbq&&global.pf&&global.pf.type==='fb') {
-        if(eventName==="pay"){
-            let data=params;
-            if(data.first) {
-                if (!!data.isd0) {
-                    fb_trackEvent("firstpayD0", {external_id: data.udid})
 
+    // Handle Facebook events
+    if (pf_type === 'fb') {
+        if (eventName === "pay") {
+            let data = params;
+            if (data.first) {
+                if (!!data.isd0) {
+                    fb_trackEvent("firstpayD0", { external_id: data.udid });
                     fb_trackEvent('AddToWishlist', {
                         value: data.golds,
-                        currency: 'BRL',
+                        currency: global.currency,
                         external_id: data.udid
                     });
                 }
-                fb_trackEvent("firstpayD1", {external_id: data.udid})
+                fb_trackEvent("firstpayD1", { external_id: data.udid });
                 fb_trackEvent('AddToCart', {
                     value: data.golds,
-                    currency: 'BRL',
+                    currency: global.currency,
                     external_id: data.udid
                 });
-            }else if(!data.isd0){
-                fb_trackEvent("payagain", {external_id: data.udid})
+            } else if (!data.isd0) {
+                fb_trackEvent("payagain", { external_id: data.udid });
                 fb_trackEvent('InitiateCheckout', {
                     value: data.golds,
-                    currency: 'BRL',
+                    currency: global.currency,
                     external_id: data.udid
                 });
             }
-
             fb_trackEvent('Purchase', {
                 value: data.golds,
-                currency: 'BRL',
-                external_id:data.udid
+                currency: global.currency,
+                external_id: data.udid
             });
-        }else{
+        } else if (eventName === "CompleteRegistration") {
+            fb_trackEvent('CompleteRegistration', { external_id: params.udid });
+        } else {
             fb_trackEvent(eventName, params);
         }
     }
-    if (window.kwaiq&&global.pf&&global.pf.type==='kw') {
-        if(eventName==="pay"){
-            let data=params;
-            let addParams={
+
+    // Handle Kwai events
+    if (pf_type === 'kw') {
+        if (eventName === "pay") {
+            let data = params;
+            let addParams = {
                 value: data.golds,
-                currency: 'BRL',
+                currency: global.currency,
                 mapping_id: data.udid
             };
-            if(data.first) {
+            if (data.first) {
                 if (!!data.isd0) {
-                    kwai_trackEvent('firstDeposit', addParams)
+                    kwai_trackEvent('firstDeposit', addParams);
                     kwai_trackEvent('addToWishlist', addParams);
                 }
                 kwai_trackEvent('addToCart', addParams);
-            }else if(!data.isd0){
-                kwai_trackEvent("payagain", addParams)
-                kwai_trackEvent("initiatedCheckout", addParams)
+            } else if (!data.isd0) {
+                kwai_trackEvent("payagain", addParams);
+                kwai_trackEvent('initiatedCheckout', addParams);
             }
-
             kwai_trackEvent('purchase', addParams);
-        }else{
-            if(eventName==='CompleteRegistration')eventName='completeRegistration';
+        } else {
+            if (eventName === 'CompleteRegistration') eventName = 'completeRegistration';
             kwai_trackEvent(eventName, params);
         }
     }
+
+    // Check if the platform is Firebase and send the event
+    if (pf_type === 'fire') {
+        if (eventName === "pay") {
+            let data = params;
+            let addParams={
+                price: data.golds,
+                currency: global.currency,
+                mapping_id: data.udid
+            }
+            if (data.first) {
+                if (!!data.isd0) {
+                    fa_trackEvent('first_purchase_today', addParams);
+                }
+                kwai_trackEvent('first_purchase', addParams);
+            } else if (!data.isd0) {
+                kwai_trackEvent("purchase_again", addParams);
+            }
+            fa_trackEvent('purchase',addParams );
+        } else if (eventName === "CompleteRegistration") {
+            fa_trackEvent('registration_success', { external_id: params.udid });
+        } else if (eventName === "EnterGame") {
+            fa_trackEvent('enter_game', params);
+        } else {
+            fa_trackEvent(eventName, params); // Send other events to Firebase
+        }
+    }
 };