Docs / Getting started
Docs / Getting started v0.1.0-alpha.1

Getting started

Run the example checkout in a few minutes, with no payment account, then switch on Stripe test mode.

Prerequisites

  • Node.js 18 or newer
  • pnpm 9 (corepack enable picks the version pinned in package.json)

Nothing else. The packages are not on npm yet, so you run Tenderlane from a clone of the repository.

Run the example

git clone https://github.com/farisaziz12/tenderlane.git
cd tenderlane
pnpm install
pnpm example

pnpm example builds the packages and starts the Next.js example on http://localhost:3000.

What you should see

A page with three panels: the app state (a country select), the route the router selected, and a checkout.

  1. With United Kingdom selected, the route panel reads fallback / demo / hosted.
  2. Press Pay. The browser posts { items: [{ sku: 'pro-plan', quantity: 1 }] } to /api/payments. There is no amount in the request.
  3. The server prices the item from its catalog and returns a URL. You land on a page marked Demo provider showing $29.00.
  4. Press Pay there. You return to /success, which reads Payment confirmed: the demo provider sent the shop a signed webhook when you paid, and the page asked it again from the server. The learned from line shows both. Open the same URL for a checkout you did not pay and it reads Payment not confirmed yet.

Now change the country to Switzerland. The route panel changes to ch-inline / stripe / inline and the price to CHF 29.00, without a reload. Without Stripe keys the checkout panel tells you that route cannot be paid yet.

Switch on Stripe test mode

Copy the env file and add your Stripe test keys:

cp examples/react-checkout-multi-psp/.env.example examples/react-checkout-multi-psp/.env.local
STRIPE_SECRET_KEY=sk_test_...
NEXT_PUBLIC_STRIPE_PUBLISHABLE_KEY=pk_test_...

Restart pnpm example. Then:

  • Switzerland mounts Stripe’s Payment Element in the page (inline). Pay with the test card 4242 4242 4242 4242, any future date, any CVC. The status becomes success.
  • Germany redirects to Stripe Checkout (hosted).

The Polar route (United States) needs a Polar sandbox token and product id; see .env.example.

VariableNeeded forExposed to the browser
STRIPE_SECRET_KEYStripe routesNo
NEXT_PUBLIC_STRIPE_PUBLISHABLE_KEYStripe inline routeYes, by design
POLAR_ACCESS_TOKEN, POLAR_PRODUCT_IDPolar routeNo
POLAR_ENVIRONMENTsandbox (default) or productionNo
STRIPE_WEBHOOK_SECRET, POLAR_WEBHOOK_SECRETReceiving that provider’s webhooks at /api/webhooks/<provider>No

The two files that matter

The rules, imported by both the page and the API route:

examples/react-checkout-multi-psp/app/checkout/routing.ts from the repository, typechecked in CI
import { createRulesRouter } from '@tenderlane/core';

/**
 * Which provider and flow a checkout uses, as data. The browser evaluates
 * these rules to render the right UI; the server evaluates the same rules to
 * refuse a request for any other provider.
 */
export const routing = createRulesRouter({
  rules: [
    {
      id: 'ch-inline',
      description: 'Switzerland pays in the page with the Stripe Payment Element',
      when: { country: 'CH' },
      use: { provider: 'stripe', flow: 'inline' },
    },
    {
      id: 'eu-hosted',
      description: 'The rest of the EU is sent to Stripe Checkout',
      when: { country: { in: ['DE', 'FR', 'NL'] } },
      use: { provider: 'stripe', flow: 'hosted' },
    },
    {
      id: 'us-polar',
      description: 'The US is sent to Polar, which acts as merchant of record',
      when: { country: 'US' },
      use: { provider: 'polar', flow: 'hosted' },
    },
  ],
  fallback: { provider: 'demo', flow: 'hosted' },
});

The server handler, mounted at /api/payments. It registers a real provider adapter only when its key is present:

examples/react-checkout-multi-psp/app/checkout/server.ts from the repository, typechecked in CI
import { createTenderlaneHandler } from '@tenderlane/core/server';
import type { Catalog, PaymentEvent, ServerProviderAdapter } from '@tenderlane/core';
import { stripeServerAdapter } from '@tenderlane/stripe/server';
import { createPolarCatalog, polarServerAdapter } from '@tenderlane/polar/server';
import { demoServerAdapter } from '../demo-psp/server';
import { catalog } from './catalog';
import { isCountry } from './countries';
import { applyPaymentStatus, findOrder, recordOrder } from './orders';
import type { Order, UpdateSource } from './orders';
import { routing } from './routing';

/** Real provider adapters are registered only when their keys are present. */
function createHandler() {
  const providers: ServerProviderAdapter[] = [demoServerAdapter()];
  const catalogs: Record<string, Catalog> = {};

  if (process.env.STRIPE_SECRET_KEY) {
    providers.push(
      stripeServerAdapter({
        secretKey: process.env.STRIPE_SECRET_KEY,
        webhookSecret: process.env.STRIPE_WEBHOOK_SECRET,
      }),
    );
  }

  if (process.env.POLAR_ACCESS_TOKEN && process.env.POLAR_PRODUCT_ID) {
    const polar = {
      accessToken: process.env.POLAR_ACCESS_TOKEN,
      server: process.env.POLAR_ENVIRONMENT === 'production' ? 'production' : 'sandbox',
      webhookSecret: process.env.POLAR_WEBHOOK_SECRET,
    } as const;
    providers.push(polarServerAdapter(polar));
    // Polar sells products it knows by id, so its price comes from Polar.
    catalogs.polar = createPolarCatalog({
      ...polar,
      skus: { 'pro-plan': { productId: process.env.POLAR_PRODUCT_ID } },
    });
  }

  return createTenderlaneHandler({
    providers,
    // Prices come from here, never from the request.
    catalog,
    catalogs,
    // The same rules the browser evaluated. A request for any other provider is rejected.
    routing,
    // The request's context is written by the browser. This example accepts
    // only a country from its own list; a real app would read it from a geo
    // header or the session instead.
    resolveContext: (_request, clientContext) => ({
      country: isCountry(clientContext.country) ? clientContext.country : 'GB',
    }),
    // Record the order under the provider's id, with the prices the server
    // charged. The success page and a webhook look it up by that id.
    onCheckoutCreated: ({ provider, result, items }) => {
      recordOrder({ provider, checkoutId: result.id, items });
    },
    onError: (error) => console.error('[payments]', error),
  });
}

/** Server-only: holds the secret keys. Imported by the API routes and by server components. */
export const handler = createHandler();

/**
 * Ask the provider what the state of an order's payment is and record it.
 * The one place an order's status changes, whoever asks: the success page
 * when the customer returns, or a webhook when the provider says something
 * happened.
 */
export async function refreshOrder(order: Order, source: UpdateSource): Promise<void> {
  const details = await handler.retrieve(order.provider, order.checkoutId);
  applyPaymentStatus(order, details.status, source);
}

/**
 * A webhook is treated as a hint that something changed, not as the change
 * itself: events arrive more than once and out of order, so the current
 * state is read back from the provider.
 */
export async function onPaymentEvent(event: PaymentEvent): Promise<void> {
  if (event.type === 'unhandled') return;
  // Providers also report payments this shop did not start. Not an error.
  const order = findOrder(event.checkoutId);
  if (order) await refreshOrder(order, 'webhook');
}

The checkout component is app/checkout/checkout.tsx.

Which package do I use?

You are writingImport from
Routing rules, a catalog@tenderlane/core
The API route@tenderlane/core/server, plus @tenderlane/stripe/server or @tenderlane/polar/server
A React checkout@tenderlane/react, plus @tenderlane/stripe or @tenderlane/polar
A checkout without React@tenderlane/client
An adapter for another provider@tenderlane/core/adapters

Run the checks

pnpm check   # lint, build, typecheck, tests, package export checks

The tests mock the provider SDKs. No test in this repository talks to a live Stripe or Polar sandbox.

Next