Skip to content

Tax calculation callbacks

A tax calculation callback registers the HTTPS endpoint of your own tax engine with Flint. Flint signs every request it sends to the endpoint, so your server can confirm the request came from Flint before it acts on it. Register a callback, verify its requests, test it, and select it as your environment's callback in tax settings. Then set an order's tax.calculation.components_source to callback, and Flint asks your endpoint for the order's external tax components whenever its tax would change.

Note: Which orders use the callback

Callback tax applies to orders you create or update with the orders API, including the checkout sessions and invoices you open for them, and to the orders Flint creates for checkout sessions, payment links, and subscriptions that ask for it. See Hosted checkout, payment links, and subscriptions.

How it works#

  • One callback per environment is selected. Each environment can hold many callbacks, but tax.calculation_callback_id in settings names the one Flint uses. Live and each sandbox select separately.
  • Callbacks have a lifecycle. A new callback is inactive. Only an active callback can be selected, and a selected callback can't be deactivated or archived.
  • Every request is signed. By default Flint signs with a JWT that you verify against Flint's public keys. No shared secret is issued unless you ask for one.
  • Orders opt in. An order uses the callback when its tax.calculation has mode external and components_source callback, or when your tax.default_calculation setting says so. So do the orders of checkout sessions and payment links whose tax.calculation asks for it, and of subscriptions whose tax does. Other orders keep their own tax.
  • Your endpoint has no fallback. Flint never substitutes a tax amount of its own for a callback that fails.

Before you begin#

  • A test API key with settings.write. Reads need settings.read or settings.write. Partner app tokens can't call these routes, as with the tax connection.
  • 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/tax-calculation-callbacks \
  -H "Authorization: Bearer YOUR_API_KEY" \
  -H "Content-Type: application/json" \
  -H "Idempotency-Key: tax-callback-engine-1" \
  -d '{
    "name": "Tax engine",
    "configuration": {
      "url": "https://tax.example.com/flint/tax-calculation",
      "request_timeout_seconds": 3
    }
  }'
Response
{
  "data": {
    "tax_calculation_callback_id": "tcb_01ARZ3NDEKTSV4RRFFQ69G5FAV",
    "current_tax_calculation_callback_revision_id": "tcbr_01BX5ZZKBKACTAV9WEVGEMMVRY",
    "name": "Tax engine",
    "status": "inactive",
    "version": 1,
    "configuration": {
      "url": "https://tax.example.com/flint/tax-calculation",
      "request_timeout_seconds": 3,
      "maximum_request_bytes": 262144,
      "maximum_response_bytes": 262144,
      "redirect_policy": "reject"
    },
    "signing_methods": ["jwt"],
    "circuit_state": "closed",
    "circuit_failure_count": 0,
    "created_at": "2026-11-06T18:00:00Z",
    "updated_at": "2026-11-06T18:00:00Z"
  },
  "request_id": "req_01K4EXAMPLE"
}

New callbacks default to signing_methods: ["jwt"]. Save tax_calculation_callback_id as the expected JWT audience. A JWT-only callback has no shared secret issued, stored, or returned. To opt into shared-secret verification, send "signing_methods": ["hmac"] or ["jwt", "hmac"] when creating the callback; only these create responses include secret and key_id, shown once. 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 3. Both byte limits accept up to 1,048,576. A new callback is inactive. 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. Answers a connection check with an empty JSON object.
  3. Answers a tax calculation, including a test delivery, with a calculation for every line item and charge in the request. A test delivery has none, so its answer has empty line_item_calculations and charge_calculations.

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, and answers. Each request carries a tax_calculation_evaluation_id (tce_...). Return 401 when verification fails, without saying which check failed.

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

const app = express();

app.post(
  "/flint/tax-calculation",
  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({});
    }

    res.json(calculate(evaluation));
  },
);

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 acting on a request, even if a gateway already verifies JWT signatures. Use your configured tax_calculation_callback_id as the audience, never an ID supplied by the incoming request.

HeaderValue
AuthorizationBearer <token> when jwt is enabled.
webhook-idThe request's tax_calculation_evaluation_id (tce_...). 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 tax_calculation_callback_id (tcb_...), 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.
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 = ["tcb_01ARZ3NDEKTSV4RRFFQ69G5FAV"];

// 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.tax_calculation_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 acting on the request.

Python
import base64
import hashlib
import hmac
import json
import time

import jwt

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


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("tax_calculation_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 tax calculation has "type": "tax_calculation", with "test": true on a test delivery.

Calculate the components#

Answer with a calculation for each line item and charge, in the shapes PATCH /v1/orders/{order_id} accepts. Replace componentsFor with a call to your tax engine. Every line item and charge needs at least one component, including non-taxable ones, which record a 0 rate.

JavaScript
// Replace with your tax engine. place is the item's pickup store or
// destination address, or the order's tax location.
function componentsFor(item, place) {
  return [{
    jurisdiction: { code: "US-NJ", country: "US", state: "NJ", level: "state", name: "New Jersey" },
    tax_type: "sales_tax",
    calculation_type: "percentage",
    percent: item.taxable ? 6.625 : 0,
  }];
}

function calculate(evaluation) {
  const place = (delivery) =>
    delivery?.pickup_location?.address ?? delivery?.destination ?? evaluation.tax_location.address;
  return {
    tax_calculation_evaluation_id: evaluation.tax_calculation_evaluation_id,
    line_item_calculations: evaluation.line_items.map((item) => ({
      order_line_item_id: item.order_line_item_id,
      calculation: { price_mode: "additive", components: componentsFor(item, place(item.fulfillment)) },
    })),
    charge_calculations: evaluation.charges.map((charge) => ({
      order_charge_id: charge.order_charge_id,
      calculation: { price_mode: "additive", components: componentsFor(charge, place(charge.delivery)) },
    })),
  };
}

Return 401 when verification fails, without revealing which check failed. Flint treats a 401 like any other non-2xx status: the request failed.

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.

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/tax-calculation-callbacks/tcb_01ARZ3NDEKTSV4RRFFQ69G5FAV/check-connection \
  -H "Authorization: Bearer YOUR_API_KEY" \
  -H "Idempotency-Key: check-tax-engine-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": {
    "tax_calculation_callback_id": "tcb_01ARZ3NDEKTSV4RRFFQ69G5FAV",
    "tax_calculation_callback_revision_id": "tcbr_01BX5ZZKBKACTAV9WEVGEMMVRY",
    "key_id": "",
    "status": "succeeded",
    "http_status_code": 200,
    "checked_at": "2026-11-06T18:02:00Z",
    "latency_milliseconds": 84
  },
  "request_id": "req_01K4EXAMPLE"
}

Then send a test delivery, a signed sample request with "test": true:

cURL
curl -X POST https://api.withflintpay.com/v1/tax-calculation-callbacks/tcb_01ARZ3NDEKTSV4RRFFQ69G5FAV/test-deliveries \
  -H "Authorization: Bearer YOUR_API_KEY" \
  -H "Idempotency-Key: test-tax-engine-1"

The result has the same shape as a connection check, with tested_at in place of checked_at. The sample request carries a tax_calculation_evaluation_id and empty line_items and charges. Your endpoint passes by echoing the ID and returning empty line_item_calculations and charge_calculations, which the example handler does for a request with no line items or charges. The other IDs in the sample are random, so your handler must accept IDs it has never seen.

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-tax-engine-2.

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 tcb_ 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 whose tax_calculation_evaluation_id doesn't match the request, or whose line_item_calculations or charge_calculations isn't an empty array.
request_errorFlint couldn't complete the request for another reason. Check the URL and your server logs.

4. Activate the callback and select it#

Activate the callback with a PATCH that sends only status:

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

Then select it in your environment's settings:

cURL
curl -X PATCH https://api.withflintpay.com/v1/settings \
  -H "Authorization: Bearer YOUR_API_KEY" \
  -H "Content-Type: application/json" \
  -H "Idempotency-Key: select-tax-callback-1" \
  -d '{ "tax": { "calculation_callback_id": "tcb_01ARZ3NDEKTSV4RRFFQ69G5FAV" } }'

The settings response returns the selected ID in tax.calculation_callback_id. To switch to another callback, activate it and send its ID in the same way. The selection changes in one write, so the environment never has two callbacks selected or none in between. Sandboxes and live keep separate callbacks and selections.

A selected callback can't be deactivated or archived. Select another callback first, or clear the selection. Until you do, the request returns 409 RESOURCE_IN_USE, and details[0].blocking_resources names your merchant account, with resource_type merchant and a mer_ resource_id, because the selection lives in your settings.

5. Calculate order tax#

Switch an order to your callback with its tax.calculation:

cURL
curl -X PATCH https://api.withflintpay.com/v1/orders/ord_01K4EXAMPLE \
  -H "Authorization: Bearer YOUR_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "tax": {
      "calculation": {"mode": "external", "price_mode": "additive", "components_source": "callback"}
    }
  }'

Flint drops any components you sent the order and calls your endpoint in the same request. The response's tax.components_source is callback, tax.callback_evaluation names the evaluation your endpoint answered, and each line item and charge carries the tax.calculation you returned. To create an order this way, send the same tax.calculation with POST /v1/orders, or set it once as tax.default_calculation in settings for every order that leaves its calculation out.

Flint creates these orders, so your callback is the only source of their external tax:

  • Checkout sessions and payment links: send "tax": {"calculation": {"mode": "external", "components_source": "callback"}}. Flint calls your endpoint once the buyer gives an address or picks delivery, and hosted checkout asks the buyer for a location as it does for automatic tax. The checkout_session_id in the request names the session. See Tax at checkout and payment links.
  • Subscriptions: set "tax": {"enabled": true, "calculation": {"mode": "external", "components_source": "callback"}}. Renewal, setup fee, and plan change orders call your endpoint with the request's subscription_id. A renewal your endpoint can't price is held without charging, and retried after an hour, then up to once a day; dunning doesn't start. See Tax on subscriptions.
  • With no calculation of their own, they follow tax.default_calculation. Under a callback default, turning on tax.default_enabled needs a selected callback and no tax connection.

Flint calls your endpoint:

  • On every change that would recalculate tax: adding, changing, or removing line items, charges, or discounts, and changing the customer, the delivery destination, the tax location, or the delivery or pickup selection.
  • Before a payment starts, when the order's last evaluation is more than 24 hours old. If your answer changes the order's tax, Flint saves it and refuses the payment with 409 VERSION_CONFLICT, so the buyer reviews the new total before paying again. An unchanged answer lets the payment continue without changing the order, so tax.callback_evaluation.evaluated_at keeps its earlier time.

Flint resolves the order's tax location as it does for automatic tax: a pickup store, the delivery destination, a shipment, the location you sent, then the customer's address. Without one, tax.status is requires_location and Flint doesn't call. Each call counts toward the checkout session's tax calculation limit, as automatic tax does.

While an order's components come from your callback, Flint refuses components in its requests: components in the order's tax.calculation, a line item's or charge's tax.calculation, tax.line_item_calculations, tax.charge_calculations, and tax.delivery_charge_calculation each return 400 INVALID_REQUEST with detail code NOT_ALLOWED. To supply your own components again, send components_source provided with a calculation for every line item and charge in the same request.

Delivery options#

When the buyer selects a delivery option, each generated delivery charge appears in charges with a delivery object naming its method, its choice group, and its pickup store or destination. Return its calculation by order_charge_id like any other charge. A new selection creates the charges again and Flint calls again, so no stale calculation stays on the order. For a paid pickup, the store is the pickup location for both the line items and the pickup fee, so you can tax both at the store's jurisdiction. Flint doesn't ask for tax per delivery option before the buyer selects one, and the delivery rate callback carries no tax.

Callback orders take no tax.delivery_charge_calculation. Checkout sessions, payment links, and invoices can offer paid delivery methods on them without one.

Request body#

Flint sends only what a tax calculation needs: no customer names, email addresses, or metadata.

Response
{
  "type": "tax_calculation",
  "tax_calculation_evaluation_id": "tce_01K4EXAMPLE",
  "tax_calculation_callback_revision_id": "tcbr_01BX5ZZKBKACTAV9WEVGEMMVRY",
  "test": false,
  "evaluated_at": "2026-11-07T18:00:00Z",
  "order_id": "ord_01K4EXAMPLE",
  "checkout_session_id": "cs_01K4EXAMPLE",
  "subscription_id": null,
  "currency": "USD",
  "transaction_date": "2026-11-07",
  "tax_location": {
    "location_id": null,
    "address": {"line1": "1 Hudson Street", "city": "Hoboken", "state": "NJ", "postal_code": "07030", "country": "US"}
  },
  "customer": {"customer_id": "cus_01K4EXAMPLE", "tax_exempt": false, "tax_ids": []},
  "line_items": [{
    "order_line_item_id": "li_01K4EXAMPLE",
    "variant_id": "var_01K4EXAMPLE",
    "name": "Ceramic mug",
    "quantity": 2,
    "taxable": true,
    "line_item_tax_category": "general",
    "taxable_money": {"amount": 5000, "currency": "USD"},
    "fulfillment": {
      "type": "shipment",
      "fulfillment_choice_group_id": "dcgrp_01K4EXAMPLE",
      "origin": {
        "location_id": "loc_01K4WAREHOUSE",
        "address": {"line1": "300 Harbor Road", "city": "Newark", "state": "NJ", "postal_code": "07105", "country": "US"}
      },
      "destination": {"line1": "1 Hudson Street", "city": "Hoboken", "state": "NJ", "postal_code": "07030", "country": "US"}
    }
  }],
  "charges": [{
    "order_charge_id": "och_01K4EXAMPLE",
    "type": "shipping_fee",
    "charge_tax_category": "shipping",
    "taxable": true,
    "applied_money": {"amount": 799, "currency": "USD"},
    "delivery": {
      "delivery_method_id": "dmet_01K4STANDARD",
      "delivery_method_type": "shipment",
      "fulfillment_choice_group_id": "dcgrp_01K4EXAMPLE",
      "origin": {
        "location_id": "loc_01K4WAREHOUSE",
        "address": {"line1": "300 Harbor Road", "city": "Newark", "state": "NJ", "postal_code": "07105", "country": "US"}
      },
      "destination": {"line1": "1 Hudson Street", "city": "Hoboken", "state": "NJ", "postal_code": "07030", "country": "US"}
    }
  }]
}
FieldDescription
tax_calculation_evaluation_idThe evaluation (tce_...), also the webhook-id header. Identical inputs keep the same ID, so deduplicate on it.
tax_calculation_callback_revision_idThe callback revision (tcbr_...) Flint called.
testtrue on test deliveries, false for orders.
evaluated_atWhen Flint built the request, in RFC 3339 format.
order_id, checkout_session_id, subscription_idThe order, and the buyer's checkout session or the order's subscription when there is one; otherwise null.
currency, transaction_dateThe order's currency, and the UTC date of the evaluation.
tax_locationThe order's tax location, with its Flint location_id when it is a store, otherwise null.
customerThe order's customer_id, whether the customer is tax_exempt, and their tax_ids, each with country, optional region, identifier_type, and value.
line_items[]Each unpaid line item with an amount: its ID, variant_id, name, quantity, taxable, line_item_tax_category, and taxable_money after discounts. fulfillment names its delivery type, choice group, origin store, and destination address or pickup_location store, or is null when no delivery selection covers it.
charges[]Each unpaid charge with an amount: its ID, type, charge_tax_category, taxable, and applied_money. A delivery charge has delivery with delivery_method_id, delivery_method_type, choice group, origin, and destination or pickup_location; other charges have null.

Paid line items and charges keep the calculations they were paid with and aren't sent again.

Response body#

Respond with a 2xx status and one JSON object, with Content-Type application/json if you set one:

JSON
{
  "tax_calculation_evaluation_id": "tce_01K4EXAMPLE",
  "line_item_calculations": [{
    "order_line_item_id": "li_01K4EXAMPLE",
    "calculation": {
      "price_mode": "additive",
      "components": [{
        "jurisdiction": {"code": "US-NJ", "country": "US", "state": "NJ", "level": "state", "name": "New Jersey"},
        "tax_type": "sales_tax",
        "calculation_type": "percentage",
        "percent": 6.625
      }]
    }
  }],
  "charge_calculations": [{
    "order_charge_id": "och_01K4EXAMPLE",
    "calculation": {
      "price_mode": "additive",
      "components": [{
        "jurisdiction": {"code": "US-NJ", "country": "US", "state": "NJ", "level": "state", "name": "New Jersey"},
        "tax_type": "sales_tax",
        "calculation_type": "percentage",
        "percent": 6.625
      }]
    }
  }]
}
  • Echo the evaluation. tax_calculation_evaluation_id must match the request.
  • Cover exactly what Flint sent. line_item_calculations and charge_calculations are required, with one entry for each line item and charge in the request and nothing else.
  • Use the order API's shapes. Each calculation has price_mode and components, as in PATCH /v1/orders/{order_id}, and passes the same validation.
  • Flat order taxes are optional. Add calculation.components with flat_amount components, such as a retail delivery fee, as on the order's own tax.calculation.
  • One bad part rejects the answer. An unknown field, a missing or extra entry, or an invalid component rejects the whole response, and Flint applies none of it.

Flint reuses a validated answer for identical inputs for 15 minutes without calling again, and keeps it for 30 days.

Failures#

Flint never calculates tax of its own for a callback order. When your endpoint fails, times out, or answers badly:

  • A request that changes the order returns 502 EXTERNAL_SERVICE_ERROR with reason tax_callback_failed and retry same_request, and the order is unchanged. details[0].failure_category says why: callback_transport_failure (including a timeout), callback_circuit_open, callback_result_invalid, or callback_unavailable.
  • A change that keeps its update when automatic tax can't be calculated, such as releasing a delivery selection, keeps it here too. The order's tax.status is incomplete, and payment waits until a later change calculates tax.
  • When the order needs an evaluation and no active callback is selected, the request returns 409 ACTION_NOT_ALLOWED with reason configuration_required and resource_type tax_calculation_callback. An order whose evaluation is under 24 hours old can still be paid after you clear the selection. Creating a checkout session, opening a payment link, or setting a subscription's tax that needs your callback is refused the same way.
  • A subscription renewal or setup fee your endpoint can't price is held instead of failing: Flint charges nothing, the subscription doesn't become past_due, and Flint tries again after an hour, backing off to once a day. Calls that charge while you wait, a plan change or quantity change billed now and POST /v1/subscriptions/{subscription_id}/renew, return the same 502 to the request, or the 409 configuration_required above when no callback is selected. With no callback selected, a renewal is held and tried once a day, while a setup fee, a first payment, or a dunning retry fails as other configuration problems do.

Timeouts and diagnostics#

Each request, including request signing, gets request_timeout_seconds. A connection check and a test delivery each send one request. Flint doesn't retry them, and they don't change the callback's circuit state, so a failed check can be repeated with a new Idempotency-Key as often as you need.

For an order, Flint retries once, immediately, after a connection error, a timeout, a non-2xx status, or an unusable 2xx, with the same webhook-id and body. A request larger than maximum_request_bytes isn't sent. After 30 consecutive failed evaluations, the circuit opens and Flint stops calling for 30 seconds, then lets one request through; a valid answer closes it.

circuit_state and circuit_failure_count appear on every callback and describe its current revision. A change to configuration or signing_methods creates a revision with its own 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 add HMAC verification alongside JWT, issue the first secret with rotate-secret, which adds hmac and keeps jwt enabled. To remove hmac, PATCH the latest version with "signing_methods": ["jwt"]:

cURL
curl -X PATCH https://api.withflintpay.com/v1/tax-calculation-callbacks/tcb_01ARZ3NDEKTSV4RRFFQ69G5FAV \
  -H "Authorization: Bearer YOUR_API_KEY" \
  -H "Content-Type: application/json" \
  -H "Idempotency-Key: tax-callback-jwt-only" \
  -d '{"signing_methods": ["jwt"], "expected_version": 3}'

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 key_id from create or rotation. 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.

Adding hmac through PATCH when a callback has no secret returns 409 ACTION_NOT_ALLOWED with reason secret_not_issued. Call rotate-secret to issue the first secret and add hmac, keeping jwt enabled. Issuing the first secret increments the callback's version and emits a tax_calculation_callback.updated event, so read the callback again before your next PATCH.

Rotate 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/tax-calculation-callbacks/tcb_01ARZ3NDEKTSV4RRFFQ69G5FAV/rotate-secret \
  -H "Authorization: Bearer YOUR_API_KEY" \
  -H "Idempotency-Key: rotate-tax-engine-2026-11"

The response returns the new key_id and secret. When rotating an existing secret, 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.

Before you go live#

  • JWT verification checks ES256, typ, kid, issuer, your tcb_ audience, issue time, expiry, jti, and the raw-body hash before the endpoint acts on a request.
  • HMAC verification, when enabled, accepts any matching signature and rejects timestamps outside five minutes.
  • A connection check and a test delivery both succeed against your live URL.
  • The callback is active and selected in tax.calculation_callback_id.
  • Your endpoint returns a calculation for every line item and charge it receives, and answers within request_timeout_seconds.

Events#

Each change to a callback sends a webhook event with the callback as its data: tax_calculation_callback.created, tax_calculation_callback.activated, tax_calculation_callback.deactivated, tax_calculation_callback.updated, and tax_calculation_callback.archived.

Endpoints#

Tax calculation callbacks documents every field, versions, and archiving.

Next steps#

Was this helpful?