Skip to content

Live delivery rates with a callback

A delivery rate callback prices delivery methods from your server while the buyer checks out. Use one when prices come from a carrier API, a rate-shopping service, or logic that a rate table can't express. When a buyer quotes delivery, Flint sends your endpoint a signed request describing what is shipping and where, and your endpoint returns a price and delivery window for each method.

How it works#

Pricing a callback method at checkoutResponse
BuyerFlintYour rate serverenters a delivery addresssigned POST: currency, destination, and one candidate per methodone outcome per candidate: price, expiry, delivery windowchecks each outcome against the method's limitsdelivery options with prices
  1. Buyer sends enters a delivery address to Flint
  2. Flint sends signed POST: currency, destination, and one candidate per method to Your rate server
  3. Your rate server returns one outcome per candidate: price, expiry, delivery window to Flint
  4. Flint sends checks each outcome against the method's limits to Flint
  5. Flint returns delivery options with prices to Buyer
  • Quotes call your server. Creating a delivery quote calls it. Reading a checkout never does. A delivery preview calls it only when preview_enabled is true on both the callback configuration and the method's pricing.callback; otherwise the preview doesn't call your server.
  • One request prices a group of methods. Flint sends one request for each group of items delivered together, covering up to 25 methods in that group that use the callback. Each method is a candidate in the request.
  • Each method is judged on its own. A bad price for one method drops that method and leaves the others offered.

Warning: A callback has no fallback price

If your endpoint times out, fails, or returns an invalid result, Flint doesn't offer the affected methods. If buyers must always have a choice, offer a fixed-price or rate-table method alongside the callback method.

Before you begin#

  • A test API key with commerce.delivery.write. To offer the method at checkout and quote it in steps 4 and 5, the key also needs settings.write and checkouts.checkout_sessions.write.
  • At least one active Location to ship from, and a unit_weight on each variant if your rates depend on weight.
  • A server that accepts HTTPS requests at a public address. Flint rejects localhost, private IP addresses, and internal hostnames. For local development, run a tunnel such as cloudflared tunnel --url http://localhost:3000 and use the https:// URL it prints.

1. Create the callback#

Register your endpoint's URL:

cURL
curl -X POST https://api.withflintpay.com/v1/delivery-rate-callbacks \
  -H "Authorization: Bearer YOUR_API_KEY" \
  -H "Content-Type: application/json" \
  -H "Idempotency-Key: rate-callback-carrier-1" \
  -d '{
    "name": "Carrier rates",
    "configuration": {
      "url": "https://rates.example.com/flint/delivery-rates",
      "request_timeout_seconds": 2
    }
  }'
Response
{
  "data": {
    "delivery_rate_callback_id": "dcb_01K4CARRIER",
    "current_delivery_rate_callback_revision_id": "dcbr_01K4CARRIER",
    "name": "Carrier rates",
    "status": "inactive",
    "version": 1,
    "configuration": {
      "url": "https://rates.example.com/flint/delivery-rates",
      "request_timeout_seconds": 2,
      "preview_enabled": false,
      "maximum_request_bytes": 262144,
      "maximum_response_bytes": 262144,
      "redirect_policy": "reject"
    },
    "signing_methods": ["jwt"],
    "circuit_state": "closed",
    "circuit_failure_count": 0,
    "created_at": "2026-09-22T18:00:00Z",
    "updated_at": "2026-09-22T18:00:00Z"
  },
  "request_id": "req_01K4EXAMPLE"
}

New callbacks default to signing_methods: ["jwt"]. Save delivery_rate_callback_id as the expected JWT audience. A JWT-only callback has no shared secret issued, stored, or returned. Existing callbacks keep ["hmac"] until you change them. To opt into shared-secret verification, send "signing_methods": ["hmac"] or ["jwt", "hmac"] when creating the callback. That create response adds secret and its delivery_rate_callback_signing_key_id, shown once; no later read returns them. See Change signing methods.

The URL must use HTTPS, contain no username or password, and resolve to a public IP address. Flint never follows redirects. Creating or updating a callback with a malformed URL returns 400 INVALID_REQUEST, and so does a private or internal host, both with detail code INVALID_VALUE and param set to configuration.url. request_timeout_seconds accepts 0.1 to 10 and defaults to 2. Both byte limits accept up to 1,048,576. A new callback is inactive unless you send "status": "active" on create; an active method can use only an active callback. Connection checks and test deliveries work on any inactive callback, including one you deactivate later, but return 409 ACTION_NOT_ALLOWED with reason archived for an archived callback or terminal_status for a revoked one.

2. Build the endpoint#

For each request, your endpoint:

  1. Verifies the signature over the raw request body, before parsing JSON.
  2. Returns its earlier answer when Flint retries the same delivery_rate_evaluation_id.
  3. Prices each candidate from the destination, weight, and item values in the request.
  4. Returns one outcome per candidate, with every time computed from evaluated_at.

The three JavaScript snippets form one Node server file. Install its dependencies with npm install express jose. It listens on port 3000, verifies JWTs with Flint's public keys, and needs no Flint SDK or shared secret.

Receive the request#

The route reads the raw body, verifies it, answers connection checks, and prices everything else. A retry carries the same delivery_rate_evaluation_id and body, so the handler stores each answer by that ID and returns it again instead of calling your carrier twice.

JavaScript
import crypto from "node:crypto";
import express from "express";
import { createLocalJWKSet, jwtVerify } from "jose";

// Answers by evaluation ID, because a retry reuses it.
// Use a shared store with a 15-minute expiry in production.
const answers = new Map();

const app = express();

app.post(
  "/flint/delivery-rates",
  express.raw({ type: "*/*", limit: "256kb" }),
  async (req, res) => {
    let evaluation;
    try {
      evaluation = await verifyCallback(req.body, req.headers);
    } catch {
      return res.status(401).end();
    }

    if (evaluation.type === "connection_check") {
      return res.json({});
    }

    const id = evaluation.delivery_rate_evaluation_id;
    if (!answers.has(id)) {
      answers.set(id, priceEvaluation(evaluation));
    }
    res.json(await answers.get(id));
  },
);

app.listen(3000);

Verify the signature#

Verify the bearer JWT against Flint's public JWKS, then check that it binds the exact bytes you received. Complete every check before pricing a request, even if a gateway already verifies JWT signatures. Use your configured delivery_rate_callback_id as the audience, never an ID supplied by the incoming request.

HeaderValue
AuthorizationBearer <token> when jwt is enabled.
webhook-idThe request's delivery_rate_evaluation_id, unchanged on retry. Each connection check gets a new one.
webhook-timestampUnix time in seconds when Flint signed the request; equal to the JWT's iat.

The JWT has alg: ES256, typ: flint-webhook+jwt, and a kid naming a key in Flint's JWKS. Its claims are:

ClaimValue
isshttps://api.withflintpay.com for both live and test-mode callbacks.
audYour delivery_rate_callback_id (dcb_...), stable when the URL or revision changes.
iatThe webhook-timestamp value.
expiat + 300, a five-minute lifetime.
jtiAn opaque ID unique to each HTTP request. Retries get a new ID. Deduplicate on delivery_rate_evaluation_id, which stays the same.
body_sha256SHA-256 of the exact request bytes, encoded as base64url without padding.

Set callbackIds to your registered callback IDs. Keep the issuer and JWKS URL in your own configuration; never fetch a URL supplied in a token. Cache keys using the JWKS response's Cache-Control, for at most 24 hours. On an unknown kid, refresh at most once per minute, and never pin a single key ID. Allow at most 60 seconds of clock leeway.

JavaScript
const issuer = "https://api.withflintpay.com";
const jwksUrl = `${issuer}/.well-known/jwks.json`;
const callbackIds = ["dcb_01K4CARRIER"];

// One cache per process, shared by all requests and callback IDs.
let keys;
let expiresAt = 0;
let lastFetchAt = -Infinity;
let fetching;

async function refreshKeys() {
  if (!fetching) {
    lastFetchAt = Date.now();
    fetching = (async () => {
      const response = await fetch(jwksUrl, {
        redirect: "error",
        signal: AbortSignal.timeout(3000),
      });
      if (!response.ok) throw new Error("Cannot fetch Flint JWKS");
      const cacheControl = response.headers.get("cache-control") ?? "";
      const maxAge = /(?:^|,)\s*max-age=(\d+)/i.exec(cacheControl);
      const ageHeader = Number(response.headers.get("age") ?? 0);
      const age = Number.isFinite(ageHeader) ? Math.max(0, ageHeader) : 0;
      const seconds = /(?:^|,)\s*(?:no-cache|no-store)(?:,|$)/i.test(cacheControl)
        ? 0
        : Math.max(0, Math.min(Number(maxAge?.[1] ?? 0), 86400) - age);
      keys = createLocalJWKSet(await response.json());
      expiresAt = Date.now() + seconds * 1000;
    })().finally(() => { fetching = undefined; });
  }
  await fetching;
}

async function resolveKey(header, token) {
  if (header.alg !== "ES256" || header.typ !== "flint-webhook+jwt" ||
      typeof header.kid !== "string" || !header.kid) {
    throw new Error("Invalid callback JWT header");
  }
  if (!keys || Date.now() >= expiresAt) await refreshKeys();
  try {
    return await keys(header, token);
  } catch (error) {
    // Unknown IDs cannot force more than one refresh per minute.
    if (error.code !== "ERR_JWKS_NO_MATCHING_KEY" ||
        Date.now() - lastFetchAt < 60000) throw error;
    await refreshKeys();
    return keys(header, token);
  }
}

async function verifyCallback(rawBody, headers) {
  const authorization = headers.authorization;
  if (typeof authorization !== "string" ||
      !/^Bearer [A-Za-z0-9_-]+\.[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+$/.test(authorization)) {
    throw new Error("Missing callback bearer token");
  }
  const { payload } = await jwtVerify(authorization.slice(7), resolveKey, {
    algorithms: ["ES256"],
    typ: "flint-webhook+jwt",
    issuer,
    audience: callbackIds,
    requiredClaims: ["iss", "aud", "iat", "exp", "jti", "body_sha256"],
    clockTolerance: 60,
  });
  const now = Math.floor(Date.now() / 1000);
  if (!Number.isSafeInteger(payload.iat) || !Number.isSafeInteger(payload.exp) ||
      payload.iat > now + 60 || payload.exp <= payload.iat ||
      payload.exp - payload.iat > 300 ||
      typeof payload.aud !== "string" || !callbackIds.includes(payload.aud) ||
      typeof payload.jti !== "string" || !payload.jti ||
      typeof headers["webhook-id"] !== "string" || !headers["webhook-id"] ||
      payload.jti === headers["webhook-id"] ||
      headers["webhook-timestamp"] !== String(payload.iat)) {
    throw new Error("Invalid callback claims");
  }
  if (typeof payload.body_sha256 !== "string" ||
      !/^[A-Za-z0-9_-]{43}$/.test(payload.body_sha256)) {
    throw new Error("Invalid callback body hash");
  }
  const actual = Buffer.from(payload.body_sha256, "ascii");
  const expected = Buffer.from(crypto.createHash("sha256").update(rawBody).digest("base64url"), "ascii");
  if (!crypto.timingSafeEqual(actual, expected)) throw new Error("Callback body mismatch");

  // Parse only after the signature, claims, and body hash have passed.
  const evaluation = JSON.parse(rawBody.toString("utf8"));
  if (evaluation.type !== "connection_check" &&
      evaluation.delivery_rate_evaluation_id !== headers["webhook-id"]) {
    throw new Error("Invalid evaluation ID");
  }
  return evaluation;
}

For Python or Go receivers, pass a JWKS document from your own shared cache to these verifiers. Fetch it only from the configured Flint JWKS URL and apply the same cache lifetime and unknown-kid refresh limits as the Node example. Install PyJWT[crypto] for Python or github.com/go-jose/go-jose/v4 for Go. Catch verification errors and return 401 before pricing.

Python
import base64
import hashlib
import hmac
import json
import time

import jwt

ISSUER = "https://api.withflintpay.com"
CALLBACK_ID = "dcb_01K4CARRIER"


def verify_callback(raw_body: bytes, headers, jwks: dict) -> dict:
    authorization = headers.get("Authorization", "")
    if not authorization.startswith("Bearer "):
        raise ValueError("Missing callback bearer token")
    token = authorization[7:]
    header = jwt.get_unverified_header(token)
    if (header.get("alg") != "ES256" or header.get("typ") != "flint-webhook+jwt"
            or not isinstance(header.get("kid"), str) or not header["kid"]):
        raise ValueError("Invalid callback JWT header")
    keys = [key for key in jwt.PyJWKSet.from_dict(jwks).keys if key.key_id == header["kid"]]
    if len(keys) != 1 or keys[0].algorithm_name != "ES256":
        # Ask your cache to refresh at most once per minute, then retry verification once.
        raise ValueError("Unknown callback signing key")
    claims = jwt.decode(
        token, keys[0].key, algorithms=["ES256"], issuer=ISSUER,
        audience=CALLBACK_ID, leeway=60,
        options={"require": ["iss", "aud", "iat", "exp", "jti", "body_sha256"]},
    )
    if (type(claims["iat"]) is not int or type(claims["exp"]) is not int
            or claims["iat"] > time.time() + 60
            or not 0 < claims["exp"] - claims["iat"] <= 300
            or claims["aud"] != CALLBACK_ID
            or not isinstance(claims["jti"], str) or not claims["jti"]
            or not headers.get("webhook-id")
            or claims["jti"] == headers["webhook-id"]
            or headers.get("webhook-timestamp") != str(claims["iat"])):
        raise ValueError("Invalid callback claims")
    expected = base64.urlsafe_b64encode(hashlib.sha256(raw_body).digest()).rstrip(b"=")
    body_hash = claims["body_sha256"]
    if (not isinstance(body_hash, str) or len(body_hash) != 43 or not body_hash.isascii()
            or not hmac.compare_digest(body_hash.encode("ascii"), expected)):
        raise ValueError("Callback body mismatch")
    evaluation = json.loads(raw_body)
    if (evaluation.get("type") != "connection_check"
            and evaluation.get("delivery_rate_evaluation_id") != headers["webhook-id"]):
        raise ValueError("Invalid evaluation ID")
    return evaluation

The body says what kind of request it is: a connection check is {"type":"connection_check"}, and a test delivery has "test": true.

The handler returns 401 when verification fails and doesn't reveal which check failed. Flint treats a 401 like any other non-2xx status: the request failed, and Flint retries it once.

Warning:

Verification needs the exact bytes Flint sent. Body-parsing middleware such as express.json() reparses the body before your code runs, and every signature then fails. Read the raw body on this route only.

Price each candidate#

Return one result per candidate, echoing its delivery_method_revision_id so Flint can match the result to the method. To price several methods through one URL, choose the service from delivery_method_id, which stays the same when you edit the method. The example maps two method IDs to a standard and an express service.

JavaScript
const MINUTE = 60 * 1000;
const DAY = 24 * 60 * MINUTE;

// Replace these IDs with the delivery_method_id values from step 4.
const services = new Map([
  ["dmet_01K4STANDARD", "standard"],
  ["dmet_01K4EXPRESS", "express"],
]);

async function priceEvaluation(evaluation) {
  const method_results = await Promise.all(
    evaluation.candidates.map(async (candidate) => ({
      delivery_method_revision_id: candidate.delivery_method_revision_id,
      outcome: await priceCandidate(evaluation, candidate),
    })),
  );
  return {
    delivery_rate_evaluation_id: evaluation.delivery_rate_evaluation_id,
    method_results,
  };
}

async function priceCandidate(evaluation, candidate) {
  // Test deliveries use random method IDs, so price them as standard.
  const service = evaluation.test ? "standard" : services.get(candidate.delivery_method_id);
  if (!service) {
    return { type: "unavailable", unavailable_reason: "pricing_unavailable" };
  }

  // total_weight_grams is absent when any item's weight is unknown. Zero is a real weight.
  const weightGrams = candidate.pricing.total_weight_grams;
  if (weightGrams === undefined) {
    return { type: "unavailable", unavailable_reason: "pricing_unavailable" };
  }

  let rate;
  try {
    rate = await quoteCarrier({
      service,
      currency: evaluation.currency,
      destination: evaluation.destination,
      weightGrams,
    });
  } catch {
    return { type: "cannot_calculate", failure_category: "dependency_failure", retryable: true };
  }
  if (!rate) {
    return { type: "unavailable", unavailable_reason: "destination_not_served" };
  }

  // Compute every time from evaluated_at, not from your server's clock.
  const evaluatedAt = Date.parse(evaluation.evaluated_at);
  const at = (offset) => new Date(evaluatedAt + offset).toISOString();
  // Offer the price for 10 minutes, or until the quote expires if that's sooner.
  const quoteExpiresAt = Date.parse(evaluation.delivery_quote_expires_at);
  return {
    type: "available",
    amount_money: { amount: rate.amount, currency: evaluation.currency },
    expires_at: new Date(Math.min(evaluatedAt + 10 * MINUTE, quoteExpiresAt)).toISOString(),
    selection_guarantee_expires_at: at(30 * MINUTE),
    window_start_at: at(rate.minDays * DAY),
    window_end_at: at((rate.maxDays + 1) * DAY),
    merchant_reference: rate.reference,
  };
}

// Replace with your carrier or rate-shopping API.
async function quoteCarrier({ service, currency, destination, weightGrams }) {
  if (currency !== "USD" || destination?.country !== "US") {
    return null;
  }
  const kilograms = Math.max(1, Math.ceil(weightGrams / 1000));
  return service === "express"
    ? { amount: 1800 + 400 * kilograms, minDays: 1, maxDays: 2, reference: `express-${kilograms}kg` }
    : { amount: 600 + 150 * kilograms, minDays: 3, maxDays: 5, reference: `standard-${kilograms}kg` };
}

Replace quoteCarrier with your carrier or rate-shopping call. A carrier failure returns cannot_calculate rather than an HTTP error, so one carrier outage drops only the affected methods and doesn't count against your endpoint's circuit breaker.

The example offers each price for 10 minutes, or until delivery_quote_expires_at if that comes first, and hold the buyer's selection for 30 minutes (selection_guarantee_expires_at). A quote lasts up to 15 minutes, or just under 5 minutes for a cart with tracked inventory, and Flint rejects an expires_at later than the quote's expiry. Response body lists every rule an outcome must meet.

3. Test the endpoint#

Start your server and, while developing, the tunnel. Then ask Flint to send a signed connection check:

cURL
curl -X POST https://api.withflintpay.com/v1/delivery-rate-callbacks/dcb_01K4CARRIER/check-connection \
  -H "Authorization: Bearer YOUR_API_KEY" \
  -H "Idempotency-Key: check-carrier-1"

Flint posts {"type":"connection_check"}. Any 2xx response passes, unless it sets a Content-Type other than application/json or its body is larger than maximum_response_bytes:

Response
{
  "data": {
    "delivery_rate_callback_id": "dcb_01K4CARRIER",
    "delivery_rate_callback_revision_id": "dcbr_01K4CARRIER",
    "delivery_rate_callback_signing_key_id": "",
    "status": "succeeded",
    "http_status_code": 200,
    "checked_at": "2026-09-22T18:02:00Z",
    "latency_milliseconds": 84
  },
  "request_id": "req_01K4EXAMPLE"
}

Then send a test delivery, a sample rate request that your endpoint prices like a real one:

cURL
curl -X POST https://api.withflintpay.com/v1/delivery-rate-callbacks/dcb_01K4CARRIER/test-deliveries \
  -H "Authorization: Bearer YOUR_API_KEY" \
  -H "Idempotency-Key: test-carrier-1"

The result has the same shape as a connection check, with tested_at in place of checked_at. The sample request has "test": true, USD, a destination of US, NY, 10001, and one candidate whose items leave from two Locations. Its method, Location, and line item IDs are random, so your handler must price a method it has never seen. The example prices test deliveries as standard service.

Note: Each check runs once per Idempotency-Key

Repeating a key returns the stored result without contacting your server. After you fix a failure, send a new key, such as check-carrier-2.

A test delivery checks the rules that apply to every method: the response's format, an expires_at later than evaluated_at and at most 15 minutes after it, and a service_level valid for a shipment or local delivery. It sends a delivery_quote_expires_at up to 15 minutes after evaluated_at. It doesn't know which method will use the response, so it accepts any USD amount and doesn't apply minimum_option_lifetime_seconds. A response can pass the test and still fail on a real quote. Step 5 checks against your method.

When a check fails, status is failed and failure_category says why. Both endpoints use the same categories:

failure_categoryWhat to check
dns_error, tls_error, connection_errorThe URL is public, resolves, and serves a valid HTTPS certificate.
blocked_targetThe URL resolves to a private or internal address. Use a public host or tunnel.
timeoutYour endpoint answered within request_timeout_seconds.
authentication_or_http_errorYour endpoint returned a non-2xx status. For a 401, check JWT verification against Flint's JWKS, issuer, your dcb_ audience, expiry, and raw-body hash. For HMAC, check the shared secret and verify the body before parsing it.
invalid_responseYour endpoint returned a 2xx with a Content-Type other than application/json or a body larger than maximum_response_bytes. For a test delivery, also a response that broke a rule in Response body.
request_errorFlint couldn't complete the request for another reason. Check the URL and your server logs.

4. Activate the callback and attach a method#

If you created the callback with "status": "active", skip to creating the method. Otherwise activate it with a PATCH that sends only status:

cURL
curl -X PATCH https://api.withflintpay.com/v1/delivery-rate-callbacks/dcb_01K4CARRIER \
  -H "Authorization: Bearer YOUR_API_KEY" \
  -H "Content-Type: application/json" \
  -H "Idempotency-Key: activate-rate-callback-1" \
  -d '{ "status": "active" }'

Then create a method with callback pricing:

cURL
curl -X POST https://api.withflintpay.com/v1/delivery-methods \
  -H "Authorization: Bearer YOUR_API_KEY" \
  -H "Content-Type: application/json" \
  -H "Idempotency-Key: method-carrier-standard-1" \
  -d '{
    "name": "Standard shipping",
    "type": "shipment",
    "status": "active",
    "configuration": {
      "origin": { "type": "fixed_location", "location_id": "loc_01K4WHSE" },
      "pricing": {
        "type": "callback",
        "callback": {
          "delivery_rate_callback_id": "dcb_01K4CARRIER",
          "minimum_fee_currency_options": { "USD": { "amount": 0, "currency": "USD" } },
          "maximum_fee_currency_options": { "USD": { "amount": 10000, "currency": "USD" } }
        }
      },
      "minimum_option_lifetime_seconds": 120,
      "estimate": {
        "type": "transit_time",
        "transit_time": {
          "handling_days": { "minimum": 1, "maximum": 1 },
          "transit_days": { "minimum": 2, "maximum": 5 }
        }
      },
      "quote_input_fields": [
        "destination_address.state",
        "destination_address.postal_code",
        "destination_address.country"
      ],
      "public_details": { "service_level": "standard" }
    }
  }'

Copy delivery_method_id from the response into your server's method map. To add express, create a second method with the same callback ID and map its ID to express.

minimum_fee_currency_options, maximum_fee_currency_optionsobjectRequired

The lowest and highest price you accept, keyed by currency. Flint accepts only USD today, so send one USD entry. Flint doesn't clamp: an amount outside these limits drops the method, so a pricing bug can't charge buyers $10,000. The example allows free shipping with a minimum of 0.

minimum_option_lifetime_secondsintegerRequired

How long a returned price must remain usable, from 0 to 899. Flint drops an option whose expires_at isn't later than evaluated_at plus this value, so keep it below the lifetime your server returns. When delivery_quote_expires_at is too soon to meet it, Flint doesn't call your endpoint and reports option_lifetime_too_short. A quote for a cart with tracked inventory lasts just under 5 minutes, so a value of 300 or more drops the method for those carts. The example requires 120 seconds.

estimateobjectRequired

The delivery estimate. Callback pricing doesn't accept none; your windows replace the estimate for each priced option.

quote_input_fieldsarray

The buyer fields Flint sends you. List address fields under destination_address or buyer_location.address, such as buyer_location.address.postal_code, add buyer_location.coordinate for latitude and longitude, or send destination_address for the whole address. When a listed field is missing, the quote asks the buyer for it in input_requirements instead of calling your server.

Offer the method at checkout with settings.checkout.default_delivery_method_ids or a checkout's delivery_method_ids, as in Delivery options. A checkout keeps the callback configuration it pinned when the method was assigned to it, so later configuration changes apply to new checkouts.

Delivery previews don't call your server unless you set preview_enabled: true on both the callback's configuration and the method's pricing.callback. Otherwise previews report the method as needing a checkout. Flint limits how many preview calls to your callbacks run at once. A preview over the limit reports the method as callback_unavailable, and you can retry it.

5. Quote a checkout#

Create a checkout that offers the method, then create a quote for it with your API key. A quote created with your API key reports how each method fared, including why one was dropped:

cURL
curl -X POST https://api.withflintpay.com/v1/delivery-quotes \
  -H "Authorization: Bearer YOUR_API_KEY" \
  -H "Content-Type: application/json" \
  -H "Idempotency-Key: quote-carrier-1" \
  -d '{
    "checkout_session_id": "cs_01K4EXAMPLE",
    "expected_delivery_selection_id": null,
    "destination_address": {
      "state": "NY",
      "postal_code": "11249",
      "country": "US"
    }
  }'

Each choice group lists the priced options and, keyed by delivery_method_id, every method's candidate_outcomes:

Response
{
  "data": {
    "delivery_quote_id": "dqt_01K4EXAMPLE",
    "choice_groups": [
      {
        "delivery_choice_group_id": "dcgrp_01K4EXAMPLE",
        "availability_status": "ready",
        "options": [
          {
            "delivery_option_id": "dopt_01K4STANDARD",
            "delivery_method_id": "dmet_01K4STANDARD",
            "name": "Standard shipping",
            "amount_money": { "amount": 1050, "currency": "USD" }
          }
        ],
        "candidate_outcomes": {
          "dmet_01K4STANDARD": {
            "type": "available",
            "option": {
              "delivery_option_id": "dopt_01K4STANDARD",
              "amount_money": { "amount": 1050, "currency": "USD" }
            }
          },
          "dmet_01K4EXPRESS": {
            "type": "cannot_calculate",
            "failure_category": "callback_result_invalid",
            "retryable": false
          }
        }
      }
    ],
    "expires_at": "2026-09-22T18:19:12Z"
  },
  "request_id": "req_01K4EXAMPLE"
}

When a callback method is missing from options, its failure_category says why:

failure_categoryMeaning
callback_result_invalidYour endpoint answered, but Flint couldn't use the result: the method's result broke a rule in Response body, such as an amount outside the method's limits, or Flint rejected the whole response. Not retryable until you fix the response.
callback_transport_failureFlint got no response, or a non-2xx status, after its retry. Retryable.
option_lifetime_too_shortThe quote expires too soon for the method's minimum_option_lifetime_seconds, so Flint didn't call your endpoint.
callback_unavailableFlint couldn't call your endpoint because of a problem on its side. Retryable.
callback_circuit_openThe circuit breaker is open, so Flint didn't call your endpoint.

A method that your endpoint returned as unavailable or cannot_calculate reports your own unavailable_reason or failure_category. Buyers see only the options. Delivery quotes documents the full response.

6. Match the order to your rate#

merchant_reference carries your own ID for a rate, such as a carrier rate or shipment ID you need when you buy the label. When the buyer selects the option, Flint stores the reference with the selection. It appears in:

  • Selection reads made with your API key, at GET /v1/delivery-selections/{delivery_selection_id} and GET /v1/delivery-selections, as choices[].merchant_reference.
  • The order fulfillment's external_reference_id.

Buyers never see it.

Request body#

Flint sends only what a rate calculation needs. It never sends customer names, email addresses, eligibility facts, or metadata.

The OpenAPI document publishes this body as DeliveryRateEvaluationRequest, in the deliveryRateEvaluation callback of createDeliveryRateCallback under components.callbacks. The JWT in Authorization is the DeliveryRateCallbackBearer security scheme on the callback operations, and only the HMAC headers are parameters. Generate your request and response types from it. A connection check sends DeliveryRateCallbackConnectionCheckRequest to the same URL, in the deliveryRateCallbackConnectionCheck callback.

JSON
{
  "delivery_rate_evaluation_id": "dreval_4c1e9a7b2f3d8e6a0b5c7d9e",
  "delivery_rate_callback_signing_key_id": "",
  "checkout_session_id": "cs_01K4EXAMPLE",
  "order_id": "ord_01K4EXAMPLE",
  "quote_creation_identity": "5e0b...",
  "delivery_feasibility_plan_fingerprint": "7b1d...",
  "delivery_choice_group_id": "dcgrp_01K4EXAMPLE",
  "choice_group_fingerprint": "a93f...",
  "delivery_rate_callback_revision_id": "dcbr_01K4CARRIER",
  "currency": "USD",
  "destination": {
    "state": "NY",
    "postal_code": "11249",
    "country": "US"
  },
  "candidates": [
    {
      "delivery_method_id": "dmet_01K4STANDARD",
      "delivery_method_revision_id": "dmetr_01K4STANDARD",
      "execution_legs": [
        {
          "delivery_execution_leg_id": "dleg_01K4EXAMPLE",
          "fingerprint": "c2e8...",
          "origin_location_id": "loc_01K4WHSE",
          "origin_geography_version": 3,
          "allocations": [
            {
              "demand_key": "line:li_01K4EXAMPLE",
              "order_line_item_id": "li_01K4EXAMPLE",
              "quantity": 2,
              "merchandise_value_money": { "amount": 5000, "currency": "USD" },
              "allowed_types": ["shipment"]
            }
          ]
        }
      ],
      "pricing": {
        "currency": "USD",
        "bases": {
          "choice_group.fulfillment_quantity": 2,
          "choice_group.merchandise_subtotal_before_discounts": 5000,
          "choice_group.merchandise_subtotal_after_line_item_discounts": 5000,
          "order.merchandise_subtotal_before_discounts": 5000,
          "order.merchandise_subtotal_after_line_item_discounts": 5000
        },
        "total_weight_grams": 2300,
        "total_item_quantity": 2,
        "leg_distance_meters": [8200]
      }
    }
  ],
  "evaluated_at": "2026-09-22T18:04:12.482913517Z",
  "delivery_quote_expires_at": "2026-09-22T18:19:12Z"
}

delivery_rate_callback_signing_key_id is the current HMAC key ID when HMAC is enabled, or an empty string for JWT-only callbacks. It is unrelated to the JWT header's kid. checkout_session_id is null when a delivery preview prices the methods, because a preview has no checkout session.

The fields a rate calculation usually reads:

delivery_rate_evaluation_idstring

Identifies this request. A retry reuses it, and each new quote gets a new one. Echo it in your response.

currencystring

The checkout currency. Every amount you return must use it.

destinationobject

The delivery address, limited to the fields listed in quote_input_fields. When several methods share a request, it holds every field any of them lists. Omitted when none lists an address field. buyer_location follows the same rule and adds latitude and longitude when a method lists buyer_location.coordinate.

candidates[].delivery_method_idstring

The method being priced. It stays the same when you edit the method, so use it to choose a service or price list.

candidates[].delivery_method_revision_idstring

The exact method revision being priced. Echo it in the method's result.

candidates[].execution_legs[]array

One entry per origin. origin_location_id is the Location the items leave from, and each allocation lists an order line, its quantity, and its merchandise value. Every candidate in a request has the same legs; methods that ship from different Locations get separate requests.

candidates[].pricingobject

Totals for the group. total_weight_grams is the sum of each item's variant unit_weight times its quantity, or the unit_weight on a custom line. It is omitted when any item in the group has no weight, so handle an absent value separately from 0, which is a real weight. leg_distance_meters holds the straight-line distance from each origin to the destination, and is empty when the address or an origin has no coordinates. bases holds the quantity and merchandise subtotals in minor units, keyed by the same names as tiered pricing bases.

evaluated_atstring

The quote's evaluation time, in RFC 3339 format with up to nine fractional digits. Compute every time you return from this value, not from your server's clock.

delivery_quote_expires_atstring

When the quote expires, in RFC 3339 format truncated to whole seconds. Every expires_at you return must be no later than this. It is up to 15 minutes after evaluated_at, or just under 5 minutes for a cart with tracked inventory.

testboolean

true on test deliveries. Omitted on live requests.

Response body#

Respond with a 2xx status and one JSON object, a DeliveryRateEvaluationResponse. Each method's outcome is a DeliveryRateEvaluationOutcome, selected by type. If you set Content-Type, it must be application/json.

JSON
{
  "delivery_rate_evaluation_id": "dreval_4c1e9a7b2f3d8e6a0b5c7d9e",
  "method_results": [
    {
      "delivery_method_revision_id": "dmetr_01K4STANDARD",
      "outcome": {
        "type": "available",
        "amount_money": { "amount": 1050, "currency": "USD" },
        "expires_at": "2026-09-22T18:14:12.482Z",
        "selection_guarantee_expires_at": "2026-09-22T18:34:12.482Z",
        "window_start_at": "2026-09-25T18:04:12.482Z",
        "window_end_at": "2026-09-28T18:04:12.482Z",
        "merchant_reference": "standard-3kg"
      }
    }
  ]
}

Outcome types#

Status
  • available
    You can deliver for this price. The outcome must meet every rule under Available outcomes.
  • unavailable
    You don't offer this method for the request. Set unavailable_reason to destination_not_served, pickup_unavailable, no_window_available, eligibility_no_match, pricing_unavailable, or inventory_unavailable.
  • cannot_calculate
    You couldn't price it, for example because your carrier API failed. Set failure_category, usually dependency_failure or timeout, and retryable to say whether a new quote might succeed.
JSON
{ "type": "unavailable", "unavailable_reason": "destination_not_served" }
JSON
{
  "type": "cannot_calculate",
  "failure_category": "dependency_failure",
  "retryable": true
}

failure_category also accepts malformed_response, pricing_failure, schedule_failure, geography_failure, routing_failure, address_verification_failed, and address_could_not_be_verified. Flint reserves the callback_ categories for failures it detects, and treats a result that uses one as invalid.

Available outcomes#

amount_moneyobjectRequired

The price in minor units. currency must equal the request's currency, and amount must be an integer within the method's minimum_fee_currency_options and maximum_fee_currency_options.

expires_atstringRequired

When the price stops being offered. It must be later than evaluated_at plus the method's minimum_option_lifetime_seconds, and no later than the request's delivery_quote_expires_at.

selection_guarantee_expires_atstringRequired

How long the price holds once the buyer selects it. Not earlier than expires_at. Flint holds a selection for at most 24 hours.

window_start_at, window_end_atstringRequired

The delivery window. The start is not earlier than evaluated_at, the end is after the start, and the end is within 366 days, or within the method's scheduling horizon for a schedule_window estimate. Buyers see the window as arrival_estimate dates in the timezone of the method's schedule, or of the origin Location. The end is exclusive, so a window ending at midnight doesn't include the next day.

service_levelstring

Replaces the method's configured service level for this option. For a shipment: economy, standard, expedited, express, overnight, or same_day. For local delivery: on_demand, same_day, or scheduled.

merchant_referencestring

Your private reference for the rate, at most 500 characters (not bytes), with no leading or trailing spaces. See step 6.

offered_windowsarray

Lets the buyer choose a delivery window. Each window has a unique window_id, start_at, end_at, and amount_money, plus an optional selection_guarantee_expires_at that is after evaluated_at and not later than the option's. Send at most 50 windows with no overlaps, and set the option's amount_money to the cheapest window's price. If you also send window_start_at and window_end_at, they must equal the first window's start and the last window's end.

Warning: Don't start a window at exactly evaluated_at

evaluated_at can have nine fractional digits. Node keeps three and Python keeps six, so a window that starts at the parsed time can fall before the real one and be rejected. Start windows later, as the examples do.

What Flint rejects#

Flint rejects the whole response, and drops every method in it, when:

  • delivery_rate_evaluation_id doesn't match the request.
  • The object has unknown fields or trailing data.
  • The body is larger than the callback's maximum_response_bytes.
  • Content-Type is set to something other than application/json, or the body isn't valid JSON.
  • ttl_seconds is outside 0 to 300.

Flint drops a single method, without affecting the others, when its result is missing, duplicated, has unknown fields, or breaks a rule above. An outcome carries only its own type's fields plus merchant_reference: an unavailable outcome with amount_money, or any outcome with window_selection or window_pricing, is dropped. Flint derives the window shape from offered_windows.

Cache responses with no available outcome#

When no outcome in a response is available, Flint reuses the response for the same checkout for ttl_seconds, which defaults to 120 and accepts 0 to 300. A response with a cannot_calculate outcome is reused for at most 30 seconds. Send "ttl_seconds": 0 at the top level to turn this off. Responses with an available outcome are never reused, so every new quote calls your server.

Timeouts, retries, and the circuit breaker#

  • Timeout. Each attempt, including request signing, gets request_timeout_seconds. Buyers wait on this call, so keep your endpoint fast and set the shortest timeout your carrier allows. With a retry, a buyer can wait about twice the timeout.
  • Retry. Flint retries once, immediately, after a connection error, a timeout, a non-2xx status, a 2xx with a Content-Type other than application/json, or an oversized body. The retry has the same webhook-id and body. Flint signs each HTTP request again; JWT retries get a fresh jti, even when two requests share the same timestamp. Flint doesn't retry other 2xx responses it rejects.
  • Circuit breaker. Consecutive failures trip a breaker that stops Flint from calling your endpoint, so a broken server doesn't slow every checkout.
Callback circuit breaker
  • closed moves to open on 30 consecutive failed requests
  • open moves to half_open on 30 seconds pass
  • half_open moves to closed on next request gets a valid response
  • half_open moves to open on next request fails

A failed request is one that fails after its retry, or whose response Flint rejects as a whole. A single malformed method result also counts: one that is missing, duplicated, has unknown fields or another type's fields, has an unknown type, lacks amount_money, or has an invalid merchant_reference. An outcome that parses but breaks a pricing or timing rule drops its method without counting. While the circuit is open, callback methods report callback_circuit_open. In half_open, the next quote's request is the probe; a valid response closes the circuit and resets the count.

The callback's circuit_state and circuit_failure_count describe its current revision. Each PATCH that carries configuration or signing_methods publishes a new revision with its own circuit, even when the values or the set are unchanged, so the new revision starts closed with a failure count of 0. Checkouts that pinned an earlier revision keep using that revision's circuit.

Change signing methods#

Every callback resource response includes signing_methods. Create defaults to ["jwt"]; PATCH replaces the whole set and requires the current expected_version. An empty array, an unknown value, or a duplicate value returns 400 INVALID_REQUEST with an INVALID_VALUE detail for signing_methods.

To migrate an existing HMAC callback, first enable both methods:

cURL
curl -X PATCH https://api.withflintpay.com/v1/delivery-rate-callbacks/dcb_01K4CARRIER \
  -H "Authorization: Bearer YOUR_API_KEY" \
  -H "Content-Type: application/json" \
  -H "Idempotency-Key: callback-enable-jwt" \
  -d '{"signing_methods": ["jwt", "hmac"], "expected_version": 1}'

Deploy JWT verification, then PATCH the latest version with "signing_methods": ["jwt"]. Removing hmac deletes the current and previous secrets, their key IDs, and expiry. A hybrid callback sends both credentials; if Flint cannot sign the JWT, it sends nothing and the callback is unavailable. Check-connection and test-deliveries return 503 SERVICE_UNAVAILABLE in that case.

Opt into HMAC#

A callback whose signing_methods includes hmac adds these headers to every request:

HeaderValue
webhook-signatureOne or more space-separated v1,<signature> values. Each is the base64 HMAC-SHA256 of {webhook-id}.{webhook-timestamp}.{raw body}, keyed with the base64-decoded part of the secret after whsec_.
Flint-Signing-Key-IdsSigning key IDs, comma-separated and current key first. Each matches a delivery_rate_callback_signing_key_id from the response that issued its secret. It lists two keys during a secret rotation.

Flint-Signing-Key-Ids is not part of the signed content. JWT-only callbacks omit both HMAC headers.

Use the HMAC verification examples with the callback secret. Check the exact raw body, webhook-id, and timestamp, reject timestamps outside five minutes, and accept any matching signature during rotation. Store secrets in your secret manager, including both during a rotation overlap.

To add HMAC to a callback that has no secret, PATCH signing_methods to include hmac, keeping jwt while you deploy:

cURL
curl -X PATCH https://api.withflintpay.com/v1/delivery-rate-callbacks/dcb_01K4CARRIER \
  -H "Authorization: Bearer YOUR_API_KEY" \
  -H "Content-Type: application/json" \
  -H "Idempotency-Key: callback-enable-hmac" \
  -d '{"signing_methods": ["jwt", "hmac"], "expected_version": 2}'

Flint issues the first secret in the same update and returns the callback with secret and delivery_rate_callback_signing_key_id, once. Store the secret before you do anything else: a retry with the same Idempotency-Key and the same API key returns it again under the one-time secret rules, but no other request does. If Flint can't return the response, it removes the secret and restores the callback's previous signing methods and URL, so retry the PATCH with the callback's latest version. The update increments version and emits one delivery_rate_callback.updated event.

Rotate or revoke the HMAC secret#

A JWT-only callback needs no shared-secret rotation. For HMAC, rotate on a schedule or when someone with access to the secret leaves:

cURL
curl -X POST https://api.withflintpay.com/v1/delivery-rate-callbacks/dcb_01K4CARRIER/rotate-secret \
  -H "Authorization: Bearer YOUR_API_KEY" \
  -H "Idempotency-Key: rotate-carrier-2026-09"

The response returns the callback with its new secret and delivery_rate_callback_signing_key_id, once. Rotation only replaces an existing secret: a callback without hmac returns 409 ACTION_NOT_ALLOWED with reason secret_not_issued, and you add hmac with PATCH instead. Rotating doesn't change the callback's version. Flint signs requests with both the old and new secrets for one hour, so webhook-signature carries two signatures and Flint-Signing-Key-Ids lists both keys. Add the new secret alongside the old one in your receiver's secret configuration, deploy, then remove the old secret. Rotating again before the hour is over returns 409 ACTION_NOT_ALLOWED with reason in_progress; details[0].previous_key_expires_at says when you can rotate again.

If a secret leaks, revoke its signing key instead of waiting out the overlap. Name both the callback and its key in target. Use the delivery_rate_callback_signing_key_id from the response that issued the secret, or an ID from that callback's Flint-Signing-Key-Ids header; don't send the secret:

cURL
curl -X POST https://api.withflintpay.com/v1/delivery-revocations \
  -H "Authorization: Bearer YOUR_API_KEY" \
  -H "Content-Type: application/json" \
  -H "Idempotency-Key: revoke-cbkey-3f9a" \
  -d '{
    "reason": "credential_compromise",
    "target": {
      "target_type": "delivery_rate_callback_signing_key",
      "delivery_rate_callback_id": "dcb_01K4CARRIER",
      "delivery_rate_callback_signing_key_id": "cbkey_3f9a1c2b7d4e5f60a1b2c3d4"
    }
  }'

Revocation is permanent, and quotes that depended on the key can no longer be selected. Rotate first, then revoke the leaked key, which is now the previous one: Flint stops signing with it immediately. Revoking the current key stops every request to your endpoint until a new key exists, so rotate right after. Flint allows that rotation even during an overlap.

Only the callback's current and previous HMAC keys can be revoked. An unknown callback, a callback from another merchant or environment, or a key that isn't its current or previous key returns 404 RESOURCE_NOT_FOUND; param names target.delivery_rate_callback_id or target.delivery_rate_callback_signing_key_id. The refusal changes nothing and sends no event. A second revocation for the same key returns 409 ALREADY_EXISTS with the existing revocation in details[0].current_resource and sends no second event. See delivery revocations for all target types and effects.

Before you go live#

  • JWT verification checks ES256, typ, kid, issuer, your dcb_ audience, issue time, expiry, jti, and the raw-body hash before pricing.
  • HMAC verification, when enabled, accepts any matching signature and rejects timestamps outside five minutes.
  • Answered evaluations live in a store that every server instance shares.
  • Every time is computed from evaluated_at, and expires_at is no later than delivery_quote_expires_at.
  • Amounts fall inside each method's minimum_fee_currency_options and maximum_fee_currency_options.
  • Carrier failures return cannot_calculate, not an HTTP error.
  • A real quote against your live URL returns available for each callback method, not only a passing test delivery.
  • A fixed-price or rate-table method is offered alongside callback methods if buyers must always have an option.

Endpoints#

A callback can't be deactivated or archived while an active method uses it. Delivery configuration documents every field and how PATCH updates a configuration.

Next steps#

Was this helpful?