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.







