PHP code example of kalimeromk / postal-tracking

1. Go to this page and download the library: Download kalimeromk/postal-tracking library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

kalimeromk / postal-tracking example snippets



KalimeroMK\PostalTracking\Services\PostalTrackingService;

$service = new PostalTrackingService();
$result = $service->trackShipment('CQ117742716DE');

if ($result['success']) {
    echo "Tracking successful!\n";
    echo "Total events: " . count($result['data']) . "\n";

    foreach ($result['data'] as $event) {
        echo "- {$event['Забелешка']} on {$event['Датум']}\n";
    }
} else {
    echo "Error: " . $result['error'] . "\n";
}


use KalimeroMK\PostalTracking\Services\PostalTrackingService;

$service = new PostalTrackingService(
    timeout: 30,           // API timeout in seconds
    retryAttempts: 3,      // Number of retry attempts
    transformData: true    // Transform API response data
);

$result = $service->trackShipment('CQ117742716DE');

use KalimeroMK\PostalTracking\Laravel\Facades\PostalTracking;

// Track a shipment
$result = PostalTracking::trackShipment('CQ117742716DE');

// With options
$result = PostalTracking::trackShipment('CQ117742716DE', [
    'timeout' => 30,
    'retry_attempts' => 3,
    'transform' => true
]);


namespace App\Http\Controllers;

use Illuminate\Http\Request;
use KalimeroMK\PostalTracking\Laravel\Facades\PostalTracking;

class TrackingController extends Controller
{
    public function track(Request $request)
    {
        try {
            $trackingCode = $request->get('tracking_code');
            $result = PostalTracking::trackShipment($trackingCode);

            return response()->json($result);
        } catch (\Exception $e) {
            return response()->json([
                'success' => false,
                'error' => $e->getMessage()
            ], 422);
        }
    }
}

'providers' => [
    // ...
    KalimeroMK\PostalTracking\Laravel\PostalTrackingServiceProvider::class,
],

'aliases' => [
    // ...
    'PostalTracking' => KalimeroMK\PostalTracking\Laravel\Facades\PostalTracking::class,
],

use KalimeroMK\PostalTracking\Services\PostalTrackingService;

// In your controller
$service = new PostalTrackingService();
$trackingData = $service->trackShipment('CQ117742716DE');

// Return as JSON
Yii::$app->response->format = Response::FORMAT_JSON;
return $trackingData;


namespace app\controllers;

use yii\web\Controller;
use yii\web\Response;
use KalimeroMK\PostalTracking\Services\PostalTrackingService;

class TrackingController extends Controller
{
    public function actionTrack()
    {
        Yii::$app->response->format = Response::FORMAT_JSON;

        try {
            $trackingCode = Yii::$app->request->get('tracking_code');
            $service = new PostalTrackingService();
            $result = $service->trackShipment($trackingCode);

            return $result;
        } catch (\Exception $e) {
            Yii::$app->response->statusCode = 422;
            return [
                'success' => false,
                'error' => $e->getMessage()
            ];
        }
    }
}

'components' => [
    'postalTracking' => [
        'class' => KalimeroMK\PostalTracking\Services\PostalTrackingService::class,
        'timeout' => 30,
        'retryAttempts' => 3,
        'transformData' => true,
    ],
],


KalimeroMK\PostalTracking\Services\PostalTrackingService;

class SimplePostalTracker
{
    private PostalTrackingService $service;

    public function __construct()
    {
        $this->service = new PostalTrackingService();
    }

    public function track(string $code): array
    {
        try {
            return $this->service->trackShipment($code);
        } catch (\Exception $e) {
            return [
                'success' => false,
                'error' => $e->getMessage(),
                'code' => $code
            ];
        }
    }

    public function isValidCode(string $code): bool
    {
        return preg_match('/^[A-Z]{2}\d{9}[A-Z]{2}$/', strtoupper($code)) === 1;
    }

    public function isDelivered(string $code): bool
    {
        $result = $this->track($code);

        if ($result['success'] && !empty($result['data'])) {
            $lastEvent = end($result['data']);
            return strpos($lastEvent['Забелешка'], 'Испорачана') !== false;
        }

        return false;
    }
}

// Usage
$tracker = new SimplePostalTracker();

if ($tracker->isValidCode('CQ117742716DE')) {
    $result = $tracker->track('CQ117742716DE');

    if ($result['success']) {
        echo "Tracking successful!\n";
        echo "Total events: " . count($result['data']) . "\n";
        echo "Is delivered: " . ($tracker->isDelivered('CQ117742716DE') ? 'Yes' : 'No') . "\n";

        // Show all events
        foreach ($result['data'] as $event) {
            echo "- {$event['Забелешка']} on {$event['Датум']}\n";
        }
    }
}


KalimeroMK\PostalTracking\Services\PostalTrackingService;

