Skip to Content
FastracDocs

Show shipping options at checkout

Quote every courier at once, sort the results, and keep the customer's choice valid until payment.

Product
APIShipping Engine API
Section
Guides
Reading time
3 min read

Goal: at checkout, show your customer a list of couriers with price and delivery time, and book the one they choose.

Before you start: you can get an access token and have the subdistrictId of your warehouse and of the customer's address. See the Quickstart.

Here is what you will build. Try the sort buttons:

Choose shipping

You store: shippingRateCode = "SR-B9X3P7RE"
  1. Quote all couriers in one request

    When the customer reaches the shipping step, request rates with courierCode: "REGULAR", or "ALL" if you also offer instant delivery. Couriers that can't serve the route are left out automatically.

    checkout.js
    async function getShippingOptions(cart, address, token) {
      const res = await fetch(`${API}/b2b/shipping-rate`, {
        method: 'POST',
        headers: { Authorization: `Bearer ${token}`, 'Content-Type': 'application/json' },
        body: JSON.stringify({
          origin: WAREHOUSE, // { fullAddress, subdistrictId }
          destinations: [{ fullAddress: address.full, subdistrictId: address.subdistrictId }],
          courierCode: 'REGULAR',
          insurance: cart.total >= 1_000_000, // your own policy
          packages: [{
            itemValue: cart.total,
            isGlassware: cart.items.some((i) => i.fragile),
            weight: cart.items.reduce((g, i) => g + i.weightGrams * i.qty, 0),
            dimension: cart.boxSize, // { length, width, height } in cm
          }],
        }),
      });
    
      if (res.status === 404) return []; // no courier serves this route
      if (!res.ok) throw new Error((await res.json()).message);
      return (await res.json()).data;
    }
  2. Sort and label the options

    Show priceDetail.totalPrice, the full price including tax and insurance, never basePrice. etdRange is display text such as 2 - 3 Days, so parse the upper bound if you want to sort by speed:

    const maxDays = (etd) => {
      const nums = etd?.match(/\d+/g)?.map(Number);
      return nums?.length ? Math.max(...nums) : Infinity; // unknown estimates sort last
    };
    
    function toOptions(rates, sortBy = 'price') {
      return rates
        .map((r) => ({
          code: r.shippingRateCode,
          label: r.serviceName,
          price: r.priceDetail.totalPrice,
          eta: r.etdRange,
          cod: r.isSupportCod,
          expiresAt: new Date(r.validUntil),
        }))
        .sort((a, b) =>
          sortBy === 'price' ? a.price - b.price : maxDays(a.eta) - maxDays(b.eta) || a.price - b.price,
        );
    }

    Filter by what the order needs

    If the customer chose cash on delivery, request with codOption.isCod: true and keep only rates with isSupportCod: true. If you pick up from a warehouse, keep only isSupportPickup: true.

  3. Store the chosen shippingRateCode

    When the customer picks an option, save its shippingRateCode and validUntil with the cart. You don't need anything else: the code already locks in the courier, price, addresses and parcel.

  4. Check it is still valid at payment

    Rates usually last about 15 minutes. Customers sometimes take longer. Before you create the order, check validUntil and quote again if it has passed:

    async function ensureFreshRate(cart, token) {
      const msLeft = new Date(cart.rateValidUntil) - Date.now();
      if (msLeft > 60_000) return cart.rateCode; // more than a minute left: use it
    
      const fresh = await getShippingOptions(cart, cart.address, token);
      const same = fresh.find((r) => r.courierCode === cart.courierCode && r.serviceName === cart.serviceName);
      if (!same) throw new Error('This shipping option is no longer available.');
      if (same.priceDetail.totalPrice !== cart.shippingPrice) {
        // Show the new price and ask the customer to confirm before charging.
      }
      return same.shippingRateCode;
    }
  5. Book the shipment

    Pass the code to POST /b2b/orders with the sender and receiver contacts. The price is deducted from your balance and the courier is booked. The Orders section of these docs is coming next.

Checklist

  • Quote at the shipping step, not earlier.
  • Show totalPrice, and etdRange as an estimate.
  • Treat 404 as "no couriers available for this address", and tell the customer.
  • Store shippingRateCode and validUntil with the customer's choice.
  • Re-quote if the rate expired, and confirm any price change with the customer.
  • Re-quote whenever the address or cart changes.

Was this page helpful?

On this page