Created
May 20, 2025 09:57
-
-
Save RichStone/62fad2d7efba4536e306c8ed0234fc4f to your computer and use it in GitHub Desktop.
Testing Google Analytics events
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| #!/usr/bin/env ruby | |
| require 'net/http' | |
| require 'uri' | |
| require 'json' | |
| require 'time' | |
| # Configuration | |
| measurement_id = 'G-5DCEF2GTP6' | |
| api_secret = 'ivlym-UzRG--OhBZ9h7P9g' | |
| client_id = '182288249.1747727040' | |
| # Generate current timestamp in microseconds | |
| timestamp_micros = (Time.now.to_f * 1_000_000).to_i | |
| # Build the request body | |
| request_body = { | |
| client_id: client_id, | |
| timestamp_micros: timestamp_micros, | |
| events: [ | |
| { | |
| name: 'generate_lead', | |
| params: { | |
| currency: 'USD', | |
| value: 0, | |
| lead_source: 'https://funnels.myclickfunnels.test/opt' | |
| } | |
| } | |
| ] | |
| } | |
| # Create the URI for the request | |
| uri = URI.parse("https://www.google-analytics.com/mp/collect?measurement_id=#{measurement_id}&api_secret=#{api_secret}") | |
| # Create and configure the HTTP request | |
| http = Net::HTTP.new(uri.host, uri.port) | |
| http.use_ssl = true | |
| request = Net::HTTP::Post.new(uri) | |
| request['Content-Type'] = 'application/json' | |
| request.body = request_body.to_json | |
| puts "Sending GA4 event with payload:" | |
| puts JSON.pretty_generate(request_body) | |
| puts "\nTimestamp: #{timestamp_micros} (#{Time.at(timestamp_micros / 1_000_000.0)})" | |
| puts "\nSending request to: #{uri}" | |
| # Send the request and get the response | |
| response = http.request(request) | |
| puts "\nResponse status code: #{response.code}" | |
| puts "Response headers:" | |
| response.each_header do |key, value| | |
| puts " #{key}: #{value}" | |
| end | |
| puts "\nResponse body:" | |
| puts response.body.to_s | |
| # Also show the debug validation | |
| debug_uri = URI.parse("https://www.google-analytics.com/debug/mp/collect?measurement_id=#{measurement_id}&api_secret=#{api_secret}") | |
| debug_http = Net::HTTP.new(debug_uri.host, debug_uri.port) | |
| debug_http.use_ssl = true | |
| debug_request = Net::HTTP::Post.new(debug_uri) | |
| debug_request['Content-Type'] = 'application/json' | |
| debug_request.body = request_body.to_json | |
| puts "\n\nSending validation request to: #{debug_uri}" | |
| debug_response = debug_http.request(debug_request) | |
| puts "\nValidation response status code: #{debug_response.code}" | |
| puts "Validation response:" | |
| puts JSON.pretty_generate(JSON.parse(debug_response.body)) |
Author
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Successful output:
Failed output: