In short
- There are four touchpoints: a quote at checkout, a booking when payment succeeds, a label for the parcel, and status updates back to the order.
- Send an idempotency key with every booking, so that a retry after a timeout cannot create a second delivery.
- Take status from webhooks. Verify the signature on the raw body, answer fast, and treat every event as possibly duplicated or out of order.
- Keep the API key on your server. Nothing in the browser or a mobile app should ever hold it.
The four touchpoints
A delivery integration looks large and is mostly four moments in the life of an order. Get these right and the rest is error handling.
| Touchpoint | When | Call | What you store |
|---|---|---|---|
| Quote | At checkout, once the address is known | POST /rates/quote | The price and window you showed. Nothing is stored on the delivery side |
| Book | When payment is confirmed | POST /shipments with an Idempotency-Key | The tracking number, tracking link and status, against your order |
| Label and collection | When the order is packed | GET /shipments/{id}/label | The printed label, or the barcode on your own packing slip |
| Tracking and status | From booking to delivery | Webhooks, with GET /shipments/{id} as a fallback | Order status, times and proof of delivery details |
The examples use the API that every YallaRoute workspace exposes, which a delivery company running on YallaRoute gives to its business customers. Paths are relative to a base such as https://YOUR-DELIVERY-COMPANY.example/api/v1. Other delivery APIs differ in names and agree on the ideas.
Every booking carries an address object: lines, city, region, postal code where the country uses one, country, or coordinates. Field names differ between APIs and versions, so the samples below mark that part with a comment.
Authentication and keys
Requests are authenticated with a secret key sent as a bearer token.
Authorization: Bearer ks_live_...In YallaRoute a web shop creates its own keys on the Developers page of the customer portal. A key made there belongs to one sender account: it books for that account and sees only that account's deliveries. A key has a scope. Reading shipments, labels and quotes needs read. Booking and cancelling need write. The delivery company's plan switches the API on: it is included in the Growth, Scale and Enterprise plans.
Key handling
- The key lives in a server-side secret store or environment variable. Never in front-end code, a mobile app or a repository
- One key per system and environment, so that one can be revoked without stopping the others
- The lowest scope that does the job. A reporting tool needs read only
- Revoke and replace a key when someone who had access leaves, or the moment it appears in a log or a ticket
Quote at checkout
The quote call returns the price a booking with these details would get right now, the window it would be promised, and whether the address is in the delivery area. It stores nothing, so it is safe to call as the customer edits the basket.
- Call it from your server once the delivery address is complete, not on every keystroke.
- Send the order as the carrier will see it: service, packed weight, and dimensions if you have them.
- Show the total with its currency, and the promised window, straight from the response. Do not recompute tax yourself.
- Give the call a short timeout of two or three seconds. If it fails, show a fallback you have agreed with the delivery company, such as a flat rate.
- Cache by address, weight and service for a few minutes, so that a page reload is not a new call.
If the response says the address is not covered, say so at checkout and offer what you can. Finding out after payment costs a refund and a customer. And because a price can change between checkout and booking, store the price the booking returns, not the quote.
Book on payment, with an idempotency key
Book when payment is confirmed, from the same server-side job that marks the order paid. Do not book from the page the customer returns to: customers close tabs.
The risk in booking is the retry. Your request times out, you do not know whether the delivery was created, you send it again, and now two drivers are coming. An idempotency key removes the risk. You send a unique value with the request. If the server has already handled that value, it returns the first answer and creates nothing.
// Runs on your server when payment is confirmed.
const BASE = "https://YOUR-DELIVERY-COMPANY.example/api/v1";
async function bookDelivery(order) {
// Build the body once. A retry must send exactly the same bytes.
const body = JSON.stringify({
service: order.deliveryService,
order_ref: order.number,
recipient: { name: order.customerName, phone: order.phone, email: order.email },
address: order.deliveryAddress, // the address object, as your delivery company's reference describes it
parcel: { weight_kg: order.packedWeightKg },
});
for (let attempt = 1; attempt <= 4; attempt++) {
const res = await fetch(BASE + "/shipments", {
method: "POST",
headers: {
Authorization: "Bearer " + process.env.DELIVERY_API_KEY,
"Content-Type": "application/json",
"Idempotency-Key": "order-" + order.id,
},
body,
signal: AbortSignal.timeout(10000),
}).catch(() => null); // network error or timeout
if (res && res.status === 201) return (await res.json()).data;
if (res && res.status < 500 && res.status !== 409 && res.status !== 429) {
throw new BookingRejected((await res.json()).error); // fix the data, do not retry
}
await sleep(waitFor(res, attempt)); // defined under rate limits below
}
throw new Error("Booking not confirmed. Queue it and retry with the same key.");
}- The header is
Idempotency-Key: 1 to 120 printable characters with no spaces. Your order id is the natural choice. - A key is remembered for 24 hours. A repeat with the same key and the same body returns the first answer, with the response header
Idempotent-Replayed: true. - The same key with a different body answers 422
idempotency_key_reused. That is a bug on your side: a key must mean one request. - A repeat that arrives while the first is still being handled answers 409
request_in_progress. Wait and retry. - A request that failed is forgotten, so you can correct the data and send it again under the same key.
The response is the shipment. Store its id, which is the tracking number, with tracking_url, status and price, against your order. If the consignment has several parcels, each has its own tracking number in piece_ids.
Errors, rate limits and pagination
Every response is JSON in one of two envelopes: data with meta on success, or error with a code, a message and, for validation, a list of fields.
| Status | Example codes | What to do |
|---|---|---|
| 400 | invalid_json, invalid_parameter, invalid_cursor | A bug in the request. Fix the code. Do not retry |
| 401, 403 | invalid_key, insufficient_scope, forbidden | Stop and alert a person. Retrying will not help |
| 404 | not_found | The tracking number is wrong, or belongs to another sender |
| 409 | request_in_progress, not_cancellable | Retry the first after a pause. The second is final |
| 413 | payload_too_large | The body is over 64 KB |
| 422 | validation_failed, idempotency_key_reused | Show error.fields to someone who can correct the order. Do not retry unchanged |
| 429 | rate_limited | Wait the number of seconds in Retry-After, then retry |
| 500 | server_error | Retry with backoff, under the same idempotency key |
Validation errors are about your customers' data. Each entry in error.fields names a field, such as recipient.name, and says what is wrong in a sentence you can show to staff. Put the order in a queue that a person works: an order that fails validation silently is a parcel that never ships.
A YallaRoute key may make 120 requests in any 60 seconds, and every response carries X-RateLimit-Limit, X-RateLimit-Remaining and X-RateLimit-Reset. Over the limit, the answer is 429 with Retry-After in seconds. Honour it, and back off on server errors and timeouts with growing, randomised waits.
const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
// How long to wait before the next attempt, in milliseconds.
function waitFor(res, attempt) {
const retryAfter = res ? Number(res.headers.get("Retry-After")) : 0;
if (retryAfter > 0) return retryAfter * 1000;
const base = 500 * 2 ** attempt; // 1s, 2s, 4s, 8s
return base / 2 + Math.random() * (base / 2); // jitter, so retries do not arrive together
}List calls return a page at a time. GET /shipments takes limit, up to 100, and returns meta.has_more and meta.next_cursor. Pass the cursor back as cursor and stop when has_more is false. A cursor is valid for 15 minutes, so run a reconciliation through in one go. Lists are for reconciliation, not for status.
Labels and collection
Every parcel needs something a driver can scan. Some APIs return a finished label as a file. Others, YallaRoute among them, return label data for you to draw: GET /shipments/{id}/label answers with the tracking number, a Code 128 barcode value, a QR value that opens the tracking page, carrier and service names, delivery details, handling words such as fragile, any cash to collect and your order reference.
- Print the barcode at a size and contrast a phone camera can read, and test it with the delivery company's scanner before go-live.
- Print one label per parcel. A consignment of three boxes has three tracking numbers.
- Fetch the label when the order is packed, not when it is booked, so that a cancelled order never gets one.
- If packing changes the weight or the number of parcels, cancel and rebook before the parcel leaves.
Collection is the other half. Agree how parcels reach the delivery company: a daily collection at a fixed time, a collection per booking, or your own drop at their depot. Agree the cut-off too, and show customers a promise that matches it.
Cancelling is POST /shipments/{id}/cancel. It is safe to repeat. Once the parcel is out for delivery or finished it answers 409 not_cancellable, and a person has to phone dispatch.
Webhooks: subscribe, verify, answer fast
A webhook is the delivery system calling you when something happens, so that you never have to ask.
Subscribe. Register an https address and choose the events. In YallaRoute's customer portal a sender can add up to 5 endpoints. The signing secret is shown when the endpoint is created, and can be shown again or replaced there. A shop usually wants shipment.created, shipment.out_for_delivery, shipment.delivered, shipment.failed, shipment.rescheduled, shipment.returned and shipment.cancelled.
Verify the signature. Anyone can post to your address, so check that each request came from the delivery system. YallaRoute sends the header X-YallaRoute-Signature: t=<unix ms>,v1=<hex>. The v1 value is an HMAC-SHA256, keyed with the endpoint's secret, of the timestamp, a full stop and the raw request body.
import { createHmac, timingSafeEqual } from "node:crypto";
// rawBody: the request body exactly as received, before any JSON parsing.
// header: the value of the signature header, "t=<unix ms>,v1=<hex>".
export function verify(rawBody, header, secret) {
const parts = Object.fromEntries(header.split(",").map((p) => p.split("=")));
const expected = createHmac("sha256", secret).update(parts.t + "." + rawBody).digest("hex");
const fresh = Math.abs(Date.now() - Number(parts.t)) < 5 * 60 * 1000;
return fresh && expected.length === (parts.v1 || "").length
&& timingSafeEqual(Buffer.from(expected), Buffer.from(parts.v1));
}Use the raw body: parsing and re-serialising the JSON changes the bytes. Check the timestamp, which is in milliseconds, and reject anything more than a few minutes old so that a captured request cannot be replayed. Compare in constant time, as above.
Respond fast, process afterwards. Your endpoint has one job: verify, store and answer 200. YallaRoute waits 6 seconds, treats any 2xx as delivered and does not follow redirects. Anything else is retried after 30 seconds, 2 minutes, 10 minutes and 1 hour, five attempts in all, and then marked failed. So write the event to a queue and return. Update the order and email the customer from a worker.
Expect duplicates and disorder. Retries mean the same event can arrive twice, and two events for one parcel can arrive in either order. Each delivery has an id in its body that stays the same across retries, and the X-YallaRoute-Delivery header carries the same number. Store the ids you have processed and skip repeats. For order, compare the event's created time with the last one applied to that order.
{
"id": "evt_48213",
"type": "shipment.delivered",
"created": 1796212800000,
"data": {
"id": "KS-TEST-0001",
"status": "delivered",
"orderRef": "ORDER-1001",
"attempt": 1,
"deliveredAt": 1796212800000,
"receivedBy": "Alex Morgan",
"trackingPath": "/track/KS-TEST-0001"
}
}Note the two conventions. Webhook bodies use camelCase names and Unix milliseconds. The REST responses use snake_case names and ISO 8601 times. Convert both on the way in.
Map delivery statuses to order statuses
Your customers read your shop's order statuses, not the carrier's. Map them once, in one place. These are the statuses of a YallaRoute shipment with a sensible mapping. Each has an event of the same name, such as shipment.delivered, except loaded.
| Delivery status | Meaning | Order status in the shop | Message the customer? |
|---|---|---|---|
created | Booked, not yet collected | Processing | No |
collected | Picked up from you | Shipped | Yes, with the tracking link |
at_hub | At the delivery company's depot | Shipped | No |
loaded | On a vehicle | Shipped | No |
out_for_delivery | The driver has started the run | Out for delivery | Only if the delivery company does not |
delivered | Proof of delivery recorded | Delivered | Yes, unless the delivery company does |
failed | An attempt was made and failed | Delivery attempted | Yes, with what happens next |
returned | Coming back to you | Returned | Yes. Start your refund or resend process |
cancelled | Cancelled before going out | Cancelled | Depends on who cancelled |
Two rules keep the mapping safe. Treat delivered, returned and cancelled as final: once an order is there, ignore older events that arrive late. And agree with the delivery company who messages the recipient, or the customer hears the same news twice. See delivery notifications that reduce contacts.
A testing plan
Test real behaviour, not only the happy path. Ask the delivery company how they want test bookings made. In YallaRoute a booking through the API is a real booking, so use references that dispatch will recognise as tests, and cancel what you create.
| Test | Expect |
|---|---|
| Quote an address inside the area, then one outside | A price and a window, then a response marked not covered |
| Book once | 201, a tracking number, and a shipment.created event |
| Send the same booking again with the same key | The same shipment, Idempotent-Replayed: true, and no second delivery |
| Same key, different body | 422 idempotency_key_reused |
| Book with the recipient's name missing | 422 validation_failed, with the field named |
| Send requests faster than the limit | 429 with Retry-After. Your client waits and recovers |
| Post a webhook with a wrong signature | Rejected, and nothing processed |
| Replay a genuine webhook | Processed once |
| Deliver the delivered event before out for delivery | The order ends as delivered |
| Make your endpoint fail for a minute | The event arrives on a later retry |
| Cancel a booking, then cancel it again | Cancelled both times, with no error |
YallaRoute's portal can send a signed test event to an endpoint, which is the quick way to prove your signature check before real parcels move.
Going live checklist
- The key is in the production secret store with the right scope, and is in no repository or log
- Every booking sends an idempotency key derived from the order
- Every call has a timeout, and retries back off
- Validation failures land in a queue that a named person checks daily
- The webhook endpoint verifies signatures, answers within a second and processes from a queue
- Processed event ids are stored, repeats are skipped and final statuses are protected
- A nightly job lists recent shipments and compares them with orders, to catch anything a webhook missed
- Alerts fire on repeated 401, 403 and 500 responses, and on a webhook queue that keeps growing
- The delivery company knows your go-live date, your collection arrangements and who to call
- The first ten live orders are checked by hand, end to end
Failure modes and defences
| Failure | What you see | Defence |
|---|---|---|
| Double booking | Two deliveries for one order | An idempotency key on every booking |
| Lost booking | An order paid and nothing booked | Book from a retried server-side job. Reconcile nightly |
| Leaked key | Bookings you did not make | Server-side keys, lowest scope, revoke at once |
| Silent validation failure | Orders stuck with no delivery | An error queue with a person behind it |
| Webhook endpoint down | Statuses stop moving | Retries cover short outages. Reconciliation covers long ones |
| Forged webhook | An order marked delivered that was not | Signature and timestamp check |
| Duplicate or late events | A customer told twice, or an order moving backwards | Store event ids. Protect final statuses |
| Address rejected after payment | A paid order that cannot be delivered | Quote and check coverage before payment |