Skip to content

Instantly share code, notes, and snippets.

@xlplugins
Last active January 3, 2025 04:33
Show Gist options
  • Save xlplugins/a80865a51bdf00f1ebdd81531f6bb045 to your computer and use it in GitHub Desktop.
Save xlplugins/a80865a51bdf00f1ebdd81531f6bb045 to your computer and use it in GitHub Desktop.
Server-side GTM integration
// Define GTM Server Container URL (replace with your container endpoint)
$gtmEndpoint = "https://<your-gtm-server>.appspot.com";
// Example Conversion Data
$data = [
"event_name" => "purchase", // Event name, e.g., 'purchase', 'lead'
"conversion_tracking_id" => "AW-XXXXXXX", // Replace with your Google Ads conversion ID
"transaction_id" => "12345", // Unique transaction ID
"value" => 100.0, // Conversion value
"currency" => "USD", // Currency code
"user_data" => [
"email" => hash('sha256', "[email protected]"), // Hashed email (SHA256)
"phone_number" => hash('sha256', "+1234567890"), // Hashed phone (optional)
"client_ip" => $_SERVER['REMOTE_ADDR'], // Client IP (optional)
"user_agent" => $_SERVER['HTTP_USER_AGENT'], // User Agent (optional)
]
];
// Send data to GTM Server
function sendToGtm($endpoint, $payload) {
$ch = curl_init($endpoint);
// Set cURL options
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, [
'Content-Type: application/json',
]);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($payload));
// Execute cURL request
$response = curl_exec($ch);
if ($response === false) {
$error = curl_error($ch);
curl_close($ch);
throw new Exception("cURL Error: $error");
}
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);
if ($httpCode !== 200) {
throw new Exception("Server returned HTTP code $httpCode with response: $response");
}
return json_decode($response, true);
}
try {
$response = sendToGtm($gtmEndpoint, $data);
echo "Data sent successfully: " . print_r($response, true);
} catch (Exception $e) {
echo "Error: " . $e->getMessage();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment