File: /home/storage/5/78/dd/wicomm2/public_html/clientes/eucatex/hook/masterdata_saver.php
<?php
function saveToMasterData($order, $orderId, $apiKey, $apiToken, $accountName, $currentState)
{
$email = $order['clientProfileData']['email'] ?? '';
$documento = $order['clientProfileData']['document'] ?? '';
$deliveryDate = $order['shippingData']["logisticsInfo"][0]["shippingEstimateDate"];
$deliveryTime = $order['shippingData']["logisticsInfo"][0]["shippingEstimate"];
$payload = [
"orderId" => $orderId,
"email" => $email,
"documento" => $documento,
"status" => $currentState,
"estimated_delivery_date" => formatVtexDateBr($deliveryDate),
"estimated_delivery_time" => humanizeShippingEstimate($deliveryTime),
];
$searchUrl = "https://$accountName.vtexcommercestable.com.br/api/dataentities/OK/search?_where=orderId=$orderId&_fields=id";
$headers = [
"Accept: application/json",
"Content-Type: application/json",
"X-VTEX-API-AppKey: $apiKey",
"X-VTEX-API-AppToken: $apiToken"
];
$ch = curl_init($searchUrl);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
$searchResponse = curl_exec($ch);
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);
logDebug("Search Response: $searchResponse");
sleep(10);
$existing = json_decode($searchResponse, true);
if (is_array($existing) && count($existing) > 0 && isset($existing[0]['id'])) {
$docId = $existing[0]['id'];
$updateUrl = "https://$accountName.vtexcommercestable.com.br/api/dataentities/OK/documents/$docId";
$method = 'PUT';
} else {
$updateUrl = "https://$accountName.vtexcommercestable.com.br/api/dataentities/OK/documents";
$method = 'POST';
}
$ch = curl_init($updateUrl);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, $method);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($payload));
$saveResponse = curl_exec($ch);
curl_close($ch);
logDebug("Master Data Payload: " . json_encode($payload));
logDebug("Save Response ($method): " . $saveResponse);
}