File: /home/storage/5/78/dd/wicomm2/public_html/clientes/eucatex/hook/index.php
<?php
require 'masterdata_saver.php';
$expectedToken = 'TOBKCMNYXCXZWZCNXTZAAHHUSVWPOGNJGDWHAIWNOTGKGUWHRFHRYRLFJSEOFPDPNEWZWDIEWXNWNLWSXVPODRWJDDQSPLQGGCYQLKSAVHBVEINUONIAEPNOSUCTYVOX';
$apiKey = 'vtexappkey-lojaeucatex-CZXEWO';
$apiToken = 'TOBKCMNYXCXZWZCNXTZAAHHUSVWPOGNJGDWHAIWNOTGKGUWHRFHRYRLFJSEOFPDPNEWZWDIEWXNWNLWSXVPODRWJDDQSPLQGGCYQLKSAVHBVEINUONIAEPNOSUCTYVOX';
$accountName = 'lojaeucatex';
$logFile = __DIR__ . '/hook_debug_log.txt';
function logDebug($message)
{
global $logFile;
$timestamp = date("Y-m-d H:i:s");
file_put_contents($logFile, "[$timestamp] $message\n", FILE_APPEND);
}
if (!function_exists('str_ends_with')) {
function str_ends_with($haystack, $needle)
{
return substr($haystack, -strlen($needle)) === $needle;
}
}
function formatAddress($address)
{
return ($address['street'] ?? '') . ', ' . ($address['number'] ?? '') .
(isset($address['complement']) ? ' - ' . $address['complement'] : '') .
' - ' . ($address['neighborhood'] ?? '') . ', ' . ($address['city'] ?? '') .
' - ' . ($address['state'] ?? '') . ', ' . ($address['postalCode'] ?? '');
}
function formatVtexDateBr(?string $iso8601, string $tz = 'America/Sao_Paulo'): ?string {
if (empty($iso8601)) return null;
$sanitized = preg_replace('/\.(\d{1,6})\d+/', '.$1', $iso8601);
try {
$dt = new DateTimeImmutable($sanitized);
$dt = $dt->setTimezone(new DateTimeZone($tz));
return $dt->format('d/m/Y');
} catch (Exception $e) {
return null;
}
}
function humanizeShippingEstimate(?string $estimate): ?string {
if (empty($estimate)) return null;
if (!preg_match('/^(\d+)\s*([a-zA-Z]+)$/', trim($estimate), $m)) {
return $estimate; // formato inesperado: retorna cru
}
$n = (int) $m[1];
$u = strtolower($m[2]);
switch ($u) {
case 'bd':
return $n === 1 ? '1 dia útil' : "$n dias úteis";
case 'h':
return $n === 1 ? '1 hora' : "$n horas";
case 'd':
return $n === 1 ? '1 dia' : "$n dias";
case 'm':
return $n === 1 ? '1 minuto' : "$n minutos";
default:
return $estimate;
}
}
function vtexGetRequest($url, $apiKey, $apiToken)
{
$headers = [
"Accept: application/json",
"Content-Type: application/json",
"X-VTEX-API-AppKey: $apiKey",
"X-VTEX-API-AppToken: $apiToken"
];
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
return curl_exec($ch);
}
function vtexPostRequest($url, $apiKey, $apiToken, $data)
{
$headers = [
"Accept: application/json",
"Content-Type: application/json",
"X-VTEX-API-AppKey: $apiKey",
"X-VTEX-API-AppToken: $apiToken"
];
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data));
return curl_exec($ch);
}
logDebug("=== New VTEX Hook Received ===");
$headers = getallheaders();
$body = file_get_contents("php://input");
if (!isset($headers['Token']) || $headers['Token'] !== $expectedToken) {
logDebug("❌ Invalid token");
http_response_code(403);
exit;
}
$data = json_decode($body, true);
if (empty($data) || !isset($data['OrderId'], $data['State'])) {
logDebug("⚠️ Invalid or test payload");
http_response_code(200);
echo "OK";
exit;
}
$orderId = $data['OrderId'];
$currentState = $data['State'];
logDebug("=== HOOK INFORMATION ===");
logDebug("Order ID: $orderId, Status: $currentState");
// Fetch full order
$orderUrl = "https://$accountName.vtexcommercestable.com.br/api/oms/pvt/orders/$orderId";
$orderResponse = vtexGetRequest($orderUrl, $apiKey, $apiToken);
$order = json_decode($orderResponse, true);
if (isset($order['status']) && $order['status'] === 401) {
logDebug("❌ Unauthorized to access VTEX OMS API.");
http_response_code(401);
exit;
}
saveToMasterData($order, $orderId, $apiKey, $apiToken, $accountName, $currentState);
http_response_code(200);
echo json_encode(["message" => "Processed"]);