I need to track purchases in GA4. I am using the Google Analytics Measurement Protocol.
I have a listener that is a web server written in .Net Core. Everytime a payment happens in my platform, the payment provider call my listener where I register the payment. Contextually, I need to track the payment on GA4.
Here the code I am using:
public async Task TrackPaymentAsync(string measurementId, string apiSecret, PaymentData paymentData)
{
string url = $"https://www.google-analytics.com/mp/collect?measurement_id=${measurementId}&api_secret=${apiSecret}";
string requestData = $@"
{{
""client_id"": ""{paymentData.GAClientId}"",
""user_id"": ""{paymentData.UserId}"",
""events"": [{{
""name"": ""purchase"",
""params"": {{
""currency"": ""EUR"",
""value"": ""{paymentData.Amount}"",
""transaction_id"": ""{paymentData.TransactionId}"",
""debug_mode"": true
}}
}}],
""user_data"": {{
""amount"": ""{paymentData.Amount}"",
""fee"": ""{paymentData.Fee}"",
""item_name"": ""{paymentData.ItemName}"",
""payment_method"": ""{paymentData.PaymentMethod}""
}}
}}
";
using (HttpClient client = new HttpClient())
{
var content = new StringContent(requestData, Encoding.ASCII, "application/json");
HttpResponseMessage response = await client.PostAsync(url, content);
response.EnsureSuccessStatusCode();
//string responseBody = await response.Content.ReadAsStringAsync();
}
}
The payload is a mix of the examples in Send user-provided data and Verify implementation .
I get a HTTP 204
but nothing happen on GA4.
I have some doubts:
- First of all, I got the measurement id from GA4 -> My prop -> Admin -> Data Streams . The doubt I have is the stream url… it is different from the listener url. The listener is “outside” my domain. I also would like to test the listener from localhost. Is it possible?
- The guide says:
You must use tagging (gTag, Tag Manager, or Google Analytics for Firebase) to use this protocol.
. I am not using any of them. Is it strictly required use one of them?
Can anyone help me please?
Thank you