Client & helpers

Generate a typed client from OpenAPI and implement production HTTP patterns.

TopicsReference

Avrix maintains SDKs for TypeScript, Python and PHP. All three are generated from the same OpenAPI document as this site, expose every Seller API operation as a method, and ship the three helpers a store needs on day one:

  • Order creation with key recovery — retries with the same Idempotency-Key, then looks the order up and re-reads lost keys, and only calls a refund safe when Avrix confirmed no live keys exist.
  • Webhook signature verification — HMAC-SHA256 on the raw body, a freshness window, and every v1 signature checked during a secret rotation.
  • Catalog mirror — snapshot cold start, then the GET /catalog/changes cursor (price changes included).

Every example on this site also works with plain HTTP; the Without an SDK section keeps the patterns for any other language.

Install#

The packages are built from the Avrix source repository at each SDK release: the client code is generated from the OpenAPI document, the helpers are tested against it, and the three languages are released together under one version (see Versioning). Until the first registry release:

The examples on this page show the SDK interface as it is built today. This page is updated when the packages are published.

LanguagePackage names (planned; not registered yet)Install command once published
TypeScript / Node.js 18+@avrix/seller-api-client (typed client) and @avrix/seller-api-helpers (order recovery, webhooks, catalog mirror, retries)npm install @avrix/seller-api-client @avrix/seller-api-helpers
Python 3.9+avrix-seller-api (import avrix_seller_api; standard library only, optional httpx transport)pip install avrix-seller-api
PHP 8.1+avrix/seller-api (namespace Avrix\SellerApi; ext-curl, or inject your own transport)composer require avrix/seller-api

All three are MIT licensed. Use a sandbox key while you build; the host is the same for sandbox and production keys.

Preview, order, verify#

The whole checkout in each language: preview before you charge, place the order with recovery, and verify the webhook that follows.

import {
  createOrderWithRecovery,
  createSellerClient,
  previewCheckoutLine,
  verifyAvrixWebhookSignature,
} from "@avrix/seller-api-helpers";

const avrix = createSellerClient({ baseUrl: "https://api.avrix.io", apiKey: process.env.AVRIX_API_KEY! });
const context = { schemaVersion: 1, salesCountryCode: "US", currencyCode: "USD", salesPriceGrossMinor: 7999, salesTaxRatePercent: 0, salesChannel: "web" };

// 1. Preview before you charge the buyer.
const preview = await previewCheckoutLine(avrix.fetch, avrix.baseUrl, {
  skuCode: "SANDBOX-ALWAYS-001", quantity: 1, countryCode: "US", integrationOrderContext: context,
});
if (!preview.canFulfill) throw new Error("Do not charge: Avrix cannot fulfil this quantity");

// 2. Charge, then order. Retries reuse the key; a lost response is recovered.
const order = await createOrderWithRecovery(avrix.fetch, avrix.baseUrl, {
  idempotencyKey: "store-order-10432",
  body: {
    skuCode: "SANDBOX-ALWAYS-001", quantity: 1, orderReference: "store-order-10432", countryCode: "US",
    expectedUnitPriceCents: preview.lines[0]!.unitPriceCents!,
    integrationOrderContext: { ...context, paymentProcessorReference: "psp_txn_10432" },
  },
});
if (order.status === "fulfilled") await saveKeys(order.keyIds, order.keys);
else if (order.refundSafe) await refundBuyer(order.error); // Avrix confirmed no live keys
// "unknown": keep the key and body, and run createOrderWithRecovery again later.

// 3. Verify every webhook on the raw body. During a secret rotation the header
//    carries one v1 per secret; any match passes.
const verdict = await verifyAvrixWebhookSignature(process.env.AVRIX_WEBHOOK_SECRET!, signatureHeader, rawBody);
if (!verdict.ok) throw new Error(`Rejected webhook: ${verdict.code}`);

Typed payloads, readable names and pagination#

Every SDK also ships what a large integration needs beyond the three helpers:

  • TypeScript. createSellerApi from @avrix/seller-api-client binds every typed operation to one configuration. Pass it the createSellerClient result from @avrix/seller-api-helpers and every typed call runs on the helpers transport: retries, throttling and the automatic Idempotency-Key. Without it, createSellerApi({ apiKey }) uses plain fetch. The standalone operation functions are unchanged.
  • Python. avrix_seller_api.models holds a TypedDict for every request body (PreviewOrderRequest) and every response data (PreviewOrderResult), for mypy or Pyright. iter_items and iter_pages follow meta.nextCursor for any list method; PAGINATED_OPERATIONS lists them. Method signatures are unchanged: bodies are still plain dicts.
  • PHP. Avrix\SellerApi\Generated\Shapes declares a PHPStan array shape per request body and response data; import them with @phpstan-import-type. Paginator::items() and Paginator::pages() follow meta.nextCursor for any list method. Method signatures are unchanged: bodies are still plain arrays.
  • Readable names. Where a generated method name reads badly, each SDK adds a readable name that calls exactly the same operation: revokeApiKey for deleteKey, pullKeys for pullKey, sendTestWebhook for createTest, getCatalogChecksum for listCatalogChecksum (Python: revoke_api_key, and so on). The generated names stay; both work. The full table is in connect.gen.ts of the TypeScript client and in OPERATIONS.md of the Python and PHP packages.
import { createSellerApi } from "@avrix/seller-api-client";
import { createSellerClient } from "@avrix/seller-api-helpers";

// One transport for everything: the helpers' retries, throttling and automatic
// Idempotency-Key now sit under every typed call of the generated client.
const seller = createSellerClient({ baseUrl: "https://api.avrix.io", apiKey: process.env.AVRIX_API_KEY! });
const avrix = createSellerApi(seller);

// Request bodies and results are typed from the OpenAPI document.
const { data: preview, error } = await avrix.previewOrder({
  body: { skuCode: "SANDBOX-ALWAYS-001", quantity: 1, countryCode: "US" },
});
if (error) throw new Error(`Avrix: ${JSON.stringify(error)}`);
console.log(preview.data.canFulfill);

// Readable names call exactly the generated operation (sendTestWebhook is createTest).
const { data: apiKeys } = await avrix.listApiKeys();

// Any list: the helpers paginator follows meta.nextCursor.
const refunds = seller.paginate(({ cursor, limit }) =>
  avrix.listRefunds({ query: { cursor, limit }, throwOnError: true }).then((res) => res.data),
);
for await (const refund of refunds) console.log(refund.id, refund.status);

Order creation with key recovery#

POST /orders can fail after the keys were pulled and billed — a dropped connection, 503 IDEMPOTENCY_STORE_UNAVAILABLE, 504 HOT_PATH_TIMEOUT. The order helper (createOrderWithRecovery, create_with_recovery, Orders::createWithRecovery) runs the key recovery runbook for you:

  1. POST /orders with your Idempotency-Key. A 2xx — fresh or replayed — is the answer.
  2. On a network error, 429, a 5xx or an in-flight claim, retry the same key and the same body (so the same orderReference), honouring Retry-After.
  3. When the retries run out, or Avrix answers with a definitive error, look the order up with GET /orders?orderReference=.
  4. When that shows fulfilled lines, re-read the live keys with POST /orders/recover-keys — an audited, read-only reveal that never pulls new inventory.
OutcomeMeaningWhat to do
fulfilledKeys are in keys / keyIds (source created, replayed or recovered)Persist them before you acknowledge the buyer
pre_orderThe pre-order was accepted without keysWait for order.ready, then POST /orders/{orderId}/fulfill (pre-orders)
failed with refundSafeDefinitive error and no live keys under the orderReferenceRefund the buyer at your payment processor
unknownThe outcome could not be establishedNever refund. Keep the key and body; run the helper again later

Pass an Idempotency-Key and an orderReference you persisted with the payment before the call, so a process restart replays the same request. See Idempotency.

Webhook verification#

Avrix signs <t>.<raw body> with HMAC-SHA256 and sends X-Avrix-Signature: t=<unix>,v1=<hex>. While an endpoint secret is rotating, the header carries one v1 per secret; the SDK verifiers accept a delivery when any v1 matches any secret you pass, and reject timestamps older than 300 seconds by default.

SDKCall
TypeScriptverifyAvrixWebhookSignature(secret, header, rawBody), or createWebhookConsumer({ secret, previousSecret, ... }) for verify, dedupe and fast acknowledgement
Pythonwebhooks.verify(raw_body, header, [secret]) or webhooks.construct_event(...)
PHPWebhooks::verify($rawBody, $header, [$secret]) or Webhooks::constructEvent(...)

Always pass the body bytes exactly as received — a re-serialised JSON object never matches. The full contract is in Webhooks.

Catalog mirror#

Seed from the snapshot, then drain the change feed from its cursor on a schedule. Price changes arrive in the feed with changedFields: ["pricing"]; they never move a product's updatedAt.

import { syncCatalogChanges, syncSellableCatalog } from "@avrix/seller-api-helpers";

const options = { baseUrl: "https://api.avrix.io", apiKey: process.env.AVRIX_API_KEY! };

// Cold start: snapshot + allocations. Persist the feed position it returns.
let cursor = await loadCursor();
if (!cursor) {
  const mirror = await syncSellableCatalog(options);
  await seedCatalog(mirror.products, mirror.sellable);
  cursor = mirror.changesCursor ?? null;
}

// On a schedule: drain the change feed (price changes included) from the cursor.
for (;;) {
  const page = await syncCatalogChanges({ ...options, cursor });
  await applyChanges(page.changes); // refetch only the facets in changedFields
  cursor = page.nextCursor ?? cursor;
  await saveCursor(cursor);
  if (!page.hasMore) break;
}

GET /allocations stays the authority on what you can sell — see Catalog and allocations.

Versioning#

SDK versions read 1.<YYYYMMDD>.<patch>, where the date is the contract date the SDK pins by default: the newest supported date that is not opt-in. 1.20260901.0 targets contract 2026-09-01, the same date an unpinned request is served, and sends X-Avrix-Api-Version: 2026-09-01 on every request unless you pin another supported date (api_version on the Python client, apiVersion on the PHP client; with the TypeScript helpers, set the header on the request). The patch number moves for SDK-only fixes. In Python and PHP the constant CONTRACT_DATE (Version::CONTRACT_DATE in PHP) exposes the date in code. The OpenAPI document's info.version is the same date, and its info.x-avrix-contract-dates lists every date you can pin. Compatibility rules: Versioning and compatibility.

Postman#

Import the public Seller API collection to explore the API without writing code:

The collection is regenerated from the OpenAPI document with every release, so it always matches this site. Its baseUrl is https://api.avrix.io; set apiKey to the raw key only (the collection adds the Bearer prefix). Write requests ship disabled — enable them after you selected a sandbox key.

Other languages: generate a client#

The OpenAPI document is the contract, and it is served live by your API host:

  • Interactive docs: https://api.avrix.io/api/seller/v1/docs
  • OpenAPI JSON download: https://api.avrix.io/api/seller/v1/openapi

Point any OpenAPI generator at that JSON to produce a typed client in your language of choice, and regenerate when the Changelog announces a contract change. Generated clients follow the same X-Avrix-Api-Version contract-date policy as the raw API: send the header to pin a date, or omit it for the stamped default. See Versioning and compatibility.

Without an SDK#

Every behaviour above is plain HTTP. When you use fetch or your own client, implement the same patterns.

Client configuration#

# Prefer env vars — never hardcode secrets in source control
export AVRIX_API_KEY="avrix_sk_sbx_your_key_here"
export AVRIX_BASE_URL="https://api.avrix.io"

Behaviours a production client needs#

Whether you generate a client or use fetch, implement these behaviours:

BehaviourWhy
Retry on 429 / 502 / 503 / 504Honour Retry-After with backoff
Stable Idempotency-Key on writesPrevents duplicate fulfilment on retries — Idempotency
Webhook signature verificationHMAC-SHA256 on the raw body — Webhooks
Catalog sync = snapshot + allocationsShared SKUs alone are not the sellable set — Catalog and allocations
Preview before chargeGate on canFulfill — Order preview

Authenticated request with retries#

TypeScript
async function sellerFetch(
  path: string,
  init: RequestInit & { idempotencyKey?: string } = {},
): Promise<Response> {
  const headers = new Headers(init.headers);
  headers.set("Authorization", `Bearer ${apiKey}`);
  if (init.idempotencyKey) headers.set("Idempotency-Key", init.idempotencyKey);
  if (init.body && !headers.has("Content-Type")) {
    headers.set("Content-Type", "application/json");
  }

  let attempt = 0;
  while (true) {
    const res = await fetch(`https://api.avrix.io${path}`, { ...init, headers });
    if (res.status !== 429 && res.status < 500) return res;
    attempt += 1;
    if (attempt > 5) return res;
    const retryAfter = Number(res.headers.get("Retry-After") ?? "1");
    await new Promise((r) => setTimeout(r, Math.min(30, retryAfter) * 1000));
  }
}

await sellerFetch("/api/seller/v1/whoami");

Preview → charge → order#

TypeScript
const previewRes = await sellerFetch("/api/seller/v1/orders/preview", {
  method: "POST",
  body: JSON.stringify({
    skuCode: "SANDBOX-ALWAYS-001",
    quantity: 1,
    countryCode: "US",
  }),
});
const previewJson = await previewRes.json();
if (!previewJson.data?.canFulfill) {
  throw new Error("Do not charge — Avrix cannot fulfil");
}

// Charge at your PSP, then:
const orderRes = await sellerFetch("/api/seller/v1/orders", {
  method: "POST",
  idempotencyKey: "ik_store_10432",
  body: JSON.stringify({
    skuCode: "SANDBOX-ALWAYS-001",
    quantity: 1,
    orderReference: "store-order-10432",
    countryCode: "US",
    expectedUnitPriceCents: previewJson.data.unitPriceCents,
    priceCommitmentToken: previewJson.data.priceCommitmentToken,
    integrationOrderContext: {
      schemaVersion: 1,
      salesCountryCode: "US",
      currencyCode: "USD",
      salesPriceGrossMinor: 1999,
      salesPriceNetMinor: 1999,
      priceIncludesTax: true,
      salesTaxAmountMinor: 0,
      salesTaxRatePercent: 0,
      salesChannel: "web",
      consumerIp: "203.0.113.42",
      paymentMethodFamily: "card",
      paymentProcessorReference: "psp_txn_10432",
      checkoutSessionId: "cs_store_10432",
    },
  }),
});

Catalog sync (HTTP algorithm)#

  1. Page through GET /catalog/snapshot (or GET /products) and persist meta.changesCursor.
  2. Page through GET /allocations and merge on SKU id — authoritative sellable.
  3. Poll GET /catalog/changes?cursor= from that position for deltas (tombstones and price changes included — a price change never moves a product's updatedAt), refetch the facets named in changedFields, persist meta.nextCursor, and repeat while meta.hasMore.

Never treat /products alone as the sellable catalog.

What links here

Published guides that link to this page.

Search docs

Search documentation…