// Handle tracking request
if (isset($_GET['tracking_code'])) {
    $service = new PostalTrackingService();
    $trackingCode = $_GET['tracking_code'];

    try {
        $result = $service->trackShipment($trackingCode);

        header('Content-Type: application/json');
        echo json_encode($result, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE);
    } catch (\Exception $e) {
        http_response_code(422);
        echo json_encode([
            'success' => false,
            'error' => $e->getMessage()
        ]);
    }
} else {
    // Show tracking form
    


KalimeroMK\PostalTracking\Services\PostalTrackingService;

if ($argc < 2) {
    echo "Usage: php track.php <tracking_code>\n";
    echo "Example: php track.php CQ117742716DE\n";
    exit(1);
}

$trackingCode = $argv[1];
$service = new PostalTrackingService();

try {
    $result = $service->trackShipment($trackingCode);

    if ($result['success']) {
        echo "✅ Tracking successful!\n";
        echo "📦 Tracking Code: {$result['tracking_code']}\n";
        echo "📊 Total events: " . count($result['data']) . "\n";
        echo "🕒 Last update: {$result['metadata']['last_update']}\n\n";

        echo "📋 Tracking Events:\n";
        foreach ($result['data'] as $index => $event) {
            echo ($index + 1) . ". {$event['Забелешка']}\n";
            echo "   📍 From: {$event['Од']}\n";
            echo "   📍 To: {$event['До']}\n";
            echo "   📅 Date: {$event['Датум']}\n\n";
        }
    }
} catch (\Exception $e) {
    echo "❌ Error: " . $e->getMessage() . "\n";
    exit(1);
}


use KalimeroMK\PostalTracking\Services\PostalTrackingService;

// Create service with custom configuration
$service = new PostalTrackingService(
    timeout: 60,           // 60 seconds timeout
    retryAttempts: 5,      // 5 retry attempts
    transformData: true    // Enable data transformation
);

// Track with additional options
$result = $service->trackShipment('CQ117742716DE', [
    'timeout' => 30,       // Override default timeout
    'retry_attempts' => 2, // Override default retries
    'transform' => false   // Disable transformation for this call
]);


use KalimeroMK\PostalTracking\Services\PostalTrackingService;

$service = new PostalTrackingService();
$trackingCodes = [
    'CQ117742716DE',
    'RA123456789MK',
    'DE987654321US'
];

$results = [];

foreach ($trackingCodes as $code) {
    try {
        $result = $service->trackShipment($code);
        $results[$code] = $result;
    } catch (\Exception $e) {
        $results[$code] = [
            'success' => false,
            'error' => $e->getMessage()
        ];
    }
}

// Process results
foreach ($results as $code => $result) {
    if ($result['success']) {
        echo "✅ {$code}: " . count($result['data']) . " events\n";
    } else {
        echo "❌ {$code}: {$result['error']}\n";
    }
}


use KalimeroMK\PostalTracking\Services\PostalTrackingService;
use KalimeroMK\PostalTracking\Exceptions\PostalTrackingException;
use KalimeroMK\PostalTracking\Exceptions\InvalidTrackingCodeException;
use KalimeroMK\PostalTracking\Exceptions\ApiException;

$service = new PostalTrackingService();

try {
    $result = $service->trackShipment('INVALID_CODE');
} catch (InvalidTrackingCodeException $e) {
    echo "Invalid tracking code: " . $e->getMessage() . "\n";
} catch (ApiException $e) {
    echo "API error: " . $e->getMessage() . "\n";
} catch (PostalTrackingException $e) {
    echo "General error: " . $e->getMessage() . "\n";
}

public function __construct(
    int $timeout = 30,
    int $retryAttempts = 3,
    bool $transformData = true
)

public function trackShipment(string $trackingCode, array $options = []): array

// Getter methods
public function getTimeout(): int
public function getRetryAttempts(): int
public function getTransformData(): bool

// Setter methods (fluent interface)
public function setTimeout(int $timeout): self
public function setRetryAttempts(int $retryAttempts): self
public function setTransformData(bool $transformData): self


use KalimeroMK\PostalTracking\Services\PostalTrackingService;

// Create service with custom configuration
$service = new PostalTrackingService(
    timeout: 60,           // 60 seconds timeout
    retryAttempts: 5,      // 5 retry attempts
    transformData: true    // Enable data transformation
);

// Or configure after instantiation
$service = new PostalTrackingService();
$service->setTimeout(60)
        ->setRetryAttempts(5)
        ->setTransformData(true);


return [
    'timeout' => env('POSTAL_TRACKING_TIMEOUT', 30),
    'retry_attempts' => env('POSTAL_TRACKING_RETRY_ATTEMPTS', 3),
    'transform_data' => env('POSTAL_TRACKING_TRANSFORM_DATA', true),
];

'components' => [
    'postalTracking' => [
        'class' => KalimeroMK\PostalTracking\Services\PostalTrackingService::class,
        'timeout' => 30,
        'retryAttempts' => 3,
        'transformData' => true,
    ],
],


use PHPUnit\Framework\TestCase;
use KalimeroMK\PostalTracking\Services\PostalTrackingService;

class PostalTrackingServiceTest extends TestCase
{
    public function testTrackShipmentWithValidCode()
    {
        $service = new PostalTrackingService();
        $result = $service->trackShipment('CQ117742716DE');

        $this->assertTrue($result['success']);
        $this->assertArrayHasKey('data', $result);
        $this->assertArrayHasKey('metadata', $result);
    }

    public function testTrackShipmentWithInvalidCode()
    {
        $this->expectException(InvalidTrackingCodeException::class);

        $service = new PostalTrackingService();
        $service->trackShipment('INVALID_CODE');
    }
}
bash
php artisan vendor:publish --provider="KalimeroMK\PostalTracking\Laravel\PostalTrackingServiceProvider"
json
{
  "success": true,
  "tracking_code": "CQ117742716DE",
  "data": [
    {
      "Од": "Северна Македонија",
      "До": "1006 - CARINA",
      "Датум": "2025-01-15",
      "Забелешка": "Испорачана"
    }
  ],
  "metadata": {
    "total_events": 1,
    "last_update": "2025-01-15T10:30:00Z",
    "api_url": "https://www.posta.com.mk/api/api.php/shipment?code=CQ117742716DE"
  }
}
bash
php artisan vendor:publish --provider="KalimeroMK\PostalTracking\Laravel\PostalTrackingServiceProvider"