Gambio --> Cashctrl - Automatische Bestellübergabe per API

Thema wurde von Anonymous, 24. Juni 2026 um 12:29 Uhr erstellt.

  1. Anonymous
    Anonymous Erfahrener Benutzer
    Registriert seit:
    13. Mai 2022
    Beiträge:
    85
    Danke erhalten:
    2
    Danke vergeben:
    28
    Hallo Zusammen

    Ich habe diese Tage mal versucht, via API von meinem Gambio Shop eine Verbindung zu CashCtrl via API zu schaffen. Leider komme ich nicht mehr weiter. Das Script läuft bei Gambio sauber durch, aber auch nicht mehr.

    Kann mir jemand was dazu sagen was im aktuellen Format falsch läuft. Der API Test in Google läuft problemlos.

    Code:
    <?php
    /**
    * Synchronisations-Skript v16 (Zurück zur stabilen Basis)
    * Lädt die standardmäßigen ersten 50 Bestellungen ohne URL-Filter.
    */
    
    // --- KONFIGURATION ---
    define('GAMBIO_URL', 'https://trainsimulator.ch');
    define('GAMBIO_USER', 'XXXXXXXX');
    define('GAMBIO_PASS', 'XXXXXXXX');
    
    define('CASHCTRL_SUBDOMAIN', 'xxxxxxxxxx');
    define('CASHCTRL_API_KEY', 'xxxxxxxxxxxx');
    define('CASHCTRL_ORDER_CATEGORY_ID', 1);
    
    define('STATUS_FILE', __DIR__ . '/last_order_id.txt');
    
    // --- HILFSFUNKTIONEN ---
    function getLastProcessedOrderId() {
        if (file_exists(STATUS_FILE)) {
            return (int)trim(file_get_contents(STATUS_FILE));
        }
        return 0;
    }
    
    function saveLastProcessedOrderId($id) {
        file_put_contents(STATUS_FILE, (int)$id);
    }
    
    // --- 1. DER STABILE BASIS-ABRUF ---
    function getGambioOrdersBase() {
        $base64Credentials = base64_encode(GAMBIO_USER . ":" . GAMBIO_PASS);
       
        // Einfache Standard-URL ohne zusätzliche Parameter. Das hat funktioniert!
        $url = GAMBIO_URL . "orders";
       
        $ch = curl_init($url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_HTTPHEADER, [
            'Content-Type: application/json',
            'Authorization: Basic ' . $base64Credentials
        ]);
       
        $response = curl_exec($ch);
        $httpCode = curl_getinfo($ch, HTTP_CODE);
        curl_close($ch);
    
        if ($httpCode !== 200) {
            die("Fehler beim Abrufen der Gambio-Bestellungen. HTTP-Code: " . $httpCode . "<br>");
        }
    
        return json_decode($response, true);
    }
    
    // --- 2. AUFTRAG IN CASHCTRL ANLEGEN ---
    function createCashCtrlOrder($gambioOrder) {
        $url = "https://" . CASHCTRL_SUBDOMAIN . "://";
        $billing  = $gambioOrder['billingAddress'];
       
        $orderData = [
            'categoryId'  => CASHCTRL_ORDER_CATEGORY_ID,
            'description' => 'Gambio Online-Bestellung #' . $gambioOrder['id'],
            'date'        => date('Y-m-d', strtotime($gambioOrder['purchaseDate'])),
           
            'associateName'    => $billing['firstName'] . ' ' . $billing['lastName'],
            'associateCompany' => $billing['company'] ?? '',
            'associateStreet'  => $billing['street'] . ' ' . ($billing['houseNumber'] ?? ''),
            'associateZip'     => $billing['postcode'],
            'associateCity'    => $billing['city'],
            'associateCountry' => $billing['countryIsoCode'],
        ];
    
        $index = 0;
        foreach ($gambioOrder['items'] as $item) {
            $orderData["items[$index][name]"]     = $item['name'];
            $orderData["items[$index][quantity]"] = $item['quantity'];
            $orderData["items[$index][price]"]    = $item['price'];
            $index++;
        }
    
        if (!empty($gambioOrder['shippingMethod']['price'])) {
            $orderData["items[$index][name]"]     = 'Versandkosten: ' . $gambioOrder['shippingMethod']['title'];
            $orderData["items[$index][quantity]"] = 1;
            $orderData["items[$index][price]"]    = $gambioOrder['shippingMethod']['price'];
        }
    
        $cashctrlAuth = base64_encode(CASHCTRL_API_KEY . ":");
    
        $ch = curl_init($url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($orderData));
        curl_setopt($ch, CURLOPT_HTTPHEADER, [
            'Authorization: Basic ' . $cashctrlAuth
        ]);
       
        $response = curl_exec($ch);
        $httpCode = curl_getinfo($ch, HTTP_CODE);
        curl_close($ch);
    
        $result = json_decode($response, true);
       
        if ($httpCode === 200 && isset($result['success']) && $result['success'] === true) {
            echo "Erfolg: Gambio-Bestellung #" . $gambioOrder['id'] . " in CashCtrl angelegt.<br>";
            return true;
        } else {
            echo "Fehler bei Gambio-Bestellung #" . $gambioOrder['id'] . " in CashCtrl:<br>";
            print_r($result);
            return false;
        }
    }
    
    // --- ABLAUF STEUERN ---
    $lastProcessedId = getLastProcessedOrderId();
    echo "Starte Abgleich. Letzte verarbeitete Gambio-ID: " . $lastProcessedId . "<br>";
    
    $allOrders = getGambioOrdersBase();
    $processedCount = 0;
    
    if (!empty($allOrders) && is_array($allOrders)) {
        foreach ($allOrders as $order) {
            $currentOrderId = (int)$order['id'];
            $currentStatusId = (int)$order['statusId'];
    
            if ($currentOrderId > $lastProcessedId) {
                // Wir schalten den Statusfilter für diesen Test aus (true),
                // damit die alten Test-Bestellungen auf jeden Fall durchgehen.
                if (true) {
                    $processedCount++;
                    $success = createCashCtrlOrder($order);
                   
                    if ($success) {
                        saveLastProcessedOrderId($currentOrderId);
                        $lastProcessedId = $currentOrderId;
                    } else {
                        echo "Synchronisation aufgrund eines Fehlers gestoppt.<br>";
                        break;
                    }
                }
            }
        }
       
        if ($processedCount === 0) {
            echo "Keine neuen Bestellungen im geladenen Paket gefunden.<br>";
        }
    } else {
        echo "Überhaupt keine Bestellungen in Gambio gefunden.<br>";
    }
    ?>