HEX
Server: Apache
System: Linux vpshost11508.publiccloud.com.br 5.15.179-grsec-vpshost-10.lc.el8.x86_64 #1 SMP Mon Apr 7 12:04:45 -03 2025 x86_64
User: wicomm2 (10002)
PHP: 8.3.0
Disabled: apache_child_terminate,dl,escapeshellarg,escapeshellcmd,exec,link,mail,openlog,passthru,pcntl_alarm,pcntl_exec,pcntl_fork,pcntl_get_last_error,pcntl_getpriority,pcntl_setpriority,pcntl_signal,pcntl_signal_dispatch,pcntl_sigprocmask,pcntl_sigtimedwait,pcntl_sigwaitinfo,pcntl_strerror,pcntl_wait,pcntl_waitpid,pcntl_wexitstatus,pcntl_wifexited,pcntl_wifsignaled,pcntl_wifstopped,pcntl_wstopsig,pcntl_wtermsig,php_check_syntax,php_strip_whitespace,popen,proc_close,proc_open,shell_exec,symlink,system
Upload Files
File: /home/storage/5/78/dd/wicomm2/public_html/clientes/dpaschoal/hook/index.php
<?php

require 'ga4_tracker.php';
require 'masterdata_saver.php';

$expectedToken = 'UORNDGPLJYXZEGAYDFBSOCYQGNYPHPBARHOBLRXEUMPXJCTOEZOJVWYEVQCJIZYUCNHKJCCOQUQUHICHXCQJGBGWQUHOIYBKNCGDGQODSXHSFVVWUHXMLWNAYUUXQURI';
$apiKey = 'vtexappkey-dpaschoal-JFAIJU';
$apiToken = 'SUXDZEQBTFRPCSQOTPQJCXMWAYLUWFTCXMUILGGTDCNKAEPETFVXYJCORGOJQMJHGYSXOXEEKXZYKAZXWEJIUKQDMPUQNNBRDZALFAYLPYXQHUQFAOXZWBATHSCFFWOS';
$accountName = 'dpaschoal';
$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 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);
}

function sendGA4Request($url, $payload) {
    $ch = curl_init($url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_POST, true);
    curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($payload));
    curl_setopt($ch, CURLOPT_HTTPHEADER, ['Content-Type: application/json']);
    $response = curl_exec($ch);
    $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    $curlError = curl_error($ch);
    $curlErrNo = curl_errno($ch);
    curl_close($ch);

    if ($curlErrNo !== 0) {
        logDebug("❌ cURL Error ($curlErrNo): $curlError");
    }

    return "HTTP $httpCode | $response";
}

function isOrderAlreadyTracked($orderId) {
    $vtexAccountName = 'dpaschoal';
    $vtexEnvironment = 'vtexcommercestable';
    $appKey = 'vtexappkey-dpaschoal-JFAIJU';
    $appToken = 'SUXDZEQBTFRPCSQOTPQJCXMWAYLUWFTCXMUILGGTDCNKAEPETFVXYJCORGOJQMJHGYSXOXEEKXZYKAZXWEJIUKQDMPUQNNBRDZALFAYLPYXQHUQFAOXZWBATHSCFFWOS';

    $url = "https://{$vtexAccountName}.{$vtexEnvironment}.com.br/api/dataentities/GA/search?_where=orderId=$orderId&_fields=orderId";

    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_HTTPHEADER, [
        "X-VTEX-API-AppKey: $appKey",
        "X-VTEX-API-AppToken: $appToken",
        "Accept: application/vnd.vtex.ds.v10+json"
    ]);

    $response = curl_exec($ch);
    curl_close($ch);

    $data = json_decode($response, true);

    if (is_array($data) && count($data) > 0) {
        return true; // Order found, already tracked
    }

    return false; // Order not found
}

function saveOrderTracked($orderId) {
    $vtexAccountName = 'dpaschoal';
    $vtexEnvironment = 'vtexcommercestable';
    $appKey = 'vtexappkey-dpaschoal-JFAIJU';
    $appToken = 'SUXDZEQBTFRPCSQOTPQJCXMWAYLUWFTCXMUILGGTDCNKAEPETFVXYJCORGOJQMJHGYSXOXEEKXZYKAZXWEJIUKQDMPUQNNBRDZALFAYLPYXQHUQFAOXZWBATHSCFFWOS';

    $url = "https://{$vtexAccountName}.{$vtexEnvironment}.com.br/api/dataentities/GA/documents";

    $payload = [
        "orderId" => $orderId
    ];

    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_POST, true);
    curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($payload));
    curl_setopt($ch, CURLOPT_HTTPHEADER, [
        "Content-Type: application/json",
        "Accept: application/vnd.vtex.ds.v10+json",
        "X-VTEX-API-AppKey: $appKey",
        "X-VTEX-API-AppToken: $appToken"
    ]);

    $response = curl_exec($ch);
    curl_close($ch);

    return json_decode($response, true);
}

// === Start Handling Request ===

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;
}

//logDebug("=== ORDER INFORMATION ===");
//logDebug(json_encode($order, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE));

if ($currentState === 'payment-approved') {
    saveToMasterData($order, $orderId, $apiKey, $apiToken, $accountName, $currentState);
}

sleep(2);

if ($currentState === 'order-created') {
    trackPurchaseGA4($order, $orderId, $currentState);
}

http_response_code(200);
echo json_encode(["message" => "Processed"]);