PHP

The trackified/trackified-php Composer package. PHP 8.1+.

Embed
Preview of the card
<a href="https://trackified.net/docs/php"><img src="https://trackified.net/docs/_api/public/orgs/e2a7773e-db9e-41cb-bd59-bd248745cac3/spaces/9d63a5d4-feb0-4803-84a5-dc68639362a6/pages/a394904b-8e55-4719-9bf7-5c5ec8dc6d88/social-card.svg?v=3e7ae33eec8b" alt="PHP" width="600" height="315"></a>

trackified/trackified-php works in Laravel, Symfony, WooCommerce or plain PHP. It uses any PSR-18 HTTP client you already have (Guzzle, Symfony HttpClient and others), found through php-http/discovery, and falls back to a built-in curl client when there isn't one. Source: trackified/trackified-php.

Install

composer require trackified/trackified-php

Until it reaches Packagist

If Composer can't find the package yet, add the GitHub repository first:

composer config repositories.trackified vcs https://github.com/trackified/trackified-php
composer require trackified/trackified-php:^0.2

Configure

use Trackified\TrackifiedClient;

$client = new TrackifiedClient(); // reads TRACKIFIED_API_KEY and TRACKIFIED_BASE_URL

Pass options to override the defaults:

$client = new TrackifiedClient(
    apiKey: getenv('TRACKIFIED_API_KEY') ?: null,
    baseUrl: 'https://api.trackified.net',
    timeout: 30.0,  // seconds, for the built-in curl client
    maxRetries: 2,
);

The base URL works with or without /v1 at the end.

Check that the API is up. No key is needed for this call:

echo $client->health()['status'], PHP_EOL; // "ok"; a 503 throws APIError

Responses are typed, read-only models with camelCase properties ($tracking->trackingNumber). Each model keeps the full JSON object in $model->raw, for fields the SDK doesn't model yet.

Trackings

Create

$tracking = $client->trackings->create([
    'tracking_number' => '1Z999AA10123456784',
    'carrier' => 'ups',                    // optional: our id or a name like 'UPS Ground'; detected when left out
    'custom_id' => 'order_1042',           // optional: your own reference
    'customer_email' => 'ada@example.com', // optional
]);

carrier takes our carrier id, a carrier or service name ('USPS Priority Mail'), or another provider's slug ('dhl_express'). The tracking stores our id. Leave carrier out and we detect it from the number. If we can't tell, the call throws ValidationError with errorCode set to carrier_not_detected.

Get

$tracking = $client->trackings->get('trk_...');
echo $tracking->status->value, ' ', $tracking->estimatedDelivery, PHP_EOL;
foreach ($tracking->events as $event) { // newest first
    echo $event->occurredAt, ' ', $event->status->value, ' ', $event->description, ' ', $event->location, PHP_EOL;
}

status is a Trackified\Model\TrackingStatus enum.

List and auto-paginate

use Trackified\Model\TrackingStatus;

// One page
$page = $client->trackings->list(['status' => TrackingStatus::InTransit, 'limit' => 50]);
echo count($page->data), ' of ', $page->total, PHP_EOL;

// Every matching tracking, fetching pages as you iterate
foreach ($client->trackings->all(['status' => TrackingStatus::Delivered]) as $t) {
    echo $t->trackingNumber, ' ', $t->deliveredAt, PHP_EOL;
}

Filters: status (an enum or a string), carrier, custom_id, tracking_number, plus limit and offset.

Update, stop and retrack

// Change the carrier, custom_id or customer_email. Keys you leave out stay as they are.
$client->trackings->update('trk_...', ['carrier' => 'usps']);

// Ask for the carrier to be checked again within a minute.
$result = $client->trackings->retrack('trk_...');
var_dump($result['queued']);

// Stop tracking. The tracking is no longer checked or returned.
$client->trackings->delete('trk_...');

Bulk create

$rows = $client->trackings->bulkCreate([
    ['tracking_number' => '1Z999AA10123456784', 'custom_id' => 'order_1042'],
    ['tracking_number' => '9434650110837017316201', 'carrier' => 'usps', 'custom_id' => 'order_1043'],
]);
foreach ($rows as $row) {
    echo $row->ok ? $row->tracking?->id : $row->error, PHP_EOL;
}

Each row succeeds or fails on its own. Your plan sets the most rows per request. See Rate limits and plans.

Carriers

$candidates = $client->carriers->detect('1Z999AA10123456784'); // best first
if ($candidates !== []) {
    echo $candidates[0]->carrier, ' ', $candidates[0]->confidence, PHP_EOL;
}

// Map a free-text name or another provider's slug to our id. null if we don't serve it.
$match = $client->carriers->resolve('FedEx SmartPost');
if ($match !== null) {
    echo $match->carrier, ' ', $match->confidence, ' ', $match->matched, PHP_EOL;
}

$catalog = $client->carriers->catalog(['q' => 'dhl']); // the full carrier catalog, as an array

Webhooks

Create an endpoint

use Trackified\Model\WebhookEventType;

$webhook = $client->webhooks->create(
    'https://example.com/webhooks/trackified',
    [WebhookEventType::StatusChanged, WebhookEventType::Delivered],
);
// Store $webhook->secret now. It's only returned here.

Pass null (or leave the argument out) and you get tracking.updated and tracking.delivered.

Update, pause and rotate

// Change the URL or events, or pause it. The secret stays the same.
$client->webhooks->update($webhook->id, eventTypes: [WebhookEventType::StatusChanged]);
$client->webhooks->update($webhook->id, enabled: false);

