File: /home/storage/5/78/dd/wicomm2/public_html/clientes/dpaschoal/hook/ga4_tracker.php
<?php
function trackPurchaseGA4($order, $orderId, $currentState)
{
if ($currentState !== 'order-created') {
logDebug("Skipping event because state is $currentState");
return;
}
$orderId = str_replace('-01', '', $order['orderId']);
$lockFile = sys_get_temp_dir() . "/ga4_lock_{$orderId}.lock";
$fp = fopen($lockFile, 'c');
if (!$fp || !flock($fp, LOCK_EX | LOCK_NB)) {
logDebug("Order $orderId is already being processed. Lock in place.");
return;
}
try {
if (isOrderAlreadyTracked($orderId)) {
logDebug("Order $orderId already tracked. Skipping GA4.");
return;
}
$currency = 'BRL';
$affiliation = $order['sellers'][0]['name'] ?? 'dpaschoal';
$totalValue = ($order['value'] ?? 0) / 100;
$totalValue = round($totalValue, 2);
$totalValue = number_format($totalValue, 2, '.', '');
$shippingValue = 0;
foreach ($order['totals'] ?? [] as $total) {
if ($total['id'] === 'Shipping') {
$shippingValue = $total['value'] / 100;
break;
}
}
$items = [];
foreach ($order['items'] ?? [] as $item) {
$id = (string)($item['id'] ?? '');
$variant = (string)($item['refId'] ?? $id);
$quantity = (int)($item['quantity'] ?? 1);
$brand = $item['additionalInfo']['brandName'] ?? 'DPASCHOAL';
$categories = $item['additionalInfo']['categories'] ?? [];
$category1 = $categories[2]['name'] ?? null;
$category2 = $categories[1]['name'] ?? null;
$category3 = $categories[0]['name'] ?? null;
$unitPrice = ($item['sellingPrice'] ?? 0) / 100;
$unitPrice = round($unitPrice, 2);
$unitPrice = number_format($unitPrice, 2, '.', '');
// Differentiate items by ID + Variant
$key = $id . '-' . $variant;
if (isset($items[$key])) {
$items[$key]['quantity'] += $quantity;
} else {
$items[$key] = [
'item_id' => $id,
'item_name' => $item['name'] ?? '',
'item_brand' => $brand,
'item_variant' => $variant,
'price' => $unitPrice,
'quantity' => $quantity,
'item_category' => $category1,
'item_category2' => $category2,
'item_category3' => $category3
];
}
}
$clientId = '000000.000000';
$sessionId = (int)(microtime(true) * 1000);
if (!empty($order['marketingData']['utmiPart'])) {
$utmiPartRaw = $order['marketingData']['utmiPart'];
$utmiPartDecoded = json_decode($utmiPartRaw, true);
if (is_array($utmiPartDecoded) && isset($utmiPartDecoded[0]['client_id'])) {
$clientId = $utmiPartDecoded[0]['client_id'];
if (isset($utmiPartDecoded[0]['session_id'])) {
$sessionRaw = $utmiPartDecoded[0]['session_id'];
$parts = explode('.', $sessionRaw);
$sessionId = isset($parts[1]) ? $parts[1] : (int)(microtime(true) * 1000);
} else {
$sessionId = (int)(microtime(true) * 1000);
}
} else {
$clientId = $order['marketingData']['utmiPart'];
}
}
$clientEmail = $order['clientProfileData']['email'] ?? '';
$timestampMicros = strtotime($order['creationDate'] ?? 'now') * 1000000;
$utm = $order['marketingData'] ?? [];
$customerEmailDecrypted = null;
if (!empty($order['marketingData']['utmipage'])) {
$utmiPageData = $order['marketingData']['utmipage'];
$jsonDecoded = json_decode($utmiPageData, true);
if (is_array($jsonDecoded) && isset($jsonDecoded[0]['userProperties'])) {
$encodedEmail = $jsonDecoded[0]['userProperties'];
$customerEmailDecrypted = base64_decode($encodedEmail);
} else {
$customerEmailDecrypted = base64_decode($utmiPageData);
}
}
$payload = [
"client_id" => $clientId,
"timestamp_micros" => $timestampMicros,
"user_properties" => [
"email" => ["value" => $customerEmailDecrypted],
"utm_source" => ["value" => $utm['utmSource'] ?? ''],
"utm_medium" => ["value" => $utm['utmMedium'] ?? ''],
"utm_campaign" => ["value" => $utm['utmCampaign'] ?? ''],
"utm_term" => ["value" => $utm['utmTerm'] ?? ''],
"utm_content" => [ "value" => $utm['utmContent'] ?? '' ],
],
"events" => [[
"name" => "purchase",
"params" => [
"transaction_id" => str_replace('-01', '', $orderId),
"affiliation" => $affiliation,
'value' => $totalValue,
"currency" => $currency,
"shipping" => $shippingValue,
"tax" => 0,
"payment_type" => $order['paymentData']['transactions'][0]['payments'][0]['paymentSystemName'] ?? 'unknown',
"coupon" => $utm['coupon'] ?? '',
"engagement_time_msec" => 100,
'session_id' => $sessionId,
"items" => array_values($items)
]
]]
];
//$measurement_id = 'G-WVXCYXDLPQ';
$measurement_id = 'G-7M542E4ST5';
$api_secret = 'owYnXKO2TKO5G3OVPtj2Ag';
//$api_secret = '6wrSy_lwTNeCTPkyxgik1g';
$ga4Url = "https://www.google-analytics.com/mp/collect?measurement_id=$measurement_id&api_secret=$api_secret";
$response = sendGA4Request($ga4Url, $payload);
logDebug("GA4 Payload Sent: " . json_encode($payload));
logDebug("GA4 Response: " . $response);
$saveSuccess = saveOrderTracked($orderId);
if ($saveSuccess) {
logDebug("Order $orderId successfully saved to Master Data.");
} else {
logDebug("Failed to save order $orderId to Master Data.");
}
} finally {
flock($fp, LOCK_UN);
fclose($fp);
if (file_exists($lockFile)) {
unlink($lockFile);
}
}
}