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
| Browser | stripeProvider({ publishableKey, serverEndpoint }) from @tenderlane/stripe |
| Server | stripeServerAdapter({ secretKey, webhookSecret? }) from @tenderlane/stripe/server |
| React | StripePaymentElement from @tenderlane/stripe/react |
| Peer dependencies | stripe (server), @stripe/stripe-js and @stripe/react-stripe-js (inline flow only) |
hostedcreates a Checkout Session inpaymentmode and redirects to it.retrievereads a Checkout Session (cs_…) or a PaymentIntent (pi_…), with the payment method used. A session counts ascompleteonly when itspayment_statusispaid; finished but unpaid (a bank debit) isprocessing.inlinecreates a PaymentIntent, mounts the Payment Element with its client secret, andsubmit()callsstripe.confirmPayment.- A resolved item with
providerRefs.stripe.priceIdis sent as a Stripe Price; otherwise as inlineprice_datafrom the server’s catalog. - A PaymentIntent has one currency. A cart that mixes currencies is rejected.
- A route’s
paymentMethodsbecomepayment_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 asunhandled. - Stripe.js is loaded on demand, the first time an inline route needs it.
Polar
| Browser | polarProvider({ serverEndpoint }) from @tenderlane/polar |
| Server | polarServerAdapter({ accessToken, server, webhookSecret? }) from @tenderlane/polar/server |
| Peer dependency | @polar-sh/sdk (server) |
hostedonly.retrievereads the checkout. Onlysucceedediscomplete;confirmed(payment in progress) isprocessing. Polar does not report the payment method.- Polar sells products by id. Each item needs
providerRefs.polar.productId, whichcreatePolarCatalogsupplies. - Webhooks are verified with the Standard Webhooks scheme Polar uses, and only
checkout.updatedis 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_ERRORinstead 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:
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:
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:
defineBrowserProviderkeeps the id as a string literal, so routing rules that name it are type-checked.defineServerAdaptertypeshandle’sactionas the union ofactions.requestProviderActionposts 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:
- The browser entry imports no server SDK and holds no secret.
- The server adapter reads prices only from
payload.items. - If the provider cannot represent the cart, throw a
CatalogError. Do not approximate. - Return
status: 'complete'only when the provider says the payment is complete, fromhandleand fromretrieve. Useprocessingwhen the customer has paid and the money has not arrived, andopenwhen the customer still has something to do. - In
verifyWebhook, verify against the raw body and throwWebhookVerificationErrorwhen it fails. Report what you cannot interpret asunhandled; do not throw for it. - Replace
{CHECKOUT_ID}insuccessUrlwith 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.