// New secret, shown once. The old one keeps verifying for 24 hours by default.
$rotated = $client->webhooks->rotateSecret($webhook->id, expiresInHours: 24);
echo $rotated->secret, ' ', $rotated->previousSecretExpiresAt, PHP_EOL;

During the window, pass both secrets when you verify (below).

Verify in Laravel

$request->getContent() is the raw body. Routes in routes/api.php skip CSRF checks. Add the secret to config/services.php as 'trackified' => ['webhook_secret' => env('TRACKIFIED_WEBHOOK_SECRET')].

routes/api.php
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Route;
use Trackified\Exception\SignatureVerificationError;
use Trackified\WebhookSignature;

Route::post('/webhooks/trackified', function (Request $request) {
    try {
        $event = WebhookSignature::constructEvent(
            $request->getContent(),
            (string) $request->header('x-tracking-signature', ''),
            (string) config('services.trackified.webhook_secret'),
        );
    } catch (SignatureVerificationError) {
        return response('bad signature', 400);
    }

    if ($event->isStatusChanged()) {
        Log::info($event->previousStatus()?->value.' -> '.$event->currentStatus()?->value);
    }
    Log::info($event->type.' '.$event->tracking()->trackingNumber); // the tracking, for any event type

    return response('', 200);
});

Without a framework, read the body with file_get_contents('php://input') and the header from $_SERVER['HTTP_X_TRACKING_SIGNATURE'].

Events and their data

$event->data is the raw array. $event->tracking() (or WebhookSignature::trackingOf($event)) returns the Tracking for any type; for tracking.status_changed, previousStatus() and currentStatus() give the change.

Failed carrier checks

A tracking.exception sent because we couldn't reach the carrier carries tracking_id and error, not a tracking. Read $event->data['tracking_id'] for it rather than $event->tracking(). See Webhook events.

Why verification failed

constructEvent throws SignatureVerificationError with a reason, a Trackified\SignatureFailureReason enum: Missing, Malformed, Timestamp or Mismatch. verifyDetailed returns it without throwing; verify returns a bool:

// $payload: the raw request body; $header: the x-tracking-signature value
$result = WebhookSignature::verifyDetailed($payload, $header, $secret);
if (!$result->valid) {
    error_log('webhook rejected: '.$result->reason?->value);
}

All three take one secret or an array of secrets (any may match), and a tolerance in seconds as the fourth argument (default 300). Pass both secrets while a rotation is in progress:

$event = WebhookSignature::constructEvent($payload, $header, [
    (string) getenv('TRACKIFIED_WEBHOOK_SECRET'),
    (string) getenv('TRACKIFIED_WEBHOOK_SECRET_OLD'),
]);

They're also on $client->webhooks.

Errors

use Trackified\Exception\ConnectionError;
use Trackified\Exception\NotFoundError;
use Trackified\Exception\QuotaExceededError;
use Trackified\Exception\RateLimitError;
use Trackified\Exception\TrackifiedError;
use Trackified\Exception\ValidationError;

try {
    $client->trackings->create(['tracking_number' => 'ABC123'], 'order_1042');
} catch (ValidationError $e) {
    if ($e->errorCode === 'carrier_not_detected') {
        // ask the user for the carrier
    }
} catch (QuotaExceededError $e) {
    // 402: this month's trackings are used up
} catch (ConnectionError $e) {
    if ($e->errorCode === ConnectionError::TIMEOUT) {
        // The outcome is unknown. Retry later with the same idempotency key.
    }
} catch (NotFoundError $e) {
    // 404
} catch (RateLimitError $e) {
    echo 'retry in ', $e->retryAfter, 's', PHP_EOL;
} catch (TrackifiedError $e) {
    echo $e->status, ' ', $e->errorCode, ': ', $e->getMessage(), ' (request ', $e->requestId, ')', PHP_EOL;
}

The classes, all in Trackified\Exception, are AuthenticationError (401, or no API key), PermissionError (403), NotFoundError (404), ValidationError (400, 422), QuotaExceededError (402), ConflictError (409, including idempotency_in_progress), RateLimitError (429), APIError (5xx), ConnectionError (no response; errorCode is timeout or connection) and SignatureVerificationError.

A timeout means the outcome is unknown: the request may have reached us. The library's own retries reuse the idempotency key, so a create is never doubled. If you retry yourself later, pass the same idempotency key.

Options

Argument

Default

apiKey

TRACKIFIED_API_KEY

baseUrl

TRACKIFIED_BASE_URL, else https://api.trackified.net

timeout

30.0

Seconds. Applies to the built-in curl client only.

maxRetries

2

Retries for network errors, 408, 429 and 5xx.

httpClient

discovered

A PSR-18 client. Set its timeout on the client itself.

requestFactory, streamFactory

discovered

PSR-17 factories, if discovery can't find them.

onRequest

none

Called before each attempt.

onResponse

none

Called after each attempt.

Request hooks

$client = new TrackifiedClient(
    onRequest: function (array $info): void {
        error_log("-> {$info['method']} {$info['url']} attempt {$info['attempt']} {$info['idempotencyKey']}");
    },
    onResponse: function (array $info): void {
        $outcome = $info['status'] ?? $info['error']?->errorCode;
        error_log("<- {$info['method']} {$info['url']} {$outcome} {$info['requestId']} {$info['durationMs']}ms");
    },
);

Each hook gets an array and runs once per attempt, so a retried request calls it more than once. attempt is 1 for the first try. status is null when no response arrived; error is the typed error when the status is 400 or more or the connection failed. idempotentReplayed says whether a create was a replay. A hook that throws is ignored.

trackings->create() and trackings->bulkCreate() take an idempotency key as the second argument to replace the generated one. See Pagination, retries and idempotency.

Updated