Docs / Providers and adapters
Docs / Providers and adapters v0.1.0-alpha.1

Providers and adapters

What the Stripe and Polar adapters do, and how to write an adapter for another provider with the same API they use.

Stripe

BrowserstripeProvider({ publishableKey, serverEndpoint }) from @tenderlane/stripe
ServerstripeServerAdapter({ secretKey, webhookSecret? }) from @tenderlane/stripe/server
ReactStripePaymentElement from @tenderlane/stripe/react
Peer dependenciesstripe (server), @stripe/stripe-js and @stripe/react-stripe-js (inline flow only)
  • hosted creates a Checkout Session in payment mode and redirects to it.
  • retrieve reads a Checkout Session (cs_…) or a PaymentIntent (pi_…), with the payment method used. A session counts as complete only when its payment_status is paid; finished but unpaid (a bank debit) is processing.
  • inline creates a PaymentIntent, mounts the Payment Element with its client secret, and submit() calls stripe.confirmPayment.
  • A resolved item with providerRefs.stripe.priceId is sent as a Stripe Price; otherwise as inline price_data from the server’s catalog.
  • A PaymentIntent has one currency. A cart that mixes currencies is rejected.
  • A route’s paymentMethods become payment_method_types. Without them, Stripe’s automatic payment methods apply.
  • Webhooks are verified with Stripe’s own constructEventAsync. Checkout Session and PaymentIntent events are interpreted; the rest arrive as unhandled.
  • Stripe.js is loaded on demand, the first time an inline route needs it.

Polar

BrowserpolarProvider({ serverEndpoint }) from @tenderlane/polar
ServerpolarServerAdapter({ accessToken, server, webhookSecret? }) from @tenderlane/polar/server
Peer dependency@polar-sh/sdk (server)
  • hosted only.
  • retrieve reads the checkout. Only succeeded is complete; confirmed (payment in progress) is processing. Polar does not report the payment method.
  • Polar sells products by id. Each item needs providerRefs.polar.productId, which createPolarCatalog supplies.
  • Webhooks are verified with the Standard Webhooks scheme Polar uses, and only checkout.updated is interpreted. The adapter reads three fields of the payload instead of validating all of it, so a new field on Polar’s side does not turn into rejected webhooks.
  • One product, quantity one, per checkout. Anything else is rejected with a CATALOG_ERROR instead of being charged as something it is not.

Writing an adapter

An adapter is two objects. The demo provider in the example is a complete one, written only with @tenderlane/core/adapters, the entry point the Stripe and Polar adapters use.

The browser half declares what the provider can do and how to submit:

examples/react-checkout-multi-psp/app/demo-psp/browser.ts from the repository, typechecked in CI
import { defineBrowserProvider, requestProviderAction } from '@tenderlane/core/adapters';

/**
 * Browser half of the demo provider: a complete provider adapter written with
 * `@tenderlane/core/adapters`, the same entry point the Stripe and Polar
 * adapters use. It is not a payment provider and moves no money.
 */
export function demoProvider(options: { serverEndpoint: string }) {
  return defineBrowserProvider({
    id: 'demo',
    capabilities: { flows: ['hosted'], paymentMethods: ['card'] },
    getAvailablePaymentMethods: () => [
      { id: 'card', label: 'Demo card', type: 'card', provider: 'demo' },
    ],
    async submit(input, route) {
      const result = await requestProviderAction({
        endpoint: options.serverEndpoint,
        provider: 'demo',
        action: 'checkout',
        input,
        route,
      });
      if (result.url) window.location.href = result.url;
      return result;
    },
  });
}

The server half makes the provider calls: handle creates the checkout from payload.items, which the server’s catalog already priced; the optional retrieve reads its state back, and the optional verifyWebhook checks a webhook’s signature and says what it means:

