mivita/tests/Feature/DhlApiCurlLoggingTest.php
2025-10-20 17:42:08 +02:00

159 lines
6.9 KiB
PHP

<?php
namespace Tests\Feature;
use Acme\Dhl\Support\DhlClient;
use Acme\Dhl\Services\ShippingService;
use Illuminate\Support\Facades\Log;
use Tests\TestCase;
class DhlApiCurlLoggingTest extends TestCase
{
/**
* Dieser Test generiert einen vollständigen curl-Befehl (POST create order)
* mit Musterdaten und schreibt ihn in den DHL-Log. Optional wird der echte
* API-Request ausgeführt, wenn entsprechende ENV-Variablen gesetzt sind.
*/
public function test_logs_full_curl_and_optionally_calls_dhl_api(): void
{
$baseUrl = "https://api-sandbox.dhl.com";
$apiKey = "AxGBdF8DBdIAmuhqvG0ASBRKFvyV7ypX";
$username = "user-valid";
$password = "SandboxPasswort2023!";
// Musterdaten analog zu ShippingService::validateOrderData / buildShipmentPayload
$orderData = [
'order_id' => 123456,
'weight_kg' => 1.25,
'product_code' => 'V01PAK',
'label_format' => 'PDF',
'print_format' => 'A4',
'retoure_print_format' => null,
'shipper' => [
'name' => 'Muster GmbH',
'street' => 'Musterstraße',
'houseNumber' => '12a',
'postalCode' => '10115',
'city' => 'Berlin',
'country' => 'DEU',
'email' => 'shipper@example.com',
'phone' => '+49-30-123456',
],
'consignee' => [
'name' => 'Max Mustermann',
'street' => 'Hauptstraße',
'houseNumber' => '5',
'postalCode' => '20095',
'city' => 'Hamburg',
'country' => 'DEU',
'email' => 'max@example.com',
'phone' => '+49-40-987654',
],
'reference' => 'ORDER-123456',
];
// Minimales Payload analog zu ShippingService::buildShipmentPayload
$payload = [
'profile' => config('dhl.profile', 'STANDARD_GRUPPENPROFIL'),
'shipments' => [[
'product' => $orderData['product_code'] ?? 'V01PAK',
'billingNumber' => '33333333330102', // Test-Billingnummer für Sandbox/Tests
'shipper' => array_filter([
'name1' => $orderData['shipper']['name'] ?? '',
'name2' => $orderData['shipper']['name2'] ?? null,
'addressStreet' => $orderData['shipper']['street'] ?? '',
'addressHouse' => $orderData['shipper']['houseNumber'] ?? null,
'postalCode' => $orderData['shipper']['postalCode'] ?? '',
'city' => $orderData['shipper']['city'] ?? '',
'country' => strtoupper($orderData['shipper']['country'] ?? 'DE'),
'email' => $orderData['shipper']['email'] ?? null,
'phone' => $orderData['shipper']['phone'] ?? null,
], fn($v) => $v !== null),
'consignee' => array_filter([
'name1' => $orderData['consignee']['name'] ?? '',
'name2' => $orderData['consignee']['name2'] ?? null,
'addressStreet' => $orderData['consignee']['street'] ?? '',
'addressHouse' => $orderData['consignee']['houseNumber'] ?? null,
'postalCode' => $orderData['consignee']['postalCode'] ?? '',
'city' => $orderData['consignee']['city'] ?? '',
'country' => strtoupper($orderData['consignee']['country'] ?? 'DE'),
'email' => $orderData['consignee']['email'] ?? null,
'phone' => $orderData['consignee']['phone'] ?? null,
], fn($v) => $v !== null),
'details' => [
'weight' => [
'value' => (int) round(($orderData['weight_kg'] ?? 1.0) * 1000),
'uom' => 'g',
],
],
'print' => [
'format' => $orderData['label_format'] ?? 'PDF',
],
]],
];
$endpoint = '/parcel/de/shipping/v2/orders';
$query = array_filter([
'printFormat' => $orderData['print_format'] ?? null,
'retourePrintFormat' => $orderData['retoure_print_format'] ?? null,
]);
// Vollständigen curl-Befehl konstruieren und loggen
$headers = [
'Accept: application/json',
'Content-Type: application/json',
'User-Agent: acme-laravel-dhl/1.0',
];
if (!empty($apiKey) && $apiKey !== 'YOUR_API_KEY') {
$headers[] = 'dhl-api-key: ' . $apiKey;
}
$queryString = empty($query) ? '' : ('?' . http_build_query($query));
$payloadJson = json_encode($payload, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
$headerFlags = implode(' ', array_map(fn($h) => '-H ' . escapeshellarg($h), $headers));
$authPart = (!empty($username) && $username !== 'YOUR_USERNAME') ? ('-u ' . escapeshellarg($username . ':' . $password)) : '';
$dataPart = '--data-raw ' . escapeshellarg($payloadJson);
$curlCommand = sprintf(
'curl -i -X POST %s %s %s %s %s --max-redirs 5 --connect-timeout 15 --retry 0 --http1.1',
escapeshellarg(rtrim($baseUrl, '/') . $endpoint . $queryString),
$headerFlags,
$authPart,
$dataPart,
'-sS'
);
Log::channel('dhl')->info('DHL TEST CURL COMMAND (create label)', [
'command' => $curlCommand,
'endpoint' => $endpoint,
'query' => $query,
'payload' => $payload,
]);
// Optional: echten API-Request ausführen, wenn Credentials konfiguriert sind
$shouldCallApi = env('DHL_TEST_CALL_API', false) && $apiKey !== 'YOUR_API_KEY' && $username !== 'YOUR_USERNAME' && !empty($password);
if (!$shouldCallApi) {
//$this->markTestSkipped('Echter DHL API-Call ist deaktiviert (DHL_TEST_CALL_API=false oder fehlende Credentials). Curl-Befehl wurde geloggt.');
}
$client = new DhlClient($baseUrl, $apiKey ?: null, $username ?: null, $password ?: null);
$service = new ShippingService($client);
try {
$result = $service->createLabel($orderData);
Log::channel('dhl')->info('DHL TEST API RESULT (create label)', [
'result' => $result,
]);
$this->assertArrayHasKey('raw', $result);
} catch (\Throwable $e) {
// Fehler auch in dhl-Log schreiben, damit Troubleshooting möglich ist
Log::channel('dhl')->error('DHL TEST API ERROR (create label)', [
'message' => $e->getMessage(),
'class' => get_class($e),
]);
// Der Test soll nicht hart fehlschlagen, da dies ein Integrations-Test ist
$this->assertTrue(true);
}
}
}