Shipping Calculator for E-Commerce

Our company is engaged in the development, support and maintenance of sites of any complexity. From simple one-page sites to large-scale cluster systems built on micro services. Experience of developers is confirmed by certificates from vendors.
Development and maintenance of all types of websites:
Informational websites or web applications
Business card websites, landing pages, corporate websites, online catalogs, quizzes, promo websites, blogs, news resources, informational portals, forums, aggregators
E-commerce websites or web applications
Online stores, B2B portals, marketplaces, online exchanges, cashback websites, exchanges, dropshipping platforms, product parsers
Business process management web applications
CRM systems, ERP systems, corporate portals, production management systems, information parsers
Electronic service websites or web applications
Classified ads platforms, online schools, online cinemas, website builders, portals for electronic services, video hosting platforms, thematic portals

These are just some of the technical types of websites we work with, and each of them can have its own specific features and functionality, as well as be customized to meet the specific needs and goals of the client.

Our competencies:
Development stages
Latest works
  • image_web-applications_feedme_466_0.webp
    Development of a web application for FEEDME
    1161
  • image_ecommerce_furnoro_435_0.webp
    Development of an online store for the company FURNORO
    1041
  • image_crm_enviok_479_0.webp
    Development of a web application for Enviok
    822
  • image_crm_chasseurs_493_0.webp
    CRM development for Chasseurs
    847
  • image_website-sbh_0.png
    Website development for SBH Partners
    999
  • image_website-_0.png
    Website development for Red Pear
    451

Development of a shipping calculator for e-commerce

Customers shouldn't have to add items to cart, enter address, click checkout, and only on the final step discover that shipping costs half the order. This is one of the main reasons for abandoned carts. A shipping calculator solves this problem — showing cost immediately, before checkout begins.

What the calculator computes

Shipping cost depends on parameters from different sources:

  • Origin — warehouse or nearest store address
  • Destination — customer address, door-to-door or pickup point
  • What's being shipped — weight and dimensions of items in cart
  • Shipping method — courier, pickup point, locker, postal service
  • Urgency — standard or express

Item parameters are stored in the e-commerce database. Shipping rates are either in own tables (for fixed-price partner contracts) or come in real-time via carrier API.

Local tariff tables

For simple cases — fixed-price contracts or own delivery — rates are stored locally:

CREATE TABLE shipping_zones (
    id SERIAL PRIMARY KEY,
    name VARCHAR(100),
    regions TEXT[], -- array of region or city codes
    base_price DECIMAL(10,2),
    price_per_kg DECIMAL(10,2),
    price_per_km DECIMAL(10,2),
    min_days INT,
    max_days INT
);

CREATE TABLE shipping_methods (
    id SERIAL PRIMARY KEY,
    zone_id INT REFERENCES shipping_zones(id),
    name VARCHAR(100),
    carrier VARCHAR(50),
    multiplier DECIMAL(4,2) DEFAULT 1.0, -- for express delivery
    free_from DECIMAL(10,2) -- order amount for free shipping
);
class LocalShippingCalculator
{
    public function calculate(Cart $cart, Address $destination): Collection
    {
        $zone = $this->zoneDetector->detect($destination->city);
        $weight = $cart->totalWeight(); // kg
        $orderTotal = $cart->total();

        return ShippingMethod::where('zone_id', $zone->id)->get()
            ->map(function (ShippingMethod $method) use ($weight, $orderTotal, $zone) {
                $cost = $zone->base_price + ($weight * $zone->price_per_kg);
                $cost *= $method->multiplier;

                // Free shipping above certain amount
                if ($method->free_from && $orderTotal >= $method->free_from) {
                    $cost = 0;
                }

                return [
                    'id'       => $method->id,
                    'name'     => $method->name,
                    'carrier'  => $method->carrier,
                    'cost'     => round($cost, 2),
                    'min_days' => $zone->min_days * $method->multiplier < 1 ? 1 : (int)($zone->min_days / $method->multiplier),
                    'max_days' => $zone->max_days,
                    'free'     => $cost === 0.0,
                ];
            });
    }
}

Real-time API calculation

For current carrier rates, requests go to their API. Example with CDEK:

class CdekShippingCalculator
{
    private string $baseUrl = 'https://api.cdek.ru/v2';

