@saasifier/billing-stripe
v0.1.1
Published
Stripe implementation of SaaSify's `BillingProvider` interface — plug this into `@saasifier/core` to bill subscriptions through Stripe.
Readme
@saasifier/billing-stripe
Stripe implementation of SaaSify's BillingProvider interface — plug this into @saasifier/core to bill subscriptions through Stripe.
Installation
npm install @saasifier/billing-stripe stripe
# or
pnpm add @saasifier/billing-stripe stripestripe is a peer/runtime dependency — this package expects you to construct and own the Stripe client yourself, so your API key and API version configuration stay in your app.
Overview
@saasifier/billing defines a provider-independent BillingProvider interface that @saasifier/core depends on; this package is the Stripe adapter for it, and the only place in SaaSify that imports the stripe SDK. It translates SaaSify's plan keys, organization ids, and subscription lifecycle calls into Stripe API calls, normalizes Stripe subscription objects and statuses back into SaaSify's provider-independent shape, and verifies + parses incoming Stripe webhooks into normalized BillingWebhookEvents.
Usage
import Stripe from "stripe";
import { createStripeBillingProvider } from "@saasifier/billing-stripe";
const stripe = new Stripe(process.env.STRIPE_SECRET_KEY!);
// Map SaaSify plan keys <-> Stripe Price ids (this mapping is a billing concern,
// not something saasify.config.ts plans need to know about).
const PLAN_TO_PRICE: Record<string, string> = {
starter: "price_1AbcStarter",
pro: "price_1AbcPro"
};
const PRICE_TO_PLAN = Object.fromEntries(
Object.entries(PLAN_TO_PRICE).map(([plan, price]) => [price, plan])
);
const billing = createStripeBillingProvider(stripe, {
webhookSecret: process.env.STRIPE_WEBHOOK_SECRET!,
priceIdForPlan: (planKey) => PLAN_TO_PRICE[planKey],
planKeyForPriceId: (priceId) => PRICE_TO_PLAN[priceId]
});
// Pass `billing` anywhere @saasifier/core expects a BillingProvider, e.g.:
const { customerId } = await billing.createCustomer({
organizationId: "org_123",
email: "[email protected]"
});
const { url } = await billing.createCheckout({
organizationId: "org_123",
customerId,
planKey: "pro",
successUrl: "https://app.example.com/billing/success",
cancelUrl: "https://app.example.com/billing/cancel"
});Webhook route
// e.g. an Express/Next.js route handler receiving the raw Stripe webhook body
const event = billing.verifyWebhook({
payload: rawRequestBody, // must be the raw, unparsed body string
signature: req.headers["stripe-signature"] as string
});
if (event) {
// hand event to @saasifier/core to update the organization's subscription state
}
// event === null means an authentically-signed Stripe event SaaSify doesn't model
// (e.g. "customer.updated") — acknowledge with HTTP 200 and do nothing further.API Reference
createStripeBillingProvider(stripe, options)
Returns a BillingProvider (from @saasifier/billing) backed by Stripe.
stripe: Stripe— aStripeclient instance you construct and own.options.webhookSecret: string— Stripe webhook signing secret (whsec_...), from the Dashboard orstripe listen.options.priceIdForPlan: (planKey: string) => string— maps a SaaSify plan key (e.g."pro") to the Stripe Price id billed for it.options.planKeyForPriceId: (priceId: string) => string— the inverse mapping, used to recover the plan key from a Stripe subscription/price object.
The returned provider implements the full BillingProvider interface: createCustomer, createCheckout, createSubscription, cancelSubscription, changeSubscription, getSubscription, createPortalSession, and verifyWebhook. Its name is "stripe".
mapStripeStatus(status: Stripe.Subscription.Status): SubscriptionStatus
Maps a Stripe subscription status onto SaaSify's provider-independent SubscriptionStatus set (trialing / active / past_due / cancelled / unpaid / incomplete). Two Stripe statuses have no direct equivalent and are documented approximations: incomplete_expired collapses into incomplete (the subscription never activated either way), and paused collapses into unpaid (billing is not currently succeeding).
StripeBillingProviderOptions
The options type accepted by createStripeBillingProvider — see above.
Implementing BillingProvider
This package is a concrete implementation of the BillingProvider interface exported by @saasifier/billing; @saasifier/core never imports stripe itself, only this interface, so @saasifier/billing-stripe can be swapped for another provider adapter (Paddle, Lemon Squeezy, a custom one) without touching core.
Organization tagging: every customer, checkout session, and subscription created through this adapter is tagged with
metadata.organizationId. Incoming webhooks and lookups (cancelSubscription,changeSubscription,getSubscription) read that metadata back to recover the organization id. If a Stripe customer or subscription is missingorganizationId(e.g. created outside SaaSify), the adapter throwsConfigurationError.Webhook verification:
verifyWebhookcallsstripe.webhooks.constructEvent(payload, signature, webhookSecret). A signature mismatch throwsWebhookVerificationError(from@saasifier/types) rather than returning a best-effort result. Recognized Stripe event types are mapped to SaaSify'sBillingEventType:| Stripe event | SaaSify event | | --- | --- | |
customer.subscription.created|subscription.created| |customer.subscription.updated|subscription.updated| |customer.subscription.deleted|subscription.cancelled| |invoice.payment_succeeded|payment.succeeded| |invoice.payment_failed|payment.failed| |invoice.created|invoice.created| |invoice.paid|invoice.paid|Any other Stripe event type verifies successfully but returns
null— callers should acknowledge it (HTTP 200) without further processing.
Required Stripe setup
- Create Prices in Stripe (Dashboard or API) for each SaaSify plan, and build the
priceIdForPlan/planKeyForPriceIdmaps from their ids. - Configure a webhook endpoint in the Stripe Dashboard (or via
stripe listen --forward-to ...for local development) pointing at your webhook route, subscribed at minimum tocustomer.subscription.*andinvoice.payment_succeeded/invoice.payment_failed. - Copy the endpoint's signing secret into
options.webhookSecret. - Ensure your webhook route passes the raw, unparsed request body to
verifyWebhook— Stripe's signature check will fail against a body that has been JSON-parsed and re-serialized.
