Nils Deschrijver
Nils Deschrijver

Reputation: 41

Google Analytics Measurement Protocol (GA4) Events not showing in dashboard

I code the API/back-end and do not have a website/front-end yet with GTAG (Manager) implemented. For testing, I make a POST request to my endpoint /analytics/store-id using a fake but valid client_id. The session_id is then server-generated using uuid4, and both are added to the session['user'] FlaskRestX session.

Normally, the GTAG is on every webpage; it generates and then sends the API the client_id. This gets checked before every POST request, see api.py below. In another /basket POST Resource/endpoint, it then tries to submit this event, using the client_id and session_id as stored in the user's cookie, again see api.py.

I'll provide one Event, verified to be valid.

Normal flow:

api.py:

# API Resource with customised Namespace for processing tracking ids 
@analytics_ns.route('/store-id')
class StoreAnalyticsIDs(Resource):
    manageIDs_schema = defineIDsSchema()
  
def post(self):
    # In Try Except block
    # Validation code
    # Storing ids in the session
    if 'user' not in session:
        session['user'] = {}

        session_id = str(uuid.uuid4()) # Generated server-side
        session['user'] = {"client_id": args['client_id'], "session_id": session_id} # Generated client-side

        session.modified = True  # Mark session as modified to ensure it gets saved
        return {f"message": "Successfully registered the ID."}, 200
    else:
        raise ValidationError("Duplicate client_id; already registered.")

# Before every app.route POST request, ensure client_id and session_id are set
@app.before_request
def ensure_ids_in_session():
    if request.method == "POST" and request.endpoint != 'analytics_store_analytics_i_ds': # Allow GET requests that set client_id and @analytics_ns.route
        if 'user' not in session:
            return {"message": "Requirement not met: submit client_id before any POST requests."}, 500

# API Resource for adding and removing products to and from the basket, and fetching products from the basket
@api.route('/basket')
class manageBasket(Resource):
    # Some more code
    send_basket_manipulation_to_google_analytics(args['productid'], "Added")

analytics.py:

import requests, os
from flask import session

#> Google Analytics server-side manual tracking via Google Analytics Measurement Protocol (GA4) <> client-side automatic tracking via GTAG
GA_MEASUREMENT_ID = os.getenv('GA_MEASUREMENT_ID')  # GA4 Measurement ID (G-XXXXXXXXXX)
GA_API_SECRET = os.getenv('GA_API_SECRET')  # GA4 API Secret
GA_MEASUREMENT_PROTOCOL_URL = "https://www.google-analytics.com/mp/collect"

# Helper function to send the request
def send_analytics(payload):
    try:
        # Prepare the data
        params = {
            "api_secret": GA_API_SECRET,
            "measurement_id": GA_MEASUREMENT_ID
        }

        # Send the request
        response = requests.post(GA_MEASUREMENT_PROTOCOL_URL, params=params, json=payload)

    except requests.exceptions.RequestException as e:
        # Catch any request-related exceptions (e.g., connection errors)
        print(f"Error sending data to Google Analytics: {e}")
    except Exception as e:
        # Catch any other exceptions
        print(f"Unexpected error: {e}")

# Keep track of a user's basket manipulations
def send_basket_manipulation_to_google_analytics(productid, action):
    payload = {
        "client_id": session['user']['client_id'],          # Extracted client-side client_id
        "user_properties": {                                # Optional: Add user properties if needed
            "session_id": session['user']['session_id']     # Extracted client-side session_id
        },
        "events": [
            {
                "name": "basket",
                "params": {
                    "session_id": session['user']['session_id'],    # Extracted client-side session_id
                    "productid": productid,                         # productid
                    "action": action                                # 'Added' or 'removed' from basket
                }
            }
        ]
    }
    send_analytics(payload)

Result: I see no Events showing up in the dashboard.

Upvotes: 0

Views: 33

Answers (0)

Related Questions