Skip to content
All posts
shippingsaudi-arabiaecommerceapi-integrationcase-study

Shipping Integration in Saudi Arabia: How We Connected OTO

November 12, 2026 11 min read· Mahmoud Makhlouf
اقرأ هذا المقال بالعربية

A customer in Dammam adds a brake kit to the cart, taps checkout, and sees "Delivery: SAR 0" because nobody wired a real carrier price into the app. The store eats the shipping cost on every order like that, and the owner only notices at the end of the month.

Short answer: for most Saudi online stores and marketplaces, the practical route is to integrate one shipping aggregator such as OTO instead of integrating each carrier separately. You get live delivery quotes at checkout, one tracking feed, COD handling and returns through a single API. The engineering work that matters is caching quotes, verifying webhooks, and keeping shipment creation from ever breaking payment.

The business problem

Shipping in Saudi Arabia is not one price. The fee depends on the origin city, the destination city, the weight and size of the package, whether the customer pays cash on delivery, and which carrier you pick. A store that charges one flat fee for everything will overcharge some customers (who abandon the cart) and undercharge others (where the store pays the difference).

Then there is everything after the sale:

  • Someone has to create the shipment with the carrier and print a label.
  • The customer wants to know where the order is without calling you.
  • For COD orders, the carrier collects the cash and transfers it later, so you need to know what is owed.
  • Returns and failed delivery attempts need to be visible to your team the same day, not discovered from an angry message.

Copy-paste between a carrier portal and your admin panel works at ten orders a day and breaks at a hundred.

Your options: direct carriers or an aggregator

There are two broad ways to connect an online store to shipping companies in Saudi Arabia.

Integrate each carrier directlyUse an aggregator (e.g. OTO)
ContractsOne contract per carrierUse the aggregator's rates, or plug in your own carrier contracts
EngineeringOne API, one status vocabulary, one label format per carrierOne API and one status list for all carriers
Checkout quotesYou compare carriers yourselfOne call returns priced options from several carriers
TrackingSeparate webhooks or polling per carrierOne webhook feed
Switching carriersNew integration projectUsually a setting in the aggregator dashboard
CostNo platform fee, but more build and maintenancePlatform plan and per-shipment pricing set by the aggregator

Direct integration makes sense mainly for very high volume through one carrier on a negotiated contract. For most stores and marketplaces, an aggregator is the faster path to nationwide coverage.

OTO is one of the aggregators built for this market. At the time of writing (November 2026), its Arabic homepage advertises more than 460 local and international carriers and more than 45 sales channels, and its integration pages list carriers such as Aramex, SMSA, Saudi Post (SPL) and NAQEL Express. OTO's carrier pages say you can ship on OTO's own discounted rates or connect your existing carrier contract. Plan limits (for example how many carriers you can connect) change over time, so check the current plans on tryoto.com before you commit.

Three business decisions to make before you write code

  1. Who pays shipping? The customer, nobody above a cart threshold, or a flat fee. Many stores combine them: free above a threshold, live price below it.
  2. Do you add a margin on delivery? A marketplace usually needs to cover its own support and operations cost. You can add a percentage on top of the carrier fee. Decide whether the customer sees one total or a breakdown.
  3. What happens when the carrier API is down or has no route? You need a fallback price, or the checkout stops working. Decide it now, not during an outage.

How we built it in Ajza

Ajza is a Saudi automotive parts marketplace: many independent stores, one customer app, one admin panel. Every order has to be shipped from the store's city to the customer's address, and the platform needed real carrier prices at checkout. We integrated OTO as the single shipping layer.

Here is what the business side looks like in the shipped product:

  • Checkout is per store. A cart with items from two stores becomes two orders, each with its own delivery fee, because the packages ship from different cities.
  • Free-shipping threshold per store. Each store sets its own threshold. Above it, delivery is free. Below it, we ask OTO for a live quote.
  • The customer can choose a carrier. We fetch every priced option, sorted cheapest first, and preselect the cheapest. If the customer picked another option in the cart, the order honours it.
  • One total for the customer. The platform adds its own delivery commission, a percentage set in the admin panel, on top of the carrier price. The customer only ever sees the total. The breakdown (carrier fee, commission rate, commission amount) is saved on the order for admin reporting.
  • A fallback that keeps checkout alive. If OTO is not configured, or no carrier covers that city pair, the order uses the store's flat shipping fee.
  • Coverage before checkout. When a customer drops a pin for a new address, the app can tell them whether delivery is available there, before they build a cart.
  • COD is passed through. For cash-on-delivery orders we send the full order total as the amount due to the carrier. For prepaid orders the amount due is zero.
  • Tracking reaches the customer. Carrier status updates arrive by webhook, update the order, push a live update to the app over a socket, and send push notifications at key moments like "out for delivery".