examples/react-checkout-multi-psp/app/demo-psp/server.ts from the repository, typechecked in CI
import {
  CHECKOUT_ID_PLACEHOLDER,
  ProviderError,
  WebhookVerificationError,
  defineServerAdapter,
} from '@tenderlane/core/adapters';
import { findDemoSession, saveDemoSession } from './sessions';
import { DEMO_SIGNATURE_HEADER, signDemoPayload } from './signature';

/**
 * Server half of the demo provider. A real adapter calls the provider's API with a
 * secret key here. This one keeps its checkouts in memory and links to a page
 * inside the example (`/demo-psp/checkout`) that stands in for a hosted
 * checkout. It implements all three parts of the contract: create, look up,
 * and verify a webhook.
 *
 * `payload.items` was priced by the server's catalog. The amount the demo
 * provider charges comes from there, not from the browser.
 */
export function demoServerAdapter() {
  return defineServerAdapter({
    id: 'demo',
    actions: ['checkout'],

    async handle(_action, payload) {
      const id = `demo_${crypto.randomUUID()}`;
      saveDemoSession({
        id,
        amount: payload.items.reduce((sum, item) => sum + item.unitAmount * item.quantity, 0),
        currency: payload.items[0]?.currency ?? 'usd',
        description: payload.items.map((item) => item.name).join(', '),
        // The provider fills in the checkout id, as Stripe and Polar do.
        successUrl: payload.successUrl.replaceAll(CHECKOUT_ID_PLACEHOLDER, id),
        cancelUrl: payload.cancelUrl,
        paid: false,
      });

      const url = new URL('/demo-psp/checkout', payload.successUrl);
      url.searchParams.set('session', id);
      return { provider: 'demo', id, status: 'open', url: url.toString() };
    },

    async retrieve(id) {
      const session = findDemoSession(id);
      if (!session) throw new ProviderError(`The demo provider has no checkout "${id}".`, 'demo');
      return {
        provider: 'demo',
        id,
        status: session.paid ? 'complete' : 'open',
        amountTotal: session.amount,
        currency: session.currency,
      };
    },

    async verifyWebhook(request) {
      // Read as text: the signature covers the exact bytes that were sent.
      const body = await request.text();
      if (request.headers.get(DEMO_SIGNATURE_HEADER) !== (await signDemoPayload(body))) {
        throw new WebhookVerificationError('The demo provider signature did not verify.', 'demo');
      }
      const event: unknown = JSON.parse(body);
      const { id, type, checkout } = event as Record<string, unknown>;
      const base = { provider: 'demo', eventId: String(id), providerEventType: String(type) };
      return type === 'checkout.paid' && typeof checkout === 'string'
        ? { ...base, type: 'payment.succeeded', checkoutId: checkout }
        : { ...base, type: 'unhandled' };
    },
  });
}

What the helpers do:

  • defineBrowserProvider keeps the id as a string literal, so routing rules that name it are type-checked.
  • defineServerAdapter types handle’s action as the union of actions.
  • requestProviderAction posts one action to the app’s handler in the wire format it expects, and validates the response.

For an inline flow, add createSession(input, route) to the browser provider, returning { flow, clientSecret, sessionId }, and a component that mounts the provider’s element with that secret. packages/stripe is the reference.

Rules for an adapter:

  1. The browser entry imports no server SDK and holds no secret.
  2. The server adapter reads prices only from payload.items.
  3. If the provider cannot represent the cart, throw a CatalogError. Do not approximate.
  4. Return status: 'complete' only when the provider says the payment is complete, from handle and from retrieve. Use processing when the customer has paid and the money has not arrived, and open when the customer still has something to do.
  5. In verifyWebhook, verify against the raw body and throw WebhookVerificationError when it fails. Report what you cannot interpret as unhandled; do not throw for it.
  6. Replace {CHECKOUT_ID} in successUrl with the checkout id, or with the provider’s own placeholder for it.

The repository’s e2e test runs one checkout through Stripe, Polar and a third adapter written this way, against mocked provider SDKs.