Skip to content

Shipping Integrations

This guide covers building carrier shipping integrations using the shipping_carrier backbone module — the shipping equivalent of Payment Integrations.

Carrier shipping is provider-agnostic. The shipping_carrier module handles:

  • The ShippingIntegration hook contract on the shared Integration model
  • Live rating on sales orders (SaleOrder.apply_shipping_method for a “Live Carrier Rate” method)
  • Label purchase, tracking, and void on the outbound delivery (Transfer)
  • Address validation

Carrier modules (DHL, FedEx, UPS, Royal Mail) implement the interface. Each ships as a normal module_category_integrations module with integration_category: Shipping (its catalogue heading) and provides: [shipping] (what every carrier lookup and picker — Integration.providers("shipping"), Q(provides__code='shipping') — keys on), so installing it auto-creates one shared Integration record whose credentials are company_scoped (each company plugs in its own keys against the same record).

┌──────────────────────────────────────────────────────────────────┐
│ CONSUMING SURFACES │
│ ┌───────────────┐ ┌───────────────┐ ┌────────────────────┐ │
│ │ Sales order │ │ Checkout │ │ Outbound Transfer │ │
│ │ (live rate + │ │ (live rates) │ │ (buy label, track, │ │
│ │ validate) │ │ │ │ void) │ │
│ └───────┬───────┘ └───────┬───────┘ └─────────┬──────────┘ │
│ └───────────────────┼─────────────────────┘ │
│ ▼ │
│ ┌──────────────────────────────────────┐ │
│ │ shipping_carrier (backbone) │ │
│ │ - ShippingIntegration hook contract │ │
│ │ - ShippingMethod "Live Carrier Rate" │ │
│ │ - Transfer carrier/tracking/label │ │
│ └──────────────────┬───────────────────┘ │
│ │ │
│ ┌───────────┬──────────┼───────────┬──────────────┐ │
│ ▼ ▼ ▼ ▼ ▼ │
│ shipping_dhl shipping_fedex shipping_ups shipping_royal_mail │
└──────────────────────────────────────────────────────────────────┘

The ShippingIntegration model in shipping_carrier defines the interface. All hooks are cooperative overrides: a provider guards each with its own _is_<carrier>() check and defers to super() when the integration isn’t its own — exactly like the payment providers.

Mode and Sandbox URL are not carrier-specific. Integration declares integration_mode (Test/Live), sandbox_url, and the api_base_url(test_url, live_url) seam that resolves them; shipping_carrier only opts the category in, by overriding calc_supports_test_mode to return True for its own records. See Integrations.

class ShippingIntegration(Model):
__inherit__ = "Integration"
# --- Talking to the carrier ---
async def carrier_request(self, method: str, url: str, **kwargs):
"""Call the carrier and return parsed JSON, raising UserError with a message
the user can act on when it refuses. Route every request through this."""
# --- Capability probes (safe base defaults) ---
async def supports_shipping(self) -> bool: return False
async def carrier_services(self) -> list: return [] # [{"code","name"}]
async def supports_address_validation(self) -> bool: return False
# --- Core hooks (base raises NotImplementedError) ---
async def get_rates(self, shipment: dict) -> list:
"""Live rate shopping →
[{"service", "service_name", "price", "currency", "transit_days"}]."""
async def create_label(self, shipment: dict, service: str) -> dict:
"""Buy a label → {"tracking_number", "label_data" (base64),
"label_format", "cost", "currency", "carrier_shipment_id", "tracking_url",
"documents": [{"name", "data" (base64), "format"}]} # e.g. a commercial invoice"""
async def track_shipment(self, tracking_number: str) -> dict:
"""→ {"status", "checkpoints": [...], "estimated_delivery"}."""
async def cancel_shipment(self, carrier_shipment_id: str) -> dict:
"""Void a label → {"success": bool, "message": str}."""
async def validate_address(self, address: dict) -> dict:
"""→ {"valid": bool, "normalized": {...}|None, "messages": [...]}."""

Hooks receive a provider-agnostic shipment dict — the backbone builds it from the order or the transfer, and the provider maps it to the carrier’s request shape:

{
"ship_from": <address dict>,
"ship_to": <address dict>,
"packages": [{"weight", "length", "width", "height", "value"}], # kg / cm
"total_value": float,
"currency": str,
"reference": str, # the delivery / order name
"customs": { # always present — the goods, as customs sees them
"required": bool, # the two countries are a customs border apart
"currency": str, # ISO code every unit_value is in
"invoice_number": str, # the commercial invoice reference (the order, else the delivery)
"invoice_date": str, # ISO date
"incoterm": str, # the order's Incoterm code, else "DAP"
"export_reason": str, # "Sale" | "Gift" | "Sample" | "Return" | "Other"
"lines": [{"product", "description", "hs_code", "origin_country",
"quantity", "unit_value", "weight"}], # weight: net kg for the line
},
}
# address dict: {name, company, street, street2, city, state, zip,
# country_code, phone, email} # country_code is ISO alpha-2 ("DE")

