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:

  • AJAX POST request to /analytics/store-id with body {“client_id”:
    “545454.8765465”}
  • AJAX POST request to /basket with body
    {“productid”: “12345”, “quantity”: 5}

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.

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật