Skip to content

Author a driver

Drivers replace policy or infrastructure without replacing commerce orchestration. A driver implements one narrow port and is resolved once by CommerceManager during provider boot.

Drivers replace policy or infrastructure without replacing commerce orchestration. A driver implements one narrow port and is resolved once by CommerceManager during provider boot.

Choose the correct port

Port Responsibility
PriceResolver Select one unit price for a variant, quantity, channel, currency, and customer context
PaymentProvider Create, confirm, capture, refund, void, verify, and normalize provider events
ShippingCalculator Quote one shipping method for a cart snapshot
ShippingEligibility Filter configured shipping methods for a cart snapshot
TaxCalculator Return line-level tax results without writing adjustments
StockAllocationStrategy Choose inventory levels; InventoryService performs guarded writes
CartTokenStrategy Read and issue anonymous cart tokens through HttpContext
JobDispatcher Dispatch and schedule idempotent job names
DynamicShippingQuoteProvider Return expiring multi-service shipping quote drafts
FulfillmentProvider Prepare provider-backed fulfillment
SearchDriver Search, index, and delete catalog records
ProductImageStorage Persist and remove uploaded images
TaxAddressResolver Choose the tax address
OrderNumberGenerator Allocate concurrency-safe order numbers

If your implementation needs to write cart, order, inventory, or payment rows directly, it probably belongs in a service or workflow extension instead.

Implement the interface

A shipping calculator is the smallest complete example:

import { Money } from "@adocommercekit/core";
import type { ShippingCalculator } from "@adocommercekit/core/types";

export class WeightBandShipping implements ShippingCalculator {
  readonly code = "weight-band";

  async calculate({
    cart,
    method,
  }: Parameters<ShippingCalculator["calculate"]>[0]) {
    const centsPerItem = BigInt(method.calculatorConfig.centsPerItem as number);
    const itemCount = cart.lines.reduce(
      (total, line) => total + line.quantity,
      0,
    );
    return Money.of(centsPerItem * BigInt(itemCount), cart.currency);
  }
}

Keep the driver deterministic for the same input. Do not read global request state. All request-specific values belong in the input context.

Export a factory

Commerce config stores factories so construction may use the Adonis container.

import type { DriverFactory, ShippingCalculator } from "@adocommercekit/core";

export function weightBandShipping(): DriverFactory<ShippingCalculator> {
  return async () => new WeightBandShipping();
}

Register it under a stable code:

// config/commerce.ts
import { weightBandShipping } from "#commerce/drivers/weight_band_shipping";

export default defineConfig({
  // ...
  shipping: {
    calculators: {
      "weight-band": weightBandShipping(),
    },
  },
});

A shipping-method row chooses the driver using calculator: 'weight-band' and stores serializable options in calculatorConfig.

Generate a host adapter

node ace commerce:make:driver <kind> <name> supports all 14 kinds: payment, shipping, tax, inventory, fulfillment, shipping-quote, cart-token, pricing, search, image-storage, shipping-eligibility, tax-address, order-number, and job-dispatcher.

Payment, shipping, tax, and inventory templates delegate to built-in behavior; the payment template is manual payment, not an external gateway. The other typed factories require a real working delegate, passed explicitly as factory(existingDriver). Keep delegation until your implementation satisfies the entire port.

For job-dispatcher, use the generated factory’s dispatcher with (await app.container.make(JobDispatcherService)).use(factory(existingDriver)()) in a host provider’s boot() after commerce has booted. The string config still accepts only inline or queue; do not register an adapter during module evaluation or before commerce initializes.

Lifecycle rules

  • Factories resolve once and may use the application container.
  • Drivers may expose shutdown; CommerceManager.shutdown() calls lifecycle hooks during app shutdown.
  • Throw Adocommerce Kit exceptions for stable API errors. Preserve provider decline codes in exception details.
  • Never log payment tokens, provider secrets, encrypted client secrets, raw address PII, or complete webhook payloads.
  • Webhook verification must happen before normalized payloads are trusted.
  • Driver retry behavior must not undermine service idempotency keys.

Payment operation contract

Core claims capture/refund operations in a durable journal before provider I/O and reserves their amounts against the remaining authorization or refundable balance. Drivers must forward the supplied idempotency key; a transport exception leaves the operation uncertain rather than proving that no funds moved.

capture() receives providerIntentId, amount, idempotencyKey, and optional final. Core sets final: false for a partial capture. Return providerChargeId plus a distinct providerCaptureId when multiple captures share a charge; core deduplicates by capture ID, falling back to charge ID. A provider that cannot multicapture may ignore final, but must not claim a capability it cannot supply.

refund() receives the charge ID, amount, optional reason, and idempotency key. Return providerRefundId and an explicit state: 'pending' | 'succeeded' | 'failed' for asynchronous providers; omitted state defaults to succeeded. Normalize refund events with provider refund/charge identities and the original idempotency key where available. Do not apply an arbitrary refund to a charge.

Implement optional retrieveRefund({ providerRefundId?, providerChargeId?, idempotencyKey? }) when the provider supports exact reconciliation. Return a known refund’s state and optional amount, or null when it cannot be located or confirmed. PaymentService.reconcileOperations() uses this method for pending/uncertain refunds; it does not create a replacement refund.

Shipping quote and fulfillment contract

DynamicShippingQuoteProvider.quote() receives the cart, full parcels, and optional COD/insurance amounts. Return drafts with service, name, Money price, expiry, and optional metadata; core signs the final selection token. Include every rate-affecting input in provider cache identity.

FulfillmentProvider.prepare() receives shipment ID, order, parcels, optional service/COD/insurance, and an idempotency key. Return provider shipment ID and waybill, with optional tracking number, carrier, and raw response. Optional status() returns a supported fulfillment status, timestamp, and raw response. Keep provider creation idempotent or durably journal uncertain acceptance; a timeout is not proof that a shipment was never created.

Test the contract

Test the interface, not private helpers:

  1. The same input returns the same Money and currency.
  2. Unsupported config fails with a specific error.
  3. Boundary values—zero items, maximum quantity, missing address—are explicit.
  4. Provider methods forward idempotency keys.
  5. Webhook verification rejects one-byte payload and signature changes.
  6. shutdown releases open clients or timers.

For payment drivers, run both recorded fixture tests and a documented test-mode protocol. A fixture proves deterministic normalization; a live protocol catches provider drift.

Navigation

Type to search…

↑↓ navigate↵ selectEsc close