Weights are in kilograms and dimensions in centimetres; convert to the carrier’s units inside the provider. Country codes are ISO 3166 alpha-2. A capability a carrier doesn’t offer (e.g. Royal Mail has no address-validation endpoint) simply returns False from its probe and inherits the base NotImplementedError for the hook — the consuming code only calls hooks whose probe is True.

A shipment between two countries that are not both inside the EU customs union must be declared. The backbone builds customs for you: one line per product that ships (services are left out), declared at the price it was sold for (the order line’s subtotal, so a discount reaches customs) in the order’s currency. The HS code comes from the product’s HS Code field. The country of origin comes from the product’s Country of Origin field, which this module adds beside it.

Two methods on Integration answer the customs questions. Use them rather than writing your own:

  • crosses_customs_border(shipment) -> bool — must these goods be declared? Some carriers ask for customs data on every international shipment, including inside the EU. A provider for one of those checks the countries itself and still reads the data through the next method.
  • customs_declaration(shipment) -> dict — returns the customs block when it can be declared. Otherwise it raises a UserError naming each product that has no HS code or no country of origin. Call it before booking a label. A declaration with a gap is refused at the border, so it must never be sent.

Rate quotes don’t need HS codes. Map the declared value and the duties terms, and leave the strict check to the label. When the carrier renders a commercial invoice, return it in documents. The delivery files every document next to the label, because the invoice has to be printed and travel with the parcel.

A carrier quotes and bills in its own currency, so a GBP account rates a EUR order in GBP. Report the ISO code you were given in currency. The backbone converts the quote into the order’s currency, compares services in that one currency when it picks the cheapest, and books the label’s cost in the delivery company’s currency. A currency code the database doesn’t hold is refused, never guessed.

SurfaceBackbone entry pointHook called
Sales order pricingSaleOrder.apply_shipping_method (method delivery_type == "Live Carrier Rate")get_rates
Store checkoutSaleOrder.ecom_shipping_options (bridge ecommerce_shipping_carrier)get_rates
Address checkSaleOrder.action_validate_delivery_addressvalidate_address
FulfilmentTransfer.action_buy_shipping_labelcreate_label
FulfilmentTransfer.action_track_shipmenttrack_shipment
FulfilmentTransfer.action_void_labelcancel_shipment

A ShippingMethod opts into live rating by setting delivery_type = "Live Carrier Rate", an enabled shipping_integration, and an optional carrier_service (blank = the cheapest quoted service is chosen). The purchased label, tracking number, cost, and tracking URL are stored on the outbound Transfer (the delivery record).

carrier_service is a relation to a CarrierService record, not a typed code: enabling an integration calls your carrier_services() and syncs what it returns into records, so the user picks “FedEx Priority Overnight” from a list while your hooks still receive the carrier’s own code. Re-syncing (the Refresh Services button) renames in place and archives what you drop, so a method already pointing at a service never breaks.

<your addons path>/shipping_mycarrier/
├── __init__.py
├── manifest.yaml
├── models/
│ ├── __init__.py # from . import mycarrier_provider
│ └── mycarrier_provider.py
├── views/
│ └── mycarrier_provider_views.yaml
└── static/img/mycarrier_logo.png
name: MyCarrier
identifier: shipping_mycarrier
version: '1.0'
publisher: Your Company
requires_engine: 1
category: module_category_integrations
integration_category: Shipping
provides: [shipping]
description: Ship with MyCarrier — live rates, labels, tracking, address validation.
dependencies:
- shipping_carrier
icon: Truck
image: /static/img/mycarrier_logo.png # REQUIRED for integration modules
static_paths:
- img
integration_release: # REQUIRED for integration modules
status: Ready
verified_on: '2026-11-23'
api: MyCarrier REST API v2
docs: https://developer.mycarrier.com/api
inbound: [Polled]
tests:
happy_path: tests/test_mycarrier_against_mock.py::MyCarrierAgainstMockTest::test_a_label_round_trip
failure_modes:
- tests/test_mycarrier_against_mock.py::MyCarrierAgainstMockTest::test_wrong_credentials_are_named

integration_release is checked by check --only integrations; see Integrations.

