Docs / Checkout state
Docs / Checkout state v0.1.0-alpha.1

Checkout state

The client is a small state machine. Its status is a discriminated union, so the compiler knows which fields exist in which state.

States

idle ─► evaluating ─► ready ─(inline: preparing ─► prepared)─► submitting ─► success
             │                     │                              ├─► redirecting
             ▼                     ▼                              ├─► pending
           error                 error                            └─► error ─► submit() again
StatusMeaningGuaranteed non-null
idleBefore the first evaluation. Only observable inside reset().
evaluatingAn async router is deciding. The rules router is synchronous and skips this.
readyA route is selected.route
preparingInline flow: the provider session is being created.route
preparedInline flow: the session exists; the payment element can mount.route, providerSession
submittingsubmit() is in flight.route
redirectingA hosted checkout was created and the browser is leaving for it. Nothing is paid yet.route, checkoutResult
pendingThe provider accepted the submission and has not completed the payment. checkoutResult.status says why: processing (waiting for the money) or open (waiting on the customer).route, checkoutResult
successThe provider’s browser SDK reported the payment complete.route, checkoutResult
errorRouting, preparing or submitting failed.error

canSubmit is derived (and is not a discriminant: narrow on status, not on canSubmit): a route is selected, nothing is in flight or settled, and an inline flow has its session. selectedProvider is route.provider or null.

Reading the state in React

docs-site/snippets/status.tsx from the repository, typechecked in CI
import { useTenderlaneCheckout } from '@tenderlane/react';

export function CheckoutStatus() {
  const checkout = useTenderlaneCheckout();

  switch (checkout.status) {
    case 'idle':
    case 'evaluating':
      return <p>Finding a payment route…</p>;
    case 'ready':
    case 'preparing':
    case 'prepared':
      return <p>Paying with {checkout.route.provider}.</p>;
    case 'submitting':
      return <p>Processing…</p>;
    case 'redirecting':
      return <p>Taking you to {checkout.checkoutResult.url}</p>;
    case 'pending':
      return <p>Payment {checkout.checkoutResult.id} is processing.</p>;
    case 'success':
      return <p>Payment {checkout.checkoutResult.id} went through.</p>;
    case 'error':
      // `route` is null when routing itself failed; then there is nothing to retry.
      return (
        <p role="alert">
          {checkout.error.message}
          {checkout.route && <button onClick={checkout.reset}>Start over</button>}
        </p>
      );
  }
}

useTenderlaneCheckout() returns the state plus submit, prepare, selectPaymentMethod and reset. It is built on useSyncExternalStore.

TenderlaneCheckoutForm covers the common case. It calls prepare() when an inline route is selected or its input changes, renders the element you registered for that provider, and passes { status, canSubmit, error, submit, retry } to its children. It renders no markup of its own.

Without React

docs-site/snippets/client.ts from the repository, typechecked in CI
import { createTenderlaneClient } from '@tenderlane/client';
import { stripeProvider } from '@tenderlane/stripe';
import { routing } from './routing';

const client = createTenderlaneClient({
  context: { country: 'DE' },
  providers: [stripeProvider({ publishableKey: 'pk_test_...', serverEndpoint: '/api/payments' })],
  routing,
});

client.subscribe(() => {
  const state = client.getSnapshot();

  switch (state.status) {
    case 'ready':
      console.log(`route: ${state.route.provider} / ${state.route.flow}`);
      break;
    case 'prepared':
      console.log('mount the payment element with', state.providerSession.clientSecret);
      break;
    case 'redirecting':
      console.log('leaving for', state.checkoutResult.url);
      break;
    case 'error':
      console.error(state.error.code, state.error.message);
      break;
  }
});

// App state changed: the next checkout uses the route for Switzerland.
client.updateContext({ country: 'CH' });

subscribe and getSnapshot are the whole binding surface. @tenderlane/react is about 350 lines on top of them and @tenderlane/vue about 150.

Rules the client enforces

  • One submit at a time. A second submit() while one is in flight throws INVALID_STATE.
  • No submit without a session on an inline flow. submit() before prepare() throws INVALID_STATE.
  • A stale session is never payable. A context change, or a new prepare(), drops the previous session first.
  • A context change during a submit waits. A payment element is not unmounted mid-confirmation. If the submit fails, the route for the new context is selected.
  • A settled checkout stays settled. In success, redirecting or pending, a context change is recorded but does not re-route; reset() starts a new checkout. Otherwise a paid customer would be offered a second payment.
  • A failed submit keeps the route. The status is error, canSubmit is true again, and the customer can retry.
  • A failed or expired result is an error, not a pending state.

Errors

Every error is a TenderlaneError with a code:

CodeRaised when
ROUTING_ERRORThe router threw
CONFIGURATION_ERRORThe router selected a provider that is not registered, or an unknown payment method was selected
INVALID_STATEprepare() or submit() was called when the state does not allow it
UNSUPPORTED_CAPABILITYThe router selected a flow the provider does not declare (for example inline for Polar). The status is error
PROVIDER_ERRORThe server or the provider rejected the request. provider and, where known, providerCode are set
VALIDATION_ERROR, CATALOG_ERRORServer side: bad request, or an item that cannot be priced

submit() records a provider failure in the state and also rejects, so both await and state-driven UIs work. prepare() records a provider failure in the state without rejecting. Both reject with INVALID_STATE, leaving the state alone, when called at the wrong time.

Middleware

middleware on the client config is a list of observers:

onContextChange, onRouteEvaluated, onSessionCreated, onCheckoutStart, onCheckoutSuccess, onCheckoutPending, onCheckoutError.

On the server handler, onCatalogResolved fires with the resolved prices. A middleware that throws is logged and skipped. Middleware cannot change a route, a price or a result.