API Documentation
One API for every courier we support, with the courier's own proof of delivery where it gives one
What's new
Introduction
The TrackCourier.io API provides a unified interface to track shipments across major Indian and international couriers. With one integration, you can track packages from Speed Post, Blue Dart, Delhivery, DTDC, Shree Tirupati and many more.
A courier tracking API with proof of delivery. Once your account has paid for shipments, you get the courier's own proof-of-delivery file for delivered shipments of eligible couriers, when the courier gives one.
Base URL: https://api.trackcourier.io/v1
All API requests are made over HTTPS. Requests made over plain HTTP will fail.
Authentication
All API requests require authentication via the X-API-Key header.
X-API-Key: your_api_key_here
Get your API key from your dashboard after signing up.
Pricing
You pay once for each shipment: one parcel, followed until it is delivered. Webhooks and unlimited re-checks are included. A new account starts with 25 free shipments.
Monthly plans
A plan's shipments are used first. They reset when your plan renews each month; unused ones don't carry over.
| Plan | Shipments a month | Price |
|---|---|---|
| Starter | 150 | ₹499 a month |
| Growth | 700, including 100 free | ₹1,999 a month |
| Business | 2,000, including 500 free | ₹4,999 a month |
Top-ups
They last 2 years from the day you buy them.
| Shipments | Price |
|---|---|
| 100 | ₹400 one time |
| 1,000, including 50 free | ₹3,800 one time |
| 2,500, including 250 free | ₹9,000 one time |
Start a plan or buy a top-up on the pricing page.
Questions before you pay
What counts as a shipment?
One tracking number, from the first time you look it up until it is delivered. Every re-check and every webhook for it is included. A number the courier has no record of is not counted.
Can I try it before I pay?
Yes: a new account starts with 25 free shipments, and signing up needs no card. There is no separate sandbox, so you test with real tracking numbers. A test webhook lets you check your server with a sample delivery.
Do webhooks cost extra?
No. Every account gets webhooks, with no limit on how many shipments you follow.
Which couriers can I track?
Every courier we support, on every plan: Speed Post, Blue Dart, Delhivery, DTDC, Professional Courier, Shree Tirupati Courier and many more. Need one that is not on the list? Email api@trackcourier.io with a few of its recent tracking numbers. See the full list.
How fresh is an answer?
We re-check a moving shipment with the courier about every hour, and every 30 minutes once it is out for delivery. Each lookup and each webhook gives you the newest copy we have. We do not guarantee a re-check interval.
What happens when a courier's website is down?
If we have a saved copy of the shipment, you get it. If not, the answer has no tracking history yet, and you can try again later. A lookup that gets no tracking history never uses up a shipment. We keep re-checking the shipments you have looked up for up to 30 days, so their webhooks carry on once the courier answers again. A shipment the courier has never answered for is re-checked for 3 days.
How do I reach a person?
Email api@trackcourier.io. A person reads every email. For a lookup that looks wrong, include the courier and the tracking number.
🚀 Get Started in 3 Steps
Start tracking shipments in under 5 minutes. No complex setup required.
Get Your Free API Key
Sign up with Google and get 25 free shipments instantly. No credit card required.
Get API Key →Make Your First Tracking Request
Every example reads your API key from TRACKCOURIER_API_KEY, so set that to your key, from the API Keys page of your dashboard. The cURL example does it for you: replace your_api_key in its export line.
# Set your API key
export TRACKCOURIER_API_KEY="your_api_key"
# Track a shipment
curl "https://api.trackcourier.io/v1/track?courier=dtdc&tracking_number=B1001577139" \
-H "X-API-Key: $TRACKCOURIER_API_KEY"
import os
import requests
response = requests.get(
"https://api.trackcourier.io/v1/track",
params={"courier": "dtdc", "tracking_number": "B1001577139"},
headers={"X-API-Key": os.environ["TRACKCOURIER_API_KEY"]}
)
data = response.json()
print(data["data"]["ShipmentState"]) # "intransit", "delivered", etc.
async function main() {
const response = await fetch(
"https://api.trackcourier.io/v1/track?courier=dtdc&tracking_number=B1001577139",
{ headers: { "X-API-Key": process.env.TRACKCOURIER_API_KEY } }
);
const data = await response.json();
console.log(data.data.ShipmentState); // "intransit", "delivered", etc.
}
main();
<?php
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "https://api.trackcourier.io/v1/track?courier=dtdc&tracking_number=B1001577139");
curl_setopt($ch, CURLOPT_HTTPHEADER, ["X-API-Key: " . getenv("TRACKCOURIER_API_KEY")]);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($ch);
$data = json_decode($response, true);
echo $data["data"]["ShipmentState"]; // "intransit", "delivered", etc.
A complete script that handles errors, and a webhook receiver, are under PHP.
Handle the Response
You'll get back a JSON response with the shipment status and tracking history:
{
"success": true,
"data": {
"ShipmentState": "delivered", // Normalised state
"MostRecentStatus": "Delivered", // Our short label, not the courier's wording
"Checkpoints": [...] // Full history; sort by Date+Time yourself
},
"usage": {
"used": 1,
"quota": 700,
"plan": "growth",
"percent": 0.1
}
}
That's it! You're now tracking shipments. Check the API Reference for more details.
Check everything in one command, before importing anything. This runs our Postman collection, with its own checks, from your machine. It needs Node.js. The tracking requests use recently delivered shipments where we have one for that courier; the webhook requests run only if you also pass --env-var "webhook_url=https://your-receiver/path", and are skipped otherwise:
npx newman run https://api.trackcourier.io/postman --env-var "api_key=your_api_key"
Common Use Cases
Show customers their order's tracking status on your website
Push delivery notifications to your app users
Trigger workflows based on delivery status changes
Track Shipment
Track a shipment by courier and tracking number. Returns current status and checkpoint history.
Query Parameters
| Parameter | Type | Description |
|---|---|---|
| courier required | string | The courier's slug or its name, as GET /v1/couriers lists them (e.g., "bluedart" or "Blue Dart"). Letter case and spaces do not matter. |
| tracking_number required | string | AWB or tracking number. For India Post, Speed Post, Registered Post and India Post International: 13 characters, 2 letters, 9 digits, then 2 letters, for example EE123456789IN. Spaces and small letters are fine; we remove the spaces and use capitals. |
Response
{
"success": true,
"data": {
"MostRecentStatus": "Delivered",
"ShipmentState": "delivered",
"Checkpoints": [
{
"Activity": "Delivered",
"CheckpointState": "delivered",
"CourierName": "DTDC",
"Date": "18-Sep-2026",
"Time": "17:08",
"Location": "Delhi"
},
{
"Activity": "Out for Delivery - Shipment is out for Delivery 2026-09-18 14:09:12",
"CheckpointState": "outfordelivery",
"CourierName": "DTDC",
"Date": "18-Sep-2026",
"Time": "14:09",
"Location": "Delhi"
},
{
"Activity": "Received at DELHI Delivery Centre",
"CheckpointState": "intransit",
"CourierName": "DTDC",
"Date": "18-Sep-2026",
"Time": "09:31",
"Location": "Delhi"
},
{
"Activity": "On The Way - On its way between JAIPUR and DELHI",
"CheckpointState": "intransit",
"CourierName": "DTDC",
"Date": "17-Sep-2026",
"Time": "22:15",
"Location": "Jaipur to Delhi"
}
],
"CourierHasNoRecordOfShipment": false,
"isEmptyTable": false,
"Result": "success",
"AdditionalInfo": "",
"FetchTime": "4.9084",
"PODImageUrl": "",
"ExecutionTime": ""
},
"usage": {
"used": 45,
"quota": 700,
"plan": "growth",
"percent": 6.4
}
}
The usage block. Every successful answer ends with a usage block.
used: the shipments you have used since your newest top-up, or since your monthly plan's current month began.quota:usedplus the shipments you have left, soquotaminususedis what you have left.plan: your monthly plan, orfreeif you have none.percent: the share ofquotayou have used. It reads 100.0 only when you have none left.
These numbers can be a few minutes behind your latest lookup. They have counted shipments since 10 November 2026. An account that does not count shipments yet sees this month's lookups and its monthly number instead.
PODImageUrl: when proof_of_delivery holds a file, the link to its first file, the same as that entry's file_url. Like it, the link works for up to 24 hours. Otherwise PODImageUrl is as the courier's answer gives it, often empty. The proof-of-delivery file is in proof_of_delivery, once your account has paid for shipments.
Status Values
ShipmentState and each checkpoint's CheckpointState take these values, written exactly as shown.
| Status | Description |
|---|---|
inforeceived | Booked: the courier has the shipment's details |
pending | Not moving yet, the courier has no events to show yet, or we could not get an answer from the courier this time |
intransit | Moving through the courier's network |
outfordelivery | With the delivery agent |
attemptfail | A delivery attempt did not succeed, or the courier says it was not delivered |
delivered | Delivered |
exception | A problem the courier reports, or the courier has no record of this number |
expired | The courier says the tracking has expired |
Response Codes
| 200 | Success - tracking data returned |
| 401 | Invalid or missing API key |
| 402 | No shipments left, or the account needs attention. Older free accounts also get it when this month's free lookups are used up. Check error.code. |
| 404 | Courier not found |
Proof of Delivery
Eligible couriers: Blue Dart, Professional Courier and Shree Maruti.
Once your account has paid for shipments, every GET /v1/track answer carries proof_of_delivery, a list beside data and usage. Once a shipment is delivered, the list holds the courier's own proof-of-delivery file, for the eligible couriers. The file can show a signature, a stamp or a photo of the delivery. It can also show other shipments on the same delivery sheet, with their recipients' names, phone numbers and signatures. We capture it when a delivered shipment is looked up, so it is often already in that answer; if the courier has not published it yet, it appears on a later lookup. If the courier gives no file for a shipment, the list stays empty. We keep the file for 2 years from when we capture it, so it is still in your answer after the courier stops showing it; a file we captured before 1 December 2026 is kept 90 days. Until we capture it, and for every other courier, the list is empty. Other accounts' answers have no proof_of_delivery key.
Each entry
Five fields, all strings.
| Field | Description |
|---|---|
file_url |
A link to the file. It works for up to 24 hours, and every lookup gives you a fresh one. Anyone you share it with can open it until then. |
file_url_expires_at |
When the link stops working (UTC, ISO 8601) |
captured_at |
When we captured the file from the courier (UTC, ISO 8601) |
file_type |
image/jpeg, image/png, image/webp or application/pdf |
fingerprint_sha256 |
The file's SHA-256 fingerprint, in hex |
proof_of_delivery is null when we could not check for a file this time. The rest of the answer is unchanged, and your next lookup checks again.
"proof_of_delivery": [
{
"file_url": "https://api.trackcourier.io/v1/delivery-images/gAAAAAB...",
"file_url_expires_at": "2026-10-20T09:30:00Z",
"captured_at": "2026-10-19T09:30:00Z",
"file_type": "image/png",
"fingerprint_sha256": "0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef"
}
]
Check a file
To check a file you downloaded, open Check a proof-of-delivery file. Your browser works out the file's fingerprint, and the file never leaves your computer. A match means the file is byte for byte the one we captured from the courier; it does not say whether the courier's record is right.
Try it
Your API key is on the API Keys page of your dashboard. Set it, then run this request. Its courier provides no proof-of-delivery file, so its list is empty; a delivered shipment of Blue Dart, Professional Courier or Shree Maruti carries the file once we have captured it.
export TRACKCOURIER_API_KEY="your_api_key"
curl "https://api.trackcourier.io/v1/track?courier=dtdc&tracking_number=B1001577139" \
-H "X-API-Key: $TRACKCOURIER_API_KEY"
List Couriers
Get every courier you can track, with its name, which courier also takes, and the slug to use in your requests. Calling it is free.
Response
{
"success": true,
"data": {
"couriers": [
{"slug": "bluedart", "name": "Blue Dart"},
{"slug": "delhivery", "name": "Delhivery"},
{"slug": "dtdc", "name": "DTDC"},
... // 39 more
],
"count": 42
}
}
Get Courier Details
Get details for a specific courier by its slug or its name. Calling it is free.
Response
{
"success": true,
"data": {
"slug": "delhivery",
"name": "Delhivery"
}
}
Webhooks
Webhooks push shipment events to your server. We re-check a moving shipment with the courier about every hour, and every 30 minutes once it is out for delivery. You do not need to poll for us to keep following a shipment. Events are not real-time: an event reaches you only after one of our re-checks sees the change. For a moving shipment that is usually within about an hour of the courier's own tracking showing it; it can take longer, for example when the courier does not answer a re-check. We do not guarantee a re-check interval.
Set up a webhook in your dashboard. Sign in, open Webhooks in your dashboard, choose + Create webhook, enter your https:// URL, and tick every event you act on. The same page has Rotate signing secret, which issues a new signing secret, shown once; keep accepting the old one as well for at least 15 minutes after you rotate.
Your signing secret signs every webhook on your account, test and live. The call that generates it gives it to you once, if that call succeeds: your account's first create, or a rotation made before any create. Save it then, and make that first create on its own. A later create returns a notice beginning with < in its place; do not store that, as your secret is unchanged.
Test webhooks need no particular plan: create one through the API with "mode": "test". The webhook requests in our Postman collection create one and send a sample delivery to it.
How It Works
1. Create a webhook in your dashboard
2. Look up each shipment with GET /v1/track: a lookup is what tells us to follow it
3. Receive a POST request when we see its status change or new checkpoints
Payload versions
Each webhook has a payload_version, the shape of the body we send it, and every delivery names it in the X-Webhook-Payload-Version header. There are two: version 1 is the payload below, and version 2 is described under Payload version 2. Set payload_version when you create or update a webhook. A webhook created without it gets version 2, unless your account already has a webhook on version 1, live or test, active or not: then it gets version 1, so a script written for version 1 keeps receiving version 1. A version stays available until we announce its end at least 6 months ahead, and we never move your webhook to another version: only you change it. Each new version is announced in the Changelog.
To move a webhook to version 2 safely, point a test webhook, or a second webhook, at version 2, compare what it receives with what your current webhook receives, and then change your current webhook's payload_version.
Webhook Event Types
We send one of these events when we re-check a shipment and find its status changed to one with an event below, or more checkpoints than before.
| Event | Description |
|---|---|
tracking.updated |
More checkpoints than before, with no change to a state that has its own event |
tracking.in_transit |
The shipment's status changed to in_transit |
tracking.out_for_delivery |
The shipment's status changed to out_for_delivery |
tracking.delivered |
The shipment's status changed to delivered. Terminal: we stop following it |
tracking.exception |
The shipment's status changed to exception, returned or cancelled |
A change to a state that has its own event replaces tracking.updated for that update, so one change never produces two events for one webhook. A webhook receives only the events it lists, so list every event you act on.
tracking.exception covers both a problem the shipment can recover from and a terminal non-delivery: read data.status to tell them apart (returned and cancelled are terminal, exception is not).
Webhook Payload
All webhook events are sent as POST requests with a JSON body:
Note: the webhook payload is snake_case throughout,
including inside each checkpoint. It is not the same shape as the
GET /v1/track response above, whose data object uses
PascalCase names such as MostRecentStatus. If you use both surfaces, write two mappings: a model
generated from one decodes nothing from the other.
{
"event": "tracking.delivered",
"enqueued_at": "2026-09-18T09:14:22Z",
"data": {
"tracking_number": "7X118822611",
"courier": "dtdc",
"status": "delivered",
"most_recent_status": "Delivered",
"origin_city": null,
"destination_city": null,
"delivered_date": null,
"checkpoints": [
{
"activity": "Delivered",
"checkpoint_state": "delivered",
"courier_name": "DTDC",
"date": "18-Sep-2026",
"time": "17:08",
"location": "Delhi"
},
{
"activity": "Out for Delivery - Shipment is out for Delivery 2026-09-18 14:09:12",
"checkpoint_state": "outfordelivery",
"courier_name": "DTDC",
"date": "18-Sep-2026",
"time": "14:09",
"location": "Delhi"
},
{
"activity": "Received at DELHI Delivery Centre",
"checkpoint_state": "intransit",
"courier_name": "DTDC",
"date": "18-Sep-2026",
"time": "09:31",
"location": "Delhi"
},
{
"activity": "On The Way - On its way between JAIPUR and DELHI",
"checkpoint_state": "intransit",
"courier_name": "DTDC",
"date": "17-Sep-2026",
"time": "22:15",
"location": "Jaipur to Delhi"
}
],
"enqueued_at": "2026-09-18T09:14:22Z"
}
}
Payload version 2
A webhook on version 2 receives the same headers, envelope and events as one on version 1. Only data differs: courier is the courier's slug in the API, such as bluedart; status and every checkpoint_state take one vocabulary of eleven states, so you can switch on them exhaustively; every checkpoint has the same six fields, each a string, "" when the courier gave nothing; only the fields below are ever sent; and enqueued_at is in the envelope only. A courier reply that holds no tracking gives status unknown, most_recent_status null and checkpoints [].
Field of data | Meaning |
|---|---|
tracking_number | The tracking number, as you looked it up. |
courier | The courier's slug in our API, such as dtdc or bluedart: the usual spelling of the slug the shipment was looked up with (dp-world arrives as dpworld). A test fire's begins synthetic-test- (§3.1). |
status | The shipment's state: always one of the eleven states below. |
most_recent_status | Our own short label for the newest event, such as Delivered; null when we have none. |
checkpoints | The courier's events, in the order the courier gives them (§5.3). [] when the courier's reply held none; null only when we could not read our record of the shipment at delivery time. |
origin_city | Reserved: always null. |
destination_city | Reserved: always null. |
delivered_date | Reserved: always null. Read the date of the checkpoint whose checkpoint_state is delivered. |
| Field of each checkpoint | Meaning |
|---|---|
date | The day of the event as the courier publishes it (for Indian couriers usually like 18-Sep-2026), with no zone (§3.3); "" when the courier gave none. |
time | The time of day as the courier publishes it (usually like 17:08), with no zone (§3.3); "" when none. |
location | Where the event happened, in the courier's words; "" when none. |
activity | The courier's own words for the event; "" when none. |
courier_name | The courier named on the event; "" when none. |
checkpoint_state | This event's state: one of the eleven states below, unknown when the courier's wording is none of them. |
| State | Meaning |
|---|---|
pending | No movement yet. |
info_received | The courier has the booking, not yet the parcel. |
in_transit | Moving. |
out_for_delivery | With the delivery executive. |
attempt_failed | Delivery was attempted and failed. |
delivered | Reached the addressee. Final. |
exception | A problem the shipment can recover from. |
expired | The courier stopped reporting. |
returned | Sent back to its origin. Final. |
cancelled | Withdrawn. Final. |
unknown | No state we can name: the courier's reply gave none, or used words that are none of these. |
{
"event": "tracking.delivered",
"enqueued_at": "2026-09-18T11:40:05Z",
"data": {
"tracking_number": "7X118822611",
"courier": "dtdc",
"status": "delivered",
"most_recent_status": "Delivered",
"checkpoints": [
{
"date": "18-Sep-2026",
"time": "17:08",
"location": "Delhi",
"activity": "Delivered",
"courier_name": "DTDC",
"checkpoint_state": "delivered"
},
{
"date": "18-Sep-2026",
"time": "14:09",
"location": "Delhi",
"activity": "Out for Delivery - Shipment is out for Delivery 2026-09-18 14:09:12",
"courier_name": "DTDC",
"checkpoint_state": "out_for_delivery"
},
{
"date": "18-Sep-2026",
"time": "09:31",
"location": "Delhi",
"activity": "Received at DELHI Delivery Centre",
"courier_name": "DTDC",
"checkpoint_state": "in_transit"
},
{
"date": "17-Sep-2026",
"time": "22:15",
"location": "Jaipur to Delhi",
"activity": "On The Way - On its way between JAIPUR and DELHI",
"courier_name": "DTDC",
"checkpoint_state": "in_transit"
}
],
"origin_city": null,
"destination_city": null,
"delivered_date": null
}
}
Webhook Security
Verify that webhook requests are from TrackCourier.io by checking the signature.
Signature Verification
Every webhook includes an X-Trackcourier-Signature header containing an HMAC-SHA256 signature of the request body.
Four further headers accompany every delivery. None of the headers is signed: the signature covers the body alone, so take anything you act on from the verified body.
X-Webhook-Event: the event type, e.g.tracking.delivered. The verified body carries the same name asevent.X-Webhook-Delivery: an attempt identifier, not an event identifier. It is<webhook_id>-<attempt>, so it changes on every retry of the same event, and the first attempt of every event sent to one webhook carries the same value. Do not deduplicate on it. See Handle duplicates below.X-Webhook-Mode:testfor a sample delivery to a test webhook,liveotherwise. To tell a test delivery apart once its signature verifies, readdata.courierin the body: a test delivery's beginssynthetic-test-.X-Webhook-Payload-Version: the payload version of this body,1or2. You choose it per webhook withpayload_version.
X-Trackcourier-Signature: sha256=a1b2c3d4e5f6...
Verification Example (Python)
import hashlib
import hmac
import json
from fastapi import FastAPI, Request
from fastapi.responses import JSONResponse
app = FastAPI()
# Your signing secret. We show it only once: save it when we do.
WEBHOOK_SECRET = "your_signing_secret"
def verify(raw_body: bytes, header: str, secret: str) -> bool:
if not header.isascii(): # compare_digest raises on non-ASCII text
return False
expected = "sha256=" + hmac.new(
secret.encode(), raw_body, hashlib.sha256
).hexdigest()
return hmac.compare_digest(expected, header)
@app.post("/webhook")
async def handle_webhook(request: Request):
raw_body = await request.body() # the raw bytes, never a re-serialised object
signature = request.headers.get("X-Trackcourier-Signature", "")
if not verify(raw_body, signature, WEBHOOK_SECRET):
return JSONResponse({"error": "Invalid signature"}, status_code=401)
event = json.loads(raw_body)
# Replace your stored checkpoints for this consignment with
# event["data"]["checkpoints"], unless it is null (see Handle duplicates).
return {"received": True}
In PHP: a receiver for PHP 7.2 and later.
Retry Policy
Any 2xx response counts as delivered. We follow redirects, so do not answer with one: after a 301, 302 or 303 the redirected request is sent as a GET without the body, and we record a success for a delivery your endpoint never received; after a 307 or 308 we send the signed body on to wherever the redirect points. Return 2xx at the URL you configured. Anything else is retried on this schedule:
- Retry 1: After 1 minute
- Retry 2: After 5 minutes
- Retry 3: After 30 minutes
- Retry 4: After 2 hours
- Retry 5: After 24 hours
That is up to six attempts in all: the first, then these five retries. After the sixth fails, the delivery is abandoned and is not sent again. We also check your URL before every attempt: a delivery to a host that does not resolve, or that resolves to a private, loopback, link-local or unspecified address, is dropped without a retry. We never switch a webhook off because its deliveries fail: once your endpoint answers 2xx again, deliveries resume by themselves. Your dashboard shows each live webhook's count of failed deliveries in a row and its recent deliveries.
Best Practices
- Respond quickly: Return 200 within 5 seconds. Process async if needed.
- Handle duplicates: deliveries are at-least-once, so the same event can reach you more than once. Make your handler idempotent: a payload whose
checkpointsis an array carries the shipment's full known history, so replace your stored checkpoints for that consignment with the payload's rather than appending, and keep the ones you hold whencheckpointsisnull. Applying the same payload twice then changes nothing. To also skip obvious retries,event+data.courier+data.tracking_number+enqueued_atis fixed for the life of an event, but it is not unique:enqueued_atis to the second, so two differenttracking.updatedevents for one consignment queued in the same second share it. Use it to skip repeated work, never to discard an event. Do not key ondata.statusor the checkpoint list: each retry rebuildsdatafrom our freshest record. - Verify signatures: Always validate the HMAC signature.
- Use HTTPS: Only configure HTTPS webhook URLs.
PHP
Two files to copy, for PHP 7.2 or later with the curl extension. No framework and no Composer. They are also on GitHub, with the tests that run them on PHP 7.2 and PHP 8.5.
Track a shipment
Save this as trackcourier_track.php, set TRACKCOURIER_API_KEY to your key from the API Keys page, and run it:
export TRACKCOURIER_API_KEY="your_api_key"
php trackcourier_track.php
<?php
// Track one shipment with the trackcourier.io API.
// For PHP 7.2 and later, with the curl extension.
// Documentation: https://api.trackcourier.io/docs#php
// Set TRACKCOURIER_API_KEY to your API key, from
// https://api.trackcourier.io/dashboard/keys
$courier = 'dtdc';
$tracking_number = 'B1001577139';
$api_key = getenv('TRACKCOURIER_API_KEY');
if ($api_key === false || $api_key === '') {
echo "Set TRACKCOURIER_API_KEY to your API key, from\n"
. "https://api.trackcourier.io/dashboard/keys\n";
exit(1);
}
$url = 'https://api.trackcourier.io/v1/track?' . http_build_query(array(
'courier' => $courier,
'tracking_number' => $tracking_number,
));
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('X-API-Key: ' . $api_key));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_TIMEOUT, 60);
$body = curl_exec($ch);
if ($body === false) {
echo 'Could not reach the API: ' . curl_error($ch) . "\n";
exit(1);
}
$http_status = curl_getinfo($ch, CURLINFO_HTTP_CODE);
$answer = json_decode($body, true);
if ($http_status != 200 || !isset($answer['data'])) {
// Branch on error.code, never on the HTTP status.
// Every code: https://api.trackcourier.io/docs#errors
$code = isset($answer['error']['code'])
? $answer['error']['code'] : 'HTTP ' . $http_status;
$message = isset($answer['error']['message'])
? $answer['error']['message'] : $body;
echo $code . ': ' . $message . "\n";
exit(1);
}
$shipment = $answer['data'];
echo $shipment['ShipmentState'] . ': ' . $shipment['MostRecentStatus'] . "\n";
foreach ((array) $shipment['Checkpoints'] as $checkpoint) {
echo $checkpoint['Date'] . ' ' . $checkpoint['Time'] . ' '
. $checkpoint['Location'] . ' ' . $checkpoint['Activity'] . "\n";
}
It prints the shipment's state and each checkpoint, or the error's code and message (every code is under Error Handling). If you would rather not receive webhooks, run it on a schedule, for example from cron.
Receive webhooks
Save this as trackcourier_webhook.php on your server and paste your signing secret into it. Then write your own code in save_tracking_update(), at the bottom. Until you do, the file answers every live update with 500, so it is not counted as delivered; we try each update again, up to six attempts in all over about 27 hours, and after the sixth it is not sent again. Add the file's https:// address as a webhook on your dashboard's Webhooks page.
| It receives | It answers |
|---|---|
anything but a POST | 405 |
| an update before you paste your secret, or one whose signature does not match | 401, and we try again |
| a signed body without an event, a courier and a tracking number | 400 |
| a test event | 200, without calling your code |
| a live update | 200 once save_tracking_update() has run; 500 if it throws, and we try again |
<?php
// trackcourier.io webhook receiver, for PHP 7.2 and later.
// No framework and no Composer: copy this one file to your server.
// Documentation: https://api.trackcourier.io/docs#php
//
// It answers:
// 405 to anything but a POST
// 401 until you paste your secret below, and when a signature does not match
// 400 to a signed body without an event, a courier and a tracking number
// 200 to a test event, without calling your code
// 200 to a live update once save_tracking_update() has run
// 500 when save_tracking_update() throws
// After a 401 or a 500 we try the update again, up to six attempts in all
// over about 27 hours; then it is not sent again. After a 200 we stop.
// Your signing secret, exactly as your dashboard showed it.
const TRACKCOURIER_WEBHOOK_SECRET = 'paste-your-signing-secret-here';
// After you rotate your secret, put the old one here for at least 15 minutes,
// so updates signed with it are still accepted. Otherwise leave it empty.
const TRACKCOURIER_WEBHOOK_PREVIOUS_SECRET = '';
function respond($http_status, $message)
{
http_response_code($http_status);
header('Content-Type: application/json');
echo json_encode(array('message' => $message));
exit;
}
function signature_matches($raw_body, $signature, $secret)
{
if ($secret === '') {
return false;
}
$expected = 'sha256=' . hash_hmac('sha256', $raw_body, $secret);
return hash_equals($expected, $signature);
}
function text_field($fields, $name)
{
return isset($fields[$name]) && is_string($fields[$name])
? $fields[$name] : '';
}
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
header('Allow: POST');
respond(405, 'Use POST.');
}
// The placeholder above is public, so anyone could sign with it.
$secret = TRACKCOURIER_WEBHOOK_SECRET;
$previous_secret = TRACKCOURIER_WEBHOOK_PREVIOUS_SECRET;
if ($secret === '' || $secret === 'paste-your-signing-secret-here') {
error_log('TrackCourier webhook: paste your signing secret into this file');
respond(401, 'Signing secret not set.');
}
// Check the signature on the raw body, byte for byte, before anything else:
// json_decode() then json_encode() can change the bytes, and then it fails.
// Read the header from $_SERVER: getallheaders() is missing on some servers.
$raw_body = file_get_contents('php://input');
$signature = isset($_SERVER['HTTP_X_TRACKCOURIER_SIGNATURE'])
? $_SERVER['HTTP_X_TRACKCOURIER_SIGNATURE'] : '';
if (!signature_matches($raw_body, $signature, $secret)
&& !signature_matches($raw_body, $signature, $previous_secret)) {
respond(401, 'Signature does not match.');
}
$event = json_decode($raw_body, true);
if (!is_array($event) || !isset($event['data']) || !is_array($event['data'])) {
respond(400, 'Not a trackcourier.io update.');
}
$data = $event['data'];
$event_name = text_field($event, 'event');
$courier = text_field($data, 'courier');
$tracking_number = trim(text_field($data, 'tracking_number'));
if ($event_name === '' || $courier === '' || $tracking_number === '') {
respond(400, 'Not a trackcourier.io update.');
}
// A test event names no real shipment: its courier begins "synthetic-test-".
if (strpos($courier, 'synthetic-test-') === 0) {
respond(200, 'Test event received.');
}
try {
save_tracking_update(
$tracking_number,
$courier,
text_field($data, 'status'),
isset($data['checkpoints']) && is_array($data['checkpoints'])
? $data['checkpoints'] : null
);
} catch (Throwable $e) {
error_log('TrackCourier webhook not saved: ' . $e->getMessage());
respond(500, 'Not saved.');
}
respond(200, 'Received.');
// Write your own code in this function. Aim to answer within 5 seconds.
//
// $tracking_number the docket. Find your booking by this alone: $courier is
// our name for the courier (for example blue-dart-courier),
// not the one you sent us.
// $status the shipment's state, for example delivered, in_transit,
// out_for_delivery or exception. Treat a value you do not
// know as still in progress.
// $checkpoints the shipment's whole history, or null when this update
// carries none. Replace the checkpoints you hold for the
// docket with these rather than adding them: the same
// update can arrive more than once. When it is null, keep
// the ones you hold.
//
// A docket that is not yours must still get a 200: just return.
function save_tracking_update($tracking_number, $courier, $status, $checkpoints)
{
// Until you replace this line, every live update gets a 500, so none is
// counted as delivered before your code saves it. We try each one again,
// up to six attempts in all over about 27 hours: write this before then.
throw new Exception('Write your own code in save_tracking_update().');
}
After you rotate your signing secret, put the old one in TRACKCOURIER_WEBHOOK_PREVIOUS_SECRET for at least 15 minutes.
To see it answer, use our Postman collection: set webhook_url to the file's address, then run 1. Create a test webhook and 4. Fire a test event at it.
Common PHP mistakes
- An empty 500 is usually a PHP error. The file's own
500, before you writesave_tracking_update(), is expected: your error log says to write it. Any other500with an empty body is usually a fatal error: withdisplay_errorsoff, PHP answers with nothing, and your PHP error log names the file and line. On PHP 7.2 and 7.3 the common cause is code written for a newer PHP:str_contains()needs PHP 8 ("Call to undefined function str_contains()"), andfn() =>needs PHP 7.4. getallheaders()is not everywhere. Command-line PHP lacks it, and so does PHP-FPM before PHP 7.3. Read the signature from$_SERVER['HTTP_X_TRACKCOURIER_SIGNATURE'].- Check the signature on the raw body. Read it once with
file_get_contents('php://input').$_POSTis empty for a JSON body, andjson_encode(json_decode($body))can write different bytes (PHP writes/as\/and Hindi text as\ucodes), and then the signature does not match. - Compare with
hash_equals(), never==. It takes the same time however much of the signature matches. - A certificate chain with a missing link. If your server does not send its intermediate certificates, a browser may still open your address while our servers cannot connect, and the webhook's recent deliveries on your dashboard show
network_error(any failed connection shows that). Install your certificate's full chain; on cPanel, paste the intermediate certificates into "Certificate Authority Bundle (CABUNDLE)". - A redirect in front of the file. A rule in
.htaccessor WordPress that adds https, www or a trailing slash answers ourPOSTwith a redirect. After a301,302or303the update arrives as aGETwith no body, and if that answers2xxwe count it delivered (Retry Policy). Add the exact address the file answers at.
Error Handling
Errors return a consistent JSON structure with an error code and message.
For example, when your account has no shipments left, a lookup of a new parcel gets:
{
"success": false,
"error": {
"code": "NO_SHIPMENTS_LEFT",
"message": "You have no shipments left. New shipments wait for a top-up; the ones you already have are still tracked. https://api.trackcourier.io/dashboard/usage"
}
}
Error Codes
Branch on error.code: the HTTP status that comes with an error can vary. A 401 also carries detail, the same message, as it always has.
| Code | HTTP Status | Description |
|---|---|---|
API_KEY_REQUIRED |
401 | No X-API-Key header was sent |
INVALID_API_KEY |
401 | The API key is wrong or no longer active |
NO_SHIPMENTS_LEFT |
402 | No shipments left. New shipments wait for a top-up; the ones you already have are still tracked. |
QUOTA_EXCEEDED |
402 | Older free accounts only: this month's free lookups are used up. Accounts that count shipments get NO_SHIPMENTS_LEFT instead. |
ACCOUNT_NEEDS_ATTENTION |
402 | The account needs attention. Email api@trackcourier.io |
COURIER_NOT_FOUND |
404 | No courier has that slug or name. When we can tell which slug you meant, the error also carries did_you_mean. |
INVALID_TRACKING_NUMBER |
400 | The tracking number cannot be that courier's (checked today for India Post, Speed Post, Registered Post and India Post International). Nothing was looked up or counted; the message says what to send. |
COURIER_NOT_SUPPORTED |
400 | Tracking for this courier is not available through the API. GET /v1/couriers lists every courier you can track. |
TRACKING_ERROR |
4xx | We could not track this number. Check the courier and the tracking number. |
TIMEOUT |
504 | The courier did not answer in time. Retry in a minute. |
SERVICE_ERROR |
5xx, or 404 | A temporary error. Retry in a minute. |
Supported Couriers
Every account can track every courier below. Use the slug or the name in your API requests.
bluedartdelhiverydtdcindiapostspeedpostxpressbeesshadowfaxekarttrackonshreemarutiprofessionalgatisafexpresscanadapostshreetirupatishreeanjanistcouriervrlskykingshreemahavirshreenandanshiprocketindiapostinternationaltciexpressomlogisticsvtransrivigotcifreightarccarriermadhurregisteredpostvxpressnitcoposlajugmsworldwidemarkexpressdpworldmovinvalmorworldexpressxindusallcargo