customer app checkout showing the delivery fee and the carrier options list for one storecustomer app checkout showing the delivery fee and the carrier options list for one store

admin shipping page listing orders with OTO status, carrier and tracking numberadmin shipping page listing orders with OTO status, carrier and tracking number

Under the hood

The diagram below is the path one order takes.

Customer app            Ajza backend                         OTO
------------            ------------                         ---
checkout  ──quote──▶  cache (5 min) ──miss──▶  checkOTODeliveryFee
                      + commission
pay       ──────────▶ payment tx COMMIT
                      └─ after commit: createShipment ──────▶ create order + shipment
                                                              (carrier picks up)
order screen ◀─socket─ webhook handler ◀──── signed status ── webhook
             ◀─push───  (dedupe, map status)

Authentication that survives concurrency

OTO uses a refresh token that you exchange for a short-lived access token (a JWT). Two details shaped our code. First, OTO rotates the refresh token on each exchange, so the service must keep the newest one. Second, at checkout many requests can arrive at the same moment the token expires. If each of them calls the refresh endpoint, they race each other with a token that has already been rotated.

So the refresh is single-flight: the first caller starts it, and every other caller waits on the same promise.

private async getAccessToken(): Promise<string> {
  // Refresh 60s before expiry to avoid racing in-flight requests.
  if (this.accessToken && Date.now() < this.expiresAt - 60_000) {
    return this.accessToken;
  }
  if (this.refreshPromise) return this.refreshPromise; // share one refresh
  this.refreshPromise = this.refreshAccessToken().finally(() => {
    this.refreshPromise = null;
  });
  return this.refreshPromise;
}

An axios response interceptor handles the remaining case: on a 401 it clears the cached token and retries the request once, and only once.

Quotes are slow, so we cache them

A live delivery-fee call to OTO can take several seconds (our code comments note around 8 seconds per call). Customers toggle between carriers and go back and forth in checkout, so calling OTO every time is not acceptable. We cache quote results for 5 minutes, keyed by the exact request (origin, destination, weight, dimensions), and de-duplicate in-flight requests so ten identical calls become one upstream call. The list of cities OTO covers changes rarely, so we cache it for an hour with the same in-flight protection.

Package size when the catalog has no dimensions

Carriers price by weight and size, and most parts catalogs lack reliable dimensions. We use the product's own weight when it is set, fall back to a default weight per unit when it is not, apply a minimum package weight so a cart is never sent as zero kilograms, and use a default box size. All of these defaults are configuration values, so they can be tuned without a deploy.

Phone numbers in one format

Customers type Saudi mobiles as +966…, 00966…, 05… or 5…. OTO's pickup-location API expects the local 9-digit form, so every number passes through one normalizer first.

Shipment creation must never break payment

This is the decision we would repeat on every project. A successful payment updates the order inside a database transaction. Creating the OTO shipment is a network call that can be slow or fail; inside the transaction, an OTO timeout could roll back a payment the customer already made.

So shipment creation runs only after the transaction commits, and its failure is logged, not thrown:

await queryRunner.commitTransaction();

// Post-commit: failures here must not bubble up.
// Admins can retry the shipment from the shipping page.
if (payment.orderId) {
  this.shipping
    .createShipmentForOrder(payment.orderId)
    .catch((err) => this.logger.error(`Auto shipment failed: ${err}`));
}

The shipment function itself is idempotent: if the order already has an OTO ID, it returns without creating a second shipment. Before calling OTO it checks that the data is complete (customer name, phone, street address, a city name OTO recognises, store address and phone) and returns a clear list of what is missing, instead of passing on a vague error from the carrier side.

admin order detail with the shipment tracking timelineadmin order detail with the shipment tracking timeline

Webhooks: verify, route, de-duplicate, map

