Open MercatoDocsSearch docsAPI reference

Framework

Shipping Carriers

A carrier prints its own labels and reports its own tracking statuses. The shipping adapter translates those operations into the common shipment model. Keep the provider's shipment reference so a later callback can update the original shipment.

The shipping_carriers module provides a provider-agnostic hub for shipment management. Each carrier (InPost, DPD, FedEx, etc.) is a separate package implementing the ShippingAdapter interface.

Architecture

Mirrors the payment gateway pattern:

ShippingAdapter interface

import type { ShippingAdapter } from 'packages/core/src/modules/shipping_carriers/lib/adapter'

const myCarrier: ShippingAdapter = {
  providerKey: 'my_carrier',

  async calculateRates(input) {
    // Return available shipping rates
    return [
      { serviceCode: 'standard', serviceName: 'Standard', amount: 9.99, currencyCode: 'USD', estimatedDays: 5 },
      { serviceCode: 'express', serviceName: 'Express', amount: 19.99, currencyCode: 'USD', estimatedDays: 2 },
    ]
  },

  async createShipment(input) {
    // Generate label and tracking number
    return { shipmentId: '...', trackingNumber: '...', labelUrl: '...' }
  },

  async getTracking(input) {
    // Fetch tracking status and events
    return { trackingNumber: '...', status: 'in_transit', events: [] }
  },

  async cancelShipment(input) {
    return { status: 'cancelled' }
  },

  async verifyWebhook(input) {
    return { eventType: 'tracking.updated', eventId: '...', idempotencyKey: '...', data: {}, timestamp: new Date() }
  },

  mapStatus(carrierStatus) {
    return 'in_transit'
  },
}

Unified shipment status

StatusMeaning
label_createdLabel generated, not yet picked up
picked_upCarrier has collected the package
in_transitPackage is moving through carrier network
out_for_deliveryFinal delivery attempt in progress
deliveredSuccessfully delivered
failed_deliveryDelivery attempt failed
returnedPackage returned to sender
cancelledShipment cancelled before pickup

Status transitions are monotonic – terminal statuses (delivered, returned, cancelled) cannot regress.

Carriers report the current status, not every step, so a carrier may skip intermediate statuses (for example label_created straight to delivered). Forward skips are applied; backwards moves (for example delivered to in_transit, or out_for_delivery to in_transit) are refused. Webhook and tracking-refresh updates evaluate the transition against the row read under a lock, so concurrent updates for the same shipment are applied one at a time.

Registering adapters

import { registerShippingAdapter } from 'packages/core/src/modules/shipping_carriers/lib/adapter-registry'
import { registerShippingWebhookHandler } from 'packages/core/src/modules/shipping_carriers/lib/adapter-registry'

export const setup: ModuleSetupConfig = {
  async onTenantCreated() {
    registerShippingAdapter(myCarrierAdapter)
    registerShippingWebhookHandler('my_carrier', verifyMyCarrierWebhook, { queue: 'my-carrier-webhook' })
  },
}

Webhook processing

Same async pattern as payment gateways:

  1. Carrier sends POST /api/shipping_carriers/webhook/{provider}.
  2. The route finds candidate CarrierShipment rows by the carrier shipment id. It reads shipmentId or data.shipmentId from the body; a carrier that nests the id elsewhere implements the optional extractWebhookShipmentId(payload) adapter method.
  3. Signature verified with each candidate's tenant credentials, ShippingWebhookEvent constructed. Verification must fail closed when no signing secret is configured.
  4. Event enqueued to carrier-specific worker queue.
  5. Worker maps the raw carrier status from event.data.status through mapStatus, updates CarrierShipment status and emits domain events.

Each delivery needs its own idempotencyKey (for example shipment id + event + status + timestamp). A key that only identifies the shipment makes every later status update for that shipment look like a duplicate. When a status transition is rejected, the worker keeps the claim for that delivery, so a redelivery of the same event is skipped while later deliveries, which carry their own keys, are still processed.

Core service methods

The ShippingCarrierService (resolved via DI as shippingCarrierService) provides:

MethodPurpose
calculateRates(input)Get available rates from a carrier
createShipment(input)Create shipment, generate label, persist CarrierShipment
getTracking(input)Fetch tracking info and update stored status
cancelShipment(input)Cancel shipment and update status

Admin UI entry points

The carrier shipment flow is intentionally order-driven:

This means the standalone /backend/shipping-carriers/create page is an implementation route, not a first-class sidebar destination. The supported operator flow is to launch shipment creation from an order row action or another order-scoped entry point.

Practical implications:

Events

Status events (status_changed, delivered, returned) carry previousStatus (the unified status the shipment had before the change) and newStatus. Events emitted by the webhook worker also carry carrierStatus, the raw status string reported by the carrier.

Mock adapter

A mock shipping adapter is included in the example module for development:

import { registerShippingAdapter } from 'packages/core/src/modules/shipping_carriers/lib/adapter-registry'
import { mockShippingAdapter } from './lib/mock-shipping-adapter'

registerShippingAdapter(mockShippingAdapter)

The mock adapter uses in-memory storage with fixed rates and simulated tracking events.

Previous: Built-in Subscribers · Next: System status variables