add user id to api calls

This commit is contained in:
mc18g13 2024-05-12 21:37:33 +01:00
parent 24d9a7ff62
commit c9c813ec4e
2 changed files with 17 additions and 11 deletions

View File

@ -18,11 +18,11 @@ def send_event(data):
return _mp_api_handler({ return _mp_api_handler({
"action": data["object"], "action": data["object"],
"payload": data["payload"], "payload": data["payload"],
}) }, user_id=data["user_id"])
if data["event"] == EVENT_DOWNLOAD: if data["event"] == EVENT_DOWNLOAD:
return _mp_download_handler({"payload": { return _mp_download_handler({"payload": {
"resource_id": data["id"], "resource_id": data["id"]
}}) }})
log.warning("Only API and Download events supported by Measurement Protocol at the moment") log.warning("Only API and Download events supported by Measurement Protocol at the moment")
@ -36,7 +36,7 @@ class SafeJSONEncoder(json.JSONEncoder):
return None return None
def _mp_api_handler(data_dict): def _mp_api_handler(data_dict, user_id=None):
log.debug( log.debug(
"Sending API event to Google Analytics using the Measurement Protocol: %s", "Sending API event to Google Analytics using the Measurement Protocol: %s",
data_dict data_dict
@ -44,7 +44,7 @@ def _mp_api_handler(data_dict):
_mp_event({ _mp_event({
"name": data_dict["action"], "name": data_dict["action"],
"params": data_dict["payload"] "params": data_dict["payload"]
}) }, user_id=user_id)
def _mp_download_handler(data_dict): def _mp_download_handler(data_dict):
@ -58,18 +58,23 @@ def _mp_download_handler(data_dict):
}) })
def _mp_event(event): def _mp_event(event, user_id=None):
data = {
"client_id": config.measurement_protocol_client_id(),
"non_personalized_ads": False,
"events": [event]
}
if user_id:
data["user_id"] = user_id
resp = requests.post( resp = requests.post(
"https://www.google-analytics.com/mp/collect", "https://www.google-analytics.com/mp/collect",
params={ params={
"api_secret": config.measurement_protocol_client_secret(), "api_secret": config.measurement_protocol_client_secret(),
"measurement_id": config.measurement_id() "measurement_id": config.measurement_id(),
}, },
data=json.dumps({ data=json.dumps(data, cls=SafeJSONEncoder)
"client_id": config.measurement_protocol_client_id(),
"non_personalized_ads": False,
"events": [event]
}, cls=SafeJSONEncoder)
) )
if resp.status_code >= 300: if resp.status_code >= 300:

View File

@ -101,6 +101,7 @@ def _post_analytics(
"function": request_function, "function": request_function,
"id": request_id, "id": request_id,
"payload": request_payload, "payload": request_payload,
"user_id": hashlib.md5(six.ensure_binary(tk.c.user)).hexdigest()
}) })
else: else: