TypeScript SDK

The merchi_sdk_ts package uses promises, typed entity properties and a configured Merchi instance. This guide follows SDK commit bc44313; installed releases may expose a smaller surface. Check your package version before using a newer entity or option.

Installation and initialization

npm install merchi_sdk_ts
import { Merchi } from 'merchi_sdk_ts';

// Public reads still pass the server's origin and model access checks.
const merchi = new Merchi();

For SDK development at the revision used by this guide, clone the repository, run npm install, then npm run build. Application bundlers can consume the published JavaScript and declarations; you do not need to clone the SDK to use it.

Authentication and backend selection

The constructor arguments, in order, are sessionToken, clientToken, invoiceToken, cartToken, backendUri. Omitted tokens are read from the corresponding browser cookies where available. The SDK transmits named token parameters and uses API protocol v6. Token types are workflow-specific; private operations still require server permissions. There is no universal API-key requirement for all reads.

import { Merchi } from 'merchi_sdk_ts';

// sessionToken must come from your application's authenticated session.
const staffClient = new Merchi(sessionToken);
const customClient = new Merchi(
  sessionToken, undefined, undefined, undefined, 'https://your-api.example/'
);

Backend selection is: constructor argument, window.merchiBackendUri, process.env.MERCHI_BACKEND_URI, then https://api.merchi.co/. Keep the base URL unversioned: the request layer adds /v6/. Avoid mismatched session-cookie and parameter values. See REST authentication.

List, search, filter and paginate

const result = await merchi.Product.list({
  limit: 20,
  offset: 0,
  q: 'shirt',
  sort: 'id',
  order: 'desc',
  embed: { domain: {} }
});
for (const product of result.items) console.log(product.id, product.name);
console.log(result.metadata.available, result.metadata.offset);

Lists return { items, metadata }, not an entity array directly. metadata contains available, count, limit, offset and optional canCreate. These are SDK wrappers around the raw REST response. Use items.length to inspect this page; available is the matching total.

skipCount: true avoids the count query and makes metadata.available null. Do not treat null as zero or assume a total is available for pagination. Advance by the returned item count and stop at an empty/short page; collection changes between requests can affect offset pagination.

q is server-side search, not arbitrary SQL. Filters such as inDomain, categoryId, productTypes, dateFrom, dateTo, clientId and state apply only to supporting models. Date options are Date objects. Consult the filter reference and the SDK’s list options and wire serialization. A backend parameter is not automatically an SDK option.

Fetch and edit an existing entity

const product = await merchi.Product.get(123, {
  embed: { domain: {} },
  withRights: true
});
product.name = 'Updated product name';
await product.save();

Replace example IDs with records your user can access. get and list are class methods on merchi.Product; save, create and delete are instance methods. save uses PATCH and serializes changed properties. withRights requests response rights information, not additional permissions.

Create and delete

const product = new merchi.Product();
product.name = 'New product';
product.domain = await merchi.Domain.get(123);
// Supply any other required fields for the selected product type/domain.
await product.create();

Creation is POST and populates the instance from the server response. Required fields and allowed values are defined by the API model, not by this minimal example. To delete an authorized existing record, call await product.delete() explicitly. Deletion can be restricted or archival; do not use it as a generic undo for unrelated business operations.

Embedding, nested creation and nested editing

An embed is a tree of relationship names: { domain: { company: {} } }. It is not a list of names. Unembedded relationships can be absent, so fetch them before reading or editing them. includeArchived is a separate get option supporting a boolean or nested descriptor; it does not grant access to archived records.

Construct related entities through the same client, for example new merchi.Domain(), and assign instances to relationship properties. Existing related entities use their IDs; new nested entities need their own required fields. Support for nested creation is model-specific. Editing an embedded child does not imply that calling the parent’s save() is the correct workflow for every relationship: use the child endpoint where required.

undefined and null are not interchangeable. Leave an unset value undefined when no update is intended; only use null to clear a field that the model permits clearing. Array changes, relationship removal and nullable values are serialized by Entity.toFormData; do not hand-build nested form keys from guesses.

The exported entity type can be used in annotations, while merchi.Product is the constructor configured with this client. Prefer the configured constructor when creating instances so requests use the intended backend and credentials.

Estimate a storefront selection locally

The SDK exports pricing.estimateQuote. Pass the full product pricing bundle and the customer’s selections. This example uses one independent select field. Replace the sample product, field and option IDs with the IDs from your storefront and the returned bundle.

import { pricing } from 'merchi_sdk_ts';

async function estimateProduct(
  apiOrigin: string,
  productId: number,
  selections: pricing.Selections,
): Promise<pricing.QuoteResult | pricing.UnsupportedResult> {
  const url = new URL(`/v6/products/${productId}/pricing-rules/`, apiOrigin);
  const response = await fetch(url);
  if (!response.ok) {
    throw new Error(`Unable to read product pricing rules (HTTP ${response.status})`);
  }
  const bundle: pricing.PricingRules | pricing.UnsupportedResult = await response.json();
  if (!('product' in bundle)) {
    return bundle;
  }
  return pricing.estimateQuote(bundle, selections);
}

const estimate = await estimateProduct('https://api.merchi.co', 123, {
  quantity: 10,
  fieldValues: { 1: { selectedOptionIds: [1] } },
});
if ('unsupported' in estimate) {
  console.log('Use a server-side estimate', estimate.unsupported);
} else {
  console.log(estimate.currency, estimate.totalCost);
}

Estimate grouped quantities

For a product with grouped options, pass each group’s quantity and field values under groups. Use the field IDs from rules.groupFields and option IDs from the corresponding field. Put any independent selections in the top-level fieldValues.

import { pricing } from 'merchi_sdk_ts';

function estimateGroupedProduct(rules: pricing.PricingRules) {
  return pricing.estimateQuote(rules, {
    fieldValues: {},
    groups: [
      { quantity: 5, fieldValues: { 10: { selectedOptionIds: [8] } } },
      { quantity: 10, fieldValues: { 10: { selectedOptionIds: [8] } } },
    ],
  });
}

The sample IDs and quantities come from the SDK’s grouped product fixture. With that fixture’s pricing bundle, the group costs are 215 and 430, the tax is 64.50, and the total including tax is 709.50. Handle an unsupported result as in the previous example and confirm the configuration and totals with the server before checkout.

Grouped pricing fixture

SDK pricing exports · Pricing input and result types

Show available choices for the current selection

After a customer changes a selection, resolve field visibility, option visibility and stock availability from the same pricing bundle. This example builds the visible controls for independent fields.

import { pricing } from 'merchi_sdk_ts';

function visibleProductChoices(
  rules: pricing.PricingRules,
  selections: pricing.Selections,
) {
  const visibleFields = pricing.resolveVisibleFields(rules, selections);
  const visibleOptions = pricing.resolveVisibleOptionIds(rules, selections);
  const unavailable = pricing.resolveUnavailableOptionIds(rules, selections);

  return rules.fields
    .filter((field) => visibleFields.has(field.id))
    .map((field) => ({
      fieldId: field.id,
      options: field.options
        .filter((option) => visibleOptions.has(option.id))
        .map((option) => ({ id: option.id, disabled: unavailable.has(option.id) })),
    }));
}

For controls within a group, pass the independent selections and only that group’s selections when checking its stock. This keeps the options selected in other groups out of the combination check. With no inventoryUnits, the stock helper returns an empty set. Its result reflects whether a matching combination had positive stock in the snapshot. Confirm that the server can supply the requested quantity before checkout.

SDK visibility helpers · SDK stock helper

Show quantity pricing bands

Use pricing.buildPriceMatrix with the current pricing bundle and selections. Pass the product’s minimum order quantity when it has one. The SDK uses the minimum and applicable quantity breaks to choose sample quantities for the table.

import { pricing } from 'merchi_sdk_ts';

function quantityPriceRows(
  rules: pricing.PricingRules,
  selections: pricing.Selections,
  minimumOrderQuantity: number,
) {
  const matrix = pricing.buildPriceMatrix(rules, selections, {
    minQuantity: minimumOrderQuantity,
  });
  if (!matrix) return [];

  return matrix.bands.map((band, index) => {
    const cell = matrix.cells[index];
    return {
      label: band.label,
      quantity: band.quantity,
      unitPriceBeforeTax: cell.unitPrice,
      totalWithTax: cell.totalCost,
      currency: matrix.currency,
    };
  });
}

Each row quotes the lower quantity of its band. unitPrice divides the pre-tax subtotal, including setup and variation costs, by that quantity. For a grouped selection, the SDK scales the current group quantities to each sample quantity. Re-estimate the buyer’s actual quantity and group mix before checkout. A bundle marked unsupported or with fewer than two distinct prices returns null.

SDK price matrix implementation

Confirm a cart item estimate with the server

Use CartItem.calculate() to estimate the current line when the local pricing bundle is unsupported or when you need the server’s latest calculation. Set the product and quantity on an unsaved item. For a configured product, also populate variations or variationsGroups with the choices to estimate.

const product = new merchi.Product();
product.id = 123;

const item = new merchi.CartItem();
item.product = product;
item.quantity = 25;

await item.calculate();
console.log(item.currency, item.subtotalCost, item.taxAmount, item.totalCost);

The method sends the item form to POST /v6/cart-item-cost-estimate/ and loads the HTTP 201 estimate back into the item instance. The request simulates the line without saving a cart item. Use the cart item creation example to add the confirmed selection, then read the cart for shipping, discounts and checkout totals.

CartItem.calculate implementation · Cart item estimate handler

Guest checkout

  1. Create or restore the cart for this storefront.
  2. Save the selected item, then update quantities or change a group’s option as the customer edits the cart.
  3. Save the delivery address, then generate and select shipping quotes.
  4. Apply any discount codes and show the updated total.
  5. Attach the checkout customer, then start or resume payment and confirm the invoice balance.
  6. Read the checkout invoice to restore the confirmation page after a reload.

For raw HTTP requests, see the cart and shipping workflow.

Start a guest checkout

Use the storefront’s domain ID and API base URL. Run this example in the storefront’s guest context because the SDK can pick up browser credentials. If the session already has a cart ID and token, restore that checkout.

import { Merchi } from 'merchi_sdk_ts';

async function startGuestCheckout(backendUri: string, domainId: number) {
  const storefront = new Merchi(undefined, undefined, undefined, undefined, backendUri);
  const domain = new storefront.Domain();
  domain.id = domainId;

  const cart = new storefront.Cart();
  cart.domain = domain;
  await cart.create();

  if (cart.id === undefined || !cart.token) {
    throw new Error('The API did not return a guest cart ID and token.');
  }

  return { cartId: cart.id, cartToken: cart.token };
}

Save the returned pair in the checkout session before adding items. Use that pair with the same API base URL in subsequent cart requests. In a browser, the storefront origin must be allowed by the domain’s API settings.

Restore a guest checkout after a page reload

Keep the cart ID and token together in the checkout session for the same storefront and API environment. Use the saved values to fetch the cart and restore the items, delivery address, selected quotes and discount codes.

import { Merchi } from 'merchi_sdk_ts';

async function restoreGuestCheckout(
  backendUri: string,
  cartId: number,
  cartToken: string,
) {
  const guest = new Merchi(undefined, undefined, undefined, cartToken, backendUri);
  const cart = await guest.Cart.get(cartId, {
    embed: {
      cartItems: { product: {}, variationsGroups: {} },
      receiverAddress: {},
      shipmentGroups: { selectedQuote: {} },
      discountItems: {},
    },
  });
  return { guest, cart };
}

Display the server’s shipmentTotalCost and totalCost. Reading the cart preserves its selected quotes. Regenerate them when the customer changes the delivery address or shippable items. For an HTTP 401 with MUST_LOGIN, check that the token belongs to this cart and API environment. For UNKNOWN_DOMAIN, check the browser origin against the storefront’s allowed API origins. Keep the token out of logs and analytics.

Set the first delivery address

Use this example when the cart has no receiverAddress. Supply the customer’s address fields for the destination and shipping method. Keep the postcode as a string so leading zeros survive.

import type { Merchi } from 'merchi_sdk_ts';

async function setFirstGuestDeliveryAddress(
  guest: Merchi,
  cartId: number,
  delivery: {
    lineOne: string;
    lineTwo?: string;
    city: string;
    state?: string;
    postcode: string;
    country: string;
  },
) {
  const address = new guest.Address();
  address.lineOne = delivery.lineOne;
  address.lineTwo = delivery.lineTwo;
  address.city = delivery.city;
  address.state = delivery.state;
  address.postcode = delivery.postcode;
  address.country = delivery.country;

  const cart = new guest.Cart();
  cart.id = cartId;
  cart.receiverAddress = address;
  return cart.save({ embed: { receiverAddress: {} } });
}

For an Australian address, use country: 'AU' and a state such as VIC. Read the saved address and its ID from the returned receiverAddress. Once the cart has items and an address, generate shipping quotes.

Edit the saved delivery address

Fetch the cart with receiverAddress embedded. Modify the embedded address and save the cart to update that address through the guest checkout.

import type { Merchi } from 'merchi_sdk_ts';

async function changeGuestDeliveryStreet(
  guest: Merchi,
  cartId: number,
  lineOne: string,
) {
  const cart = await guest.Cart.get(cartId, {
    embed: { receiverAddress: {} },
  });
  if (!cart.receiverAddress?.id) {
    throw new Error('Save a complete delivery address first.');
  }

  cart.receiverAddress.lineOne = lineOne;
  return cart.save({ embed: { receiverAddress: {} } });
}

Use the address returned by the save. An edit can return a different address ID, so use the latest ID for any subsequent edit. Generate fresh shipping quotes after changing the delivery address.

Save the selected item in a guest cart

Use the ID and token for the same guest cart. The example adds a product with no required options. For a configured product, use the configured item example.

import { Merchi } from 'merchi_sdk_ts';

async function addGuestCartItem(
  backendUri: string,
  cartId: number,
  cartToken: string,
  productId: number,
  quantity: number,
) {
  const guest = new Merchi(undefined, undefined, undefined, cartToken, backendUri);
  const cart = new guest.Cart();
  cart.id = cartId;

  const product = new guest.Product();
  product.id = productId;

  const item = new guest.CartItem();
  item.cart = cart;
  item.product = product;
  item.quantity = quantity;
  await item.create();

  const updatedCart = await guest.Cart.get(cartId, {
    embed: { cartItems: { product: {} } },
  });
  return { itemId: item.id, updatedCart };
}

Use the saved itemId for later edits and updatedCart.totalCost for the current cart total. If creation times out, read the cart before retrying to see whether the line was saved. Recalculate shipping after changing shippable items.

Save an item with grouped options

This example saves a product with one independent text field and one select field repeated across groups. Use the field and option IDs from the chosen product. Supply the real text and option values captured by the storefront alongside the quantities used in the estimate.

import type { Merchi } from 'merchi_sdk_ts';

async function addConfiguredGuestCartItem(
  guest: Merchi,
  cartId: number,
  productId: number,
  textFieldId: number,
  text: string,
  groupFieldId: number,
  selections: Array<{ quantity: number; optionId: number }>,
) {
  const variationFor = (fieldId: number, value: string) => {
    const field = new guest.VariationField();
    field.id = fieldId;
    const variation = new guest.Variation();
    variation.variationField = field;
    variation.value = value;
    return variation;
  };

  const cart = new guest.Cart();
  cart.id = cartId;
  const product = new guest.Product();
  product.id = productId;

  const item = new guest.CartItem();
  item.cart = cart;
  item.product = product;
  item.variations = [variationFor(textFieldId, text)];
  item.variationsGroups = selections.map(({ quantity, optionId }) => {
    const group = new guest.VariationsGroup();
    group.quantity = quantity;
    group.variations = [variationFor(groupFieldId, String(optionId))];
    return group;
  });

  return item.create({
    embed: { variations: {}, variationsGroups: { variations: {} } },
  });
}

Pass one entry per group, each with a positive quantity. For the select field, Variation.value is the selected option ID as a string. The server derives the item quantity from the groups. Read the saved item ID from the response and refresh the cart for the current total.

Change a saved cart item’s quantity

Use the same guest client and the saved itemId. For an item with grouped options, pass the ID of the group the customer selected for editing. Read group IDs and quantities from variationsGroups.

import type { Merchi } from 'merchi_sdk_ts';

async function changeGuestCartItemQuantity(
  guest: Merchi,
  cartId: number,
  itemId: number,
  quantity: number,
  groupId?: number,
) {
  const item = await guest.CartItem.get(itemId, {
    embed: { variationsGroups: {} },
  });
  const groups = item.variationsGroups ?? [];

  if (groups.length > 0 || groupId !== undefined) {
    const group = groups.find((candidate) => candidate.id === groupId);
    if (!group) {
      throw new Error('Choose an existing variation group for this item.');
    }
    group.quantity = quantity;
  } else {
    item.quantity = quantity;
  }

  await item.save();
  return guest.Cart.get(cartId, {
    embed: { cartItems: { variationsGroups: {} } },
  });
}

The API derives the quantity of a grouped item from the sum of its groups. Read the refreshed cart for the saved quantities and totals. To remove the line entirely, call await item.delete() on the fetched item, then refresh the cart. Refresh shipping quotes after edits that change shippable items.

Change a saved group’s selected option

Use the saved group and variation IDs from the cart item. Use an option ID from that variation’s select field. This example updates one existing selection and leaves group quantities unchanged.

import type { Merchi } from 'merchi_sdk_ts';

async function changeGuestCartGroupOption(
  guest: Merchi,
  cartId: number,
  itemId: number,
  groupId: number,
  variationId: number,
  optionId: number,
) {
  const item = await guest.CartItem.get(itemId, {
    embed: { variationsGroups: { variations: {} } },
  });
  const group = item.variationsGroups?.find((candidate) => candidate.id === groupId);
  const variation = group?.variations?.find((candidate) => candidate.id === variationId);
  if (!group?.variations || !variation) {
    throw new Error('Choose an existing variation in this group.');
  }

  variation.value = String(optionId);
  group.variations = [...group.variations];
  await item.save();

  return guest.Cart.get(cartId, {
    embed: { cartItems: { variationsGroups: { variations: {} } } },
  });
}

Assign the variations array back to the group so the SDK includes the edited group in the PATCH. Use the returned cart to display the saved selection and updated total. Refresh shipping quotes if the option changes the shipping requirements.

Generate shipping quotes and save a selection

Save the delivery address and cart items before generating quotes. Use the same guest client for both calls so the SDK sends the cart token. The quote endpoint returns shipment groups directly. Display each group’s quotes alongside the items it covers and mark its selectedQuote, if present.

import type { Merchi } from 'merchi_sdk_ts';

async function generateGuestShippingQuotes(guest: Merchi, cartId: number) {
  const response = await guest.authenticatedFetch(
    `/generate-cart-shipment-quotes/${cartId}/`,
    { method: 'GET' },
  );
  const cart = new guest.Cart();
  cart.fromJson(response);
  return cart.shipmentGroups ?? [];
}

async function selectGuestShippingQuote(
  guest: Merchi,
  cartId: number,
  shipmentGroupId: number,
  quoteId: number,
) {
  const quote = new guest.CartShipmentQuote();
  quote.id = quoteId;

  const group = new guest.CartShipmentGroup();
  group.id = shipmentGroupId;
  group.selectedQuote = quote;

  const cart = new guest.Cart();
  cart.id = cartId;
  cart.shipmentGroups = [group];
  return cart.save({ embed: { shipmentGroups: { selectedQuote: {} } } });
}

Use the chosen quote ID from the matching group in the latest response. A group with an empty quotes array has no delivery option to select. Generating quotes replaces the existing groups, so refresh the displayed options and IDs when the delivery address or shippable items change.

The save updates only the supplied group. Read shipmentGroups from the returned cart to confirm the selection, shipmentTotalCost for shipping including tax, and totalCost for the full cart total before payment.

Apply or remove checkout discount codes

Pass the full set of codes the customer wants to keep on the cart. The example checks that set against the current cart and saves only after the check succeeds. Pass an empty array to clear all codes.

import type { Merchi } from 'merchi_sdk_ts';

async function setGuestCartDiscountCodes(
  guest: Merchi,
  cartId: number,
  codes: string[],
) {
  const requested = codes.map((code) => code.trim());
  if (requested.some((code) => !code || code.includes(','))) {
    throw new Error('Enter one discount code per array entry.');
  }

  const cart = new guest.Cart();
  cart.id = cartId;
  cart.discountItems = [];

  if (requested.length > 0) {
    const checked = await guest.authenticatedFetch(
      `/carts/${cartId}/check_discount_code/`,
      { method: 'GET', query: [['codes', requested.join(',')]] },
    ) as { items: Array<{ code: string; description: string }> };

    cart.discountItems = checked.items.map(({ code, description }) => {
      const item = new guest.Item();
      item.code = code;
      item.description = description;
      item.quantity = 1;
      item.cost = 0;
      return item;
    });
  }

  return cart.save({ embed: { discountItems: {} } });
}

The check can return HTTP 404 for an unknown code or HTTP 403 if the cart fails an eligibility rule. A successful check leaves the saved cart as it was. The save sends cost: 0 as a placeholder and the server calculates the actual discount. Use the returned discountItems and totalCost to display the updated checkout amount.

Attach the checkout customer

A cart can hold items and shipping quotes before it has a customer. Creating a checkout invoice requires a client. Once your storefront’s customer sign-in or registration flow supplies the Merchi user ID for this checkout, attach that ID with the guest cart token.

import type { Merchi } from 'merchi_sdk_ts';

async function attachGuestCartCustomer(guest: Merchi, cartId: number, clientId: number) {
  const client = new guest.User();
  client.id = clientId;

  const cart = new guest.Cart();
  cart.id = cartId;
  cart.client = client;
  await cart.save();

  const updatedCart = await guest.Cart.get(cartId, { embed: { client: {} } });
  if (updatedCart.client?.id !== clientId) {
    throw new Error('The checkout customer was not attached to the cart.');
  }
  return updatedCart;
}

Send the client reference by ID. Update customer profile fields through your customer account flow. If starting payment returns Client is required, fetch the cart with embed: { client: {} } and check that the customer association was saved before retrying.

Start or resume a cart payment

Use the same guest client after the customer reviews the final cart total. Read payment mode first. If it returns legacy, follow the legacy cart payment example. In wallet mode, refresh a returned attemptId before starting a new attempt. Pass the saved attempt ID to the mode lookup when resuming after a redirect or reload.

import type { Merchi } from 'merchi_sdk_ts';

type CartPaymentMode = {
  engine: 'legacy' | 'wallet';
  attemptId: string | null;
};

type CartPaymentAttempt = {
  id: string;
  status: string;
  recorded: boolean;
  fullyPaid: boolean;
  invoiceId: number;
  amountMinor: number;
  remainingAmountMinor: number;
  currency: string;
  publishableKey: string | null;
  stripeClientSecret?: string | null;
};

async function getCartPaymentMode(guest: Merchi, cartId: number, attemptId?: string) {
  return await guest.authenticatedFetch(`/payments/stripe/cart/${cartId}/mode/`, {
    method: 'GET',
    query: attemptId ? [['attemptId', attemptId]] : [],
  }) as CartPaymentMode;
}

async function startCartPayment(guest: Merchi, cartId: number, requestKey: string) {
  return await guest.authenticatedFetch(`/payments/stripe/cart/${cartId}/attempts/`, {
    method: 'POST',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify({ requestKey }),
  }) as CartPaymentAttempt;
}

async function refreshCartPayment(guest: Merchi, cartId: number, attemptId: string) {
  return await guest.authenticatedFetch(
    `/payments/stripe/cart/${cartId}/attempts/${encodeURIComponent(attemptId)}/`,
    { method: 'GET' },
  ) as CartPaymentAttempt;
}

async function cancelCartPayment(guest: Merchi, cartId: number, attemptId: string) {
  return await guest.authenticatedFetch(
    `/payments/stripe/cart/${cartId}/attempts/${encodeURIComponent(attemptId)}/`,
    { method: 'DELETE' },
  ) as CartPaymentAttempt;
}

Keep one requestKey per payment action, including retries after a timeout. The example leaves the amount to the server. Read amountMinor and currency from the response for the amount of this attempt. If it returns a stripeClientSecret and publishableKey, pass them to the storefront’s Stripe integration. Keep the client secret out of logs and URLs. Save the attempt ID for the return from Stripe and refresh that attempt after confirmation. Use recorded to see whether Merchi recorded the payment and fullyPaid to see whether the invoice balance is settled.

A response with id: 'zero-balance' is already settled. Skip Stripe confirmation and the attempt refresh for this response. See the payment workflow for status, retry and amount details.

Cancel a wallet payment attempt

When the customer cancels, pass the saved wallet attempt ID to cancelCartPayment. Show the attempt as canceled when the returned status is canceled. If Stripe completed the payment before the cancel request arrived, the response can report a recorded payment. Use fullyPaid and remainingAmountMinor to display the invoice balance.

If the cancel request times out or the result is unclear, use refreshCartPayment on the same attempt before starting another payment. If the customer starts a new payment after cancellation, give that payment action a new requestKey.

Complete a legacy cart payment

Use the same guest client when payment mode reports legacy. Start the intent when the customer proceeds to payment. This GET can create a checkout invoice and a Stripe intent.

import type { Merchi } from 'merchi_sdk_ts';

type LegacyCartPayment =
  | { zeroBalance: true; amount: 0; currency: string }
  | { zeroBalance?: false; stripeClientSecret: string; amount: number; currency: string };

async function startLegacyCartPayment(guest: Merchi, cartId: number) {
  return await guest.authenticatedFetch(`/stripe/payment_intent/cart/${cartId}/`, {
    method: 'GET',
  }) as LegacyCartPayment;
}

async function completeLegacyCartPayment(guest: Merchi, cartId: number) {
  const response = await guest.authenticatedFetch(
    `/stripe/payment_intent/cart/complete/${cartId}/`,
    { method: 'GET' },
  );
  const invoice = new guest.Invoice();
  invoice.fromJson(response.invoice);
  return invoice;
}

For a positive balance, amount is in the currency’s minor units. Pass stripeClientSecret to Stripe with the publishable key for the same account and payment environment. After Stripe confirms success, call completeLegacyCartPayment to record the result in Merchi and read the invoice. Treat the invoice as settled when its unpaid field is false. If completion reports that validation is still pending, wait for Stripe confirmation before calling completion again.

If the start response has zeroBalance: true, Merchi has settled the invoice without a Stripe charge. You can call completion to read that invoice. See TypeScript sandbox checkout for the test-key and simulated payment paths.

Read the checkout invoice after payment

On the confirmation page, use the saved cart ID and token to fetch the cart with its invoice. This read also works after a reload. Request the invoice’s calculated balance and settlement status explicitly.

import type { Merchi } from 'merchi_sdk_ts';

async function readGuestCheckoutInvoice(guest: Merchi, cartId: number) {
  const cart = await guest.Cart.get(cartId, {
    embed: { invoice: { owedMoney: {}, isCompletelyPaid: {} } },
  });
  return cart.invoice ?? null;
}

If there is no invoice, show that checkout has yet to create one. If isCompletelyPaid is true, show the invoice as settled. Otherwise use owedMoney with the invoice currency to show the balance when available. After returning from Stripe, complete the payment flow or refresh the saved wallet attempt to reconcile the payment before reading the invoice.

Job quoting and inventory deductions

Job includes workflow methods beyond CRUD:

These are business actions; do not automatically repeat them after an ambiguous network error. Reconcile the server state first.

Custom requests, serialization and errors

merchi.authenticatedFetch(resource, options) is available for endpoints without a dedicated helper. Pass a resource such as /products/, not another /v6/ prefix. Use the handler’s actual method, encoding and response schema. Do not assume custom handlers return an entity envelope. toFormData() serializes entities; fromJson() loads response data and has dirty-state options for advanced workflows.

The request layer’s ApiError carries statusCode, mapped errorCode, errorMessage, optional details, and original. Handle ordinary network/runtime errors as well as API errors; not every caught value is an ApiError.

try {
  const product = await merchi.Product.get(123);
  console.log(product.name);
} catch (error) {
  console.error(error instanceof Error ? error.message : String(error));
}

For current routes see the API endpoint reference; for entity fields use the SDK entities and API model sources.