File: /home/storage/5/78/dd/wicomm2/public_html/clientes/artelasse/hooks/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'] ?? 'Artelasse';
$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'] ?? 'ARTELASSE';
$categories = $item['additionalInfo']['categories'] ?? [];
$category1 = $categories[0]['name'] ?? null;
$category2 = $categories[1]['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 ?? ''
];
}
}
$clientId = '000000.000000';
$sessionId = (int)(microtime(true) * 1000);
if (!empty($order['marketingData']['utmiPart'])) {
$utmiPartRaw = $order['marketingData']['utmiPart'];
$utmiPartDecoded = json_decode($utmiPartRaw, true);
$clientId = $utmiPartDecoded[0]['client_id'];
$sessionId = $utmiPartDecoded[0]['session_id'];
}
logDebug("UTM PART: " . json_encode($order['marketingData']));
$clientEmail = $order['clientProfileData']['email'] ?? '';
$timestampMicros = strtotime($order['creationDate'] ?? 'now') * 1000000;
$utm = $order['marketingData'] ?? [];
$utm_source = $utm['utmSource'] ?? '';
$params = [
"transaction_id" => str_replace('-01', '', $orderId),
"affiliation" => $affiliation,
"value" => floatval($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" => intval($sessionId),
"purchase_source" => "server",
"items" => array_values($items)
];
if (!empty($shippingTier)) {
$params['shipping_tier'] = $shippingTier;
}
if (!empty($shippingEstimated)) {
$params['shipping_estimate'] = $shippingEstimated;
}
$payload = [
"client_id" => $clientId,
"timestamp_micros" => $timestampMicros,
"user_properties" => [
"email" => ["value" => $customerEmailDecrypted ?? $clientEmail],
"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" => $params
]]
];
//$measurement_id = 'G-H1FVEVWLLQ';
//$api_secret = 'wI6--Vh_RlKRucKFOtTrJQ';
$measurement_id = 'G-9CMQYGE1DQ';
$api_secret = 'noGnn87DQLaWX3zHgRnR7g';
$ga4Url = "https://www.google-analytics.com/mp/collect?measurement_id=$measurement_id&api_secret=$api_secret&cs={$utm_source}";
$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);
}
}
}