from fullfinity.engine.base import *
MYCARRIER_BASE_TEST = "https://sandbox.mycarrier.com"
MYCARRIER_BASE_LIVE = "https://api.mycarrier.com"
class MyCarrierIntegration(Model):
__inherit__ = "Integration"
# Secrets use the Encrypted field (Fernet at rest); non-secret ids stay Char.
mycarrier_client_id = Char(max_length=128, company_scoped=True, description="Client ID")
mycarrier_client_secret = Encrypted(company_scoped=True, description="Client Secret")
async def _is_mycarrier(self) -> bool:
await self.fetch_related("module")
return self.module and self.module.identifier == "shipping_mycarrier"
# Private helpers carry the provider's name: every carrier's fragment composes into the
# one shared Integration class, so a plain `_base_url` would be one method for all of them.
async def _mycarrier_base_url(self) -> str:
# `api_base_url` is declared on Integration (every category shares it): it resolves
# Test vs Live, honours the Sandbox URL override in Test, and refuses a Live carrier
# in a copy of the database. A carrier serving both environments from one host passes
# the same URL twice.
return await self.api_base_url(MYCARRIER_BASE_TEST, MYCARRIER_BASE_LIVE)
async def _mycarrier_request(self, method, path, **kwargs):
# Always go through carrier_request: it turns a carrier's refusal into a message
# naming what to fix, instead of an unhandled traceback in the user's face.
return await self.carrier_request(method, f"{await self._mycarrier_base_url()}{path}", **kwargs)
async def enable_integration(self):
if await self._is_mycarrier() and not (self.mycarrier_client_id and self.mycarrier_client_secret):
raise UserError("Enter your MyCarrier client ID and secret before enabling.")
await super().enable_integration()
async def supports_shipping(self) -> bool:
return True if await self._is_mycarrier() else await super().supports_shipping()
async def get_rates(self, shipment: dict) -> list:
if not await self._is_mycarrier():
return await super().get_rates(shipment)
data = await self._mycarrier_request("POST", "/rates", json=self._mycarrier_rate_body(shipment))
return [self._mycarrier_to_rate(r) for r in data.get("rates", [])]
# ... create_label / track_shipment / cancel_shipment / validate_address, each
# guarded by `_is_mycarrier()` and deferring to super() otherwise.

Cache an OAuth token per company in the key/value store rather than re-authenticating each call — use env.valstore("shipping_mycarrier"), never the raw Valkey client:

async def _mycarrier_access_token(self) -> str:
store = env_ctx.get().valstore("shipping_mycarrier")
key = f"token:{env_ctx.get().company_id}:{self.integration_mode}"
token = await store.get(key)
if token:
return token
# ... POST the client-credentials grant ...
await store.set(key, token, ttl=max(expires_in - 60, 60))
return token

Step 4: Surface credentials on the Integration form

Section titled “Step 4: Surface credentials on the Integration form”

Extend integration_form_view, gating each field on the record’s own identifier Char (an M2O module__identifier never reaches the client, so it can’t be used in a visible clause):

- data_type: UiView
identifier: mycarrier_integration_form_extension
type: Form
model: Integration
inherited_view: integration_form_view
arch:
operations:
- action: add
target: {anchor: integration_description_col, field: description}
position: after
value:
type: field
name: mycarrier_client_id
properties:
visible: Q(identifier='shipping_mycarrier') & Q(state__neq='Not Installed')

Use widget: PasswordInput for secret fields.

Fullfinity’s bundled carriers are paid modules. Your own carrier module is not gated by Fullfinity’s licence.

  1. Install and enable the carrier with sandbox credentials (Mode = Test).
  2. Create a ShippingMethod with delivery_type = "Live Carrier Rate", pointing at the integration.
  3. Pick a Carrier Service on it, or leave it blank to take the cheapest rate quoted.
  4. On a sales order, Add Shipping with that method — the dialog quotes the carrier and shows the price and the service before you apply it.
  5. Confirm the order, open the outbound delivery, and Buy Shipping Label — tracking, label and cost are stored on the transfer; Track and Void Label exercise the remaining hooks.

Unit-test the request/response mapping with a mocked HTTP client (no live carrier needed) — assert the body your provider builds and that a documented carrier response maps to the hook’s return dict.

When you can’t get into the carrier’s sandbox

Section titled “When you can’t get into the carrier’s sandbox”

Most carriers gate sandbox access behind being their customer, which leaves you unable to call anything at all while building a provider. Set Sandbox URL on the integration (the field appears on the form in Test mode) and every request goes there instead. Point it at a small local HTTP mock of the carrier’s API (for example http://localhost:8787) and drive the app normally — quote, label, track, void. Give the mock a way to return the carrier’s own error responses and to delay a reply, so you can exercise the failure paths too. The bundled carriers are developed this way; their mock is part of Fullfinity’s own test tooling, not the distribution.

A live integration can never be redirected: saving a Sandbox URL while Mode is Live is refused, and api_base_url returns the live host regardless of what is stored.

Build your mock’s responses from the carrier’s published schema, not from what your provider happens to read. A mock that mirrors the provider’s assumptions confirms the provider agrees with itself — it cannot catch a field you invented. (Building the bundled carriers’ mock from the carriers’ own specs is how three field-name bugs surfaced.)