Every status change from the carrier arrives through one webhook endpoint. The handler does four things.

  1. Verify. OTO can sign the event with HMAC-SHA256 over orderId:status:timestamp, base64-encoded, or send a shared authorization key in a header. When credentials are configured, at least one of the two checks must pass.
  2. Route. Ajza ships three kinds of things: marketplace orders, external-parts orders and store requests. The handler looks the reference up in each in turn and passes the event to the right handler.
  3. De-duplicate. Webhooks can be delivered more than once. We store the raw OTO status on the record and skip any event whose status matches what we already have.
  4. Map. OTO has a long list of detailed status tokens. Our order model only needs a handful of states. A lookup table of about thirty tokens collapses them into processing, shipped, out for delivery, delivered, failed, returned and cancelled. Tokens we do not need for a state change are still recorded, so support staff can see the carrier's exact wording.
const OTO_STATUS_ACTION_MAP: Record<string, OrderAction> = {
  shipmentCreated: 'processing',
  pickedUp: 'shipped',
  inTransit: 'shipped',
  outForDelivery: 'out_for_delivery',
  delivered: 'delivered',
  pickupAttemted: 'failed',     // OTO's own spelling, kept as sent
  undeliveredAttempt: 'failed',
  reversePickedUp: 'returned',
  shipmentCanceled: 'cancelled',
  // ...
};

One small lesson sits in that table: match the provider's tokens exactly as they send them, including pickupAttemted. "Correcting" the spelling on your side means that event silently stops matching.

What we learned

  • Treat every carrier call as slow and fallible, and design checkout so it still completes when the call fails.
  • Keep the raw provider status next to your own status. It makes support conversations short.
  • Normalize inputs (phones, city names) at the boundary, once, in one function.
  • Put the commission breakdown on the order at creation time, so finance reports never have to recompute it.

Checklist: if you are integrating shipping in Saudi Arabia

  1. Decide who pays shipping, your free-shipping threshold, and whether you add a delivery margin.
  2. Define the fallback price for when the carrier API is down or has no route.
  3. Choose aggregator or direct carriers, and confirm which carriers cover your origin cities.
  4. Make sure every product has a weight, or agree on sensible defaults and a minimum.
  5. Store city names in the form the carrier API expects, not only the Arabic display name.
  6. Normalize Saudi mobile numbers before sending them.
  7. Cache delivery quotes for a few minutes and de-duplicate concurrent calls.
  8. Handle token refresh as single-flight if the provider rotates tokens.
  9. Create shipments after payment commits, idempotently, with a retry button for admins.
  10. Verify webhook signatures, skip duplicates, and record the raw status.
  11. Pass the correct COD amount due, and zero for prepaid orders.
  12. Map return and reverse-shipment statuses so returns are visible the same day.

Frequently asked questions

What is the best way to connect an online store to shipping companies in Saudi Arabia?

For most stores, integrating a shipping aggregator such as OTO is the fastest route, because one API gives you several carriers, live prices and one tracking feed. Direct carrier integration makes sense mainly when you ship high volume through a single carrier with a negotiated contract.

Does OTO support cash on delivery?

Yes. When you create an order through the OTO API you mark it as COD or prepaid and pass the amount the carrier should collect. OTO's plans describe how and how often collected COD cash is transferred to you, and those terms can change, so check the current plan details.

Can I show live shipping prices at checkout?

Yes. OTO offers a delivery-fee endpoint that returns priced options for an origin city, destination city and package size. Because the call can take several seconds, cache the result for a few minutes and keep a fallback flat fee for routes with no coverage.

Can a marketplace add its own margin to the delivery fee?

Yes. In Ajza the platform adds a configurable percentage on top of the carrier price and shows the customer one total. The carrier fee and the commission are saved separately on each order so admins can report on them.

How does order tracking reach the customer?

The carrier sends status changes to OTO, and OTO sends them to your webhook. Your backend verifies the event, updates the order, and pushes the new status to the customer app. OTO also offers its own tracking notifications to customers by SMS, WhatsApp or email.

Next step

If your shipping is still manual, start with the three business decisions above. Then see how we structured the rest of a parts marketplace in our spare parts marketplace architecture guide, and how we keep payment code safe in handling money correctly with idempotency and ledgers.

When you are ready to scope your own integration, send us a short project brief and we will tell you what it involves.

// Let's build

Have a product in mind? Get a clear plan and a free 15-minute intro call.

Tell us what you're building. We'll come back with an approach, a rough timeline, and a ballpark — usually within 24 hours.

Book a free discovery call WhatsApp