demo_json <- system.file("example", "pubsub-ga4.json", package = "measurementProtocol")
demo_list <- jsonlite::fromJSON(demo_json)
# extract the event_name
name_f <- function(x) x[["event_name"]]
# extract client_id
client_id_f <- function(x) x[["client_id"]]
# extract user_id
user_id_f <- function(x) x[["user_id"]]
# simple event
mp_parse_json(demo_list,
name_f,
client_id_f = client_id_f,
user_id_f = user_id_f)
# params could be assumed to be everything not a event_name of client_id
# also not allowed any starting with reserved 'ga_'
params_f <- function(x){
x_names <- names(x)[grepl("^x-", names(x))]
ga_names <- names(x)[grepl("^ga_", names(x))]
x[setdiff(names(x), c("client_id","user_id" ,"event_name", x_names, ga_names))]
}
# parse including params (could include items as well)
parsed_event <- mp_parse_json(demo_list,
name_f,
params_f = params_f,
client_id_f = client_id_f,
user_id_f = user_id_f)
parsed_event
# sending to a debug endpoint
# preferably set this in .Renviron
Sys.setenv(MP_SECRET="MY_SECRET")
# replace with your GA4 settings
my_measurement_id <- "G-1234"
my_connection <- mp_connection(my_measurement_id)
mp_send(parsed_event$mp_event,
client_id = parsed_event$user$client_id,
user_id = parsed_event$user$user_id,
user_properties = parsed_event$user$user_properties,
connection = my_connection,
debug_call = TRUE)
# mp_parse_gtm internally uses functions demonstrated with mp_parse_json
pubsub_event <- mp_parse_gtm(demo_json)
mp_send(pubsub_event$mp_event,
client_id = pubsub_event$user$client_id,
user_id = pubsub_event$user$user_id,
user_properties = pubsub_event$user$user_properties,
connection = my_connection,
debug_call = TRUE)
if (FALSE) {
#* Send forward a measurement protocol hit
#* @post /gtm
#* @serializer unboxedJSON
#* @parser json
function(req, res, ga_id) {
pubsub_data <- mp_pubsub_parse(req$postBody)
parsed <- mp_parse_gtm(pubsub_data)
my_connection <- mp_connection(ga_id)
mp_send(parsed$mp_event,
client_id = parsed$user$client_id,
user_id = parsed$user$user_id,
user_properties = parsed$user$user_properties,
connection = my_connection)
"OK"
}
}
Run the code above in your browser using DataLab