    public function calculate(
        string $fromCity,
        string $toCity,
        float $weight,
        array $dimensions
    ): array {
        $token = $this->authenticate();

        $response = Http::withToken($token)
            ->post("{$this->baseUrl}/calculator/tarifflist", [
                'from_location' => ['city' => $fromCity],
                'to_location'   => ['city' => $toCity],
                'packages'      => [[
                    'weight' => (int)($weight * 1000), // grams
                    'length' => $dimensions['length'],
                    'width'  => $dimensions['width'],
                    'height' => $dimensions['height'],
                ]],
            ]);

        return collect($response->json('tariff_codes'))
            ->map(fn($t) => [
                'tariff_code'  => $t['tariff_code'],
                'tariff_name'  => $t['tariff_name'],
                'cost'         => $t['delivery_sum'],
                'min_days'     => $t['period_min'],
                'max_days'     => $t['period_max'],
            ])
            ->toArray();
    }
}

Aggregating multiple carriers

Real calculator usually shows options from several carriers simultaneously. Requests go in parallel:

public function getShippingOptions(Cart $cart, Address $address): array
{
    $weight = $cart->totalWeight();
    $dimensions = $cart->boundingBox();

    // Parallel requests to carriers
    $results = collect([
        'cdek'     => fn() => $this->cdek->calculate($address, $weight, $dimensions),
        'boxberry' => fn() => $this->boxberry->calculate($address, $weight, $dimensions),
        'pochta'   => fn() => $this->russianPost->calculate($address, $weight, $dimensions),
    ])->map(function ($calculator, $carrier) {
        try {
            return $calculator();
        } catch (\Exception $e) {
            // If one service unavailable — don't break everything
            logger()->warning("Shipping calculator error: $carrier", ['error' => $e->getMessage()]);
            return [];
        }
    })->flatten(1)->sortBy('cost')->values();

    return $results->toArray();
}

If CDEK returned error — show only Russian Post and Boxberry. Customer sees fewer options, not an error.

Caching calculations

Requests to carrier API are slow (200–800 ms) and sometimes paid (some gateways count requests). Cache by key from parameters:

public function calculateCached(string $fromCity, string $toCity, float $weight): array
{
    $cacheKey = "shipping:{$fromCity}:{$toCity}:" . round($weight, 1);

    return Cache::remember($cacheKey, now()->addMinutes(30), function () use ($fromCity, $toCity, $weight) {
        return $this->calculate($fromCity, $toCity, $weight);
    });
}

Rates change rarely — 30 minutes is sufficient. On rate update — invalidate cache by pattern shipping:*.

Calculator interface

On product or cart page — compact block: city input field, methods list with prices and timeframes. Without page reload:

const ShippingCalculator = () => {
  const [city, setCity] = useState('');
  const [options, setOptions] = useState([]);
  const [loading, setLoading] = useState(false);

  const calculate = useMemo(
    () =>
      debounce(async (cityValue) => {
        if (cityValue.length < 3) return;
        setLoading(true);
        try {
          const res = await fetch('/api/shipping/calculate', {
            method: 'POST',
            headers: { 'Content-Type': 'application/json' },
            body: JSON.stringify({ city: cityValue, cart_id: cartId }),
          });
          const data = await res.json();
          setOptions(data.options);
        } finally {
          setLoading(false);
        }
      }, 600),
    [cartId]
  );

  return (
    <div className="shipping-calculator">
      <input
        value={city}
        onChange={(e) => { setCity(e.target.value); calculate(e.target.value); }}
        placeholder="Enter your city"
      />
      {loading && <Spinner />}
      {options.map((opt) => (
        <ShippingOption key={opt.id} option={opt} />
      ))}
    </div>
  );
};

Debounce at 600 ms — don't fire requests after every character.

Volumetric weight

Many carriers calculate billable weight as max of actual and volumetric:

public function billableWeight(float $actualKg, array $dimensions): float
{
    // Standard coefficient: 1 kg = 5000 cm³
    $volumetricWeight = ($dimensions['length'] * $dimensions['width'] * $dimensions['height']) / 5000;
    return max($actualKg, $volumetricWeight);
}

For air delivery coefficient is different (6000 or 6800 cm³/kg), for sea — another. This must be accounted for, otherwise rates will be underquoted.

Development timeline

Calculator with one carrier using fixed rates — 2–3 days. With real API of one carrier — 3–5 days (including error handling and caching). Aggregator for 3–5 carriers with selection interface — 2–3 weeks.