Skip to main content
← Guides

Guide

Best Payment Integration Libraries for Node.js in 2026

Updated PkgPulse Team13 min read
0

Stripe, LemonSqueezy, and Paddle compared for accepting payments in Node.js apps. Merchant of record, global taxes, and which payment solution fits your SaaS.

Contents

TL;DR

Choose standard Stripe Payments when you want direct control over checkout and can manage your sales tax obligations. Choose Paddle when you want a merchant of record for a new SaaS product. Eligible digital-product businesses can also use Stripe Managed Payments. If you already sell through Lemon Squeezy, plan your migration before it stops processing payments and renewals.

Key Takeaways

  • Stripe Payments gives you direct control over checkout. Your business is the merchant of record for its own direct sales.
  • Stripe Managed Payments acts as merchant of record for eligible digital-product businesses.
  • Paddle acts as merchant of record and supports subscriptions and invoicing.
  • Lemon Squeezy has closed new sign-ups. Existing stores must migrate before processing ends.
  • Stripe Tax helps calculate and collect tax on a standard Stripe integration.

The Payment Stack Decision

Accepting payments sounds straightforward. In practice, it is one of the most consequential technology decisions a SaaS founder makes — one that affects revenue recovery, global expansion, tax compliance, and operational overhead for years.

The core question in 2026 is not just "which library has the best API?" but "do I want to be responsible for global tax compliance?" VAT collection in the EU, GST in Australia, sales tax in US states, JCT in Japan — the list of jurisdictions requiring tax registration grows every year. Getting this wrong can result in significant fines and back-payment obligations.

This guide compares direct processing with Stripe Payments and merchant-of-record billing with Paddle. It also covers maintenance for existing Lemon Squeezy stores during the wind-down. Decide which business will be the seller on the transaction before choosing an SDK.


Stripe: The Gold Standard Direct Processor

The examples below use the stripe Node.js SDK for standard Stripe Payments and Billing. When selling directly through your own Stripe account, your business is the merchant of record and remains responsible for applicable registration, collection, and remittance. Stripe Managed Payments is a separate offering in which Stripe acts as merchant of record for eligible digital-product businesses. Stripe Managed Payments

Use standard Payments if your team needs the checkout controls shown below and has a plan for sales tax and payment compliance in the markets where it sells.

npm install stripe
// Stripe — create a customer and subscription
import Stripe from 'stripe';

const stripe = new Stripe(process.env.STRIPE_SECRET_KEY!);

// Create a customer when user signs up
async function createStripeCustomer(userId: string, email: string, name: string) {
  const customer = await stripe.customers.create({
    email,
    name,
    metadata: { userId },  // Link Stripe customer to your user ID
  });

  await db.user.update({
    where: { id: userId },
    data: { stripeCustomerId: customer.id },
  });

  return customer;
}

// Create a subscription for an existing customer
async function createSubscription(customerId: string, priceId: string) {
  const subscription = await stripe.subscriptions.create({
    customer: customerId,
    items: [{ price: priceId }],
    payment_behavior: 'default_incomplete',
    expand: ['latest_invoice.payment_intent'],
  });

  return subscription;
}
// Stripe — hosted checkout session (recommended for most cases)
// app/api/checkout/route.ts
export async function POST(req: Request) {
  const { priceId, userId } = await req.json();
  const user = await getUser(userId);

  const session = await stripe.checkout.sessions.create({
    mode: 'subscription',
    payment_method_types: ['card'],
    line_items: [{ price: priceId, quantity: 1 }],
    success_url: `${process.env.APP_URL}/dashboard?success=true`,
    cancel_url: `${process.env.APP_URL}/pricing`,
    client_reference_id: userId,
    customer_email: user.email,
    metadata: { userId },
    billing_address_collection: 'required',
    // Stripe Tax: auto-calculate taxes (requires Tax setup in Dashboard)
    automatic_tax: { enabled: true },
  });

  return Response.json({ url: session.url });
}

Handling Subscription Update Webhooks

Webhooks are how Stripe communicates subscription lifecycle events to your application. The customer.subscription.updated event fires on plan changes, payment method updates, trial endings, and dunning (failed payment recovery). Your handler must be idempotent — Stripe may deliver the same event more than once.

// Stripe — webhook handler with signature verification
// app/api/webhook/stripe/route.ts
import Stripe from 'stripe';

const stripe = new Stripe(process.env.STRIPE_SECRET_KEY!);

export async function POST(req: Request) {
  const body = await req.text();
  const signature = req.headers.get('stripe-signature')!;

  let event: Stripe.Event;
  try {
    // constructEvent verifies the webhook signature — never skip this
    event = stripe.webhooks.constructEvent(
      body,
      signature,
      process.env.STRIPE_WEBHOOK_SECRET!
    );
  } catch (err) {
    return new Response(`Webhook Error: ${(err as Error).message}`, { status: 400 });
  }

  switch (event.type) {
    case 'checkout.session.completed': {
      const session = event.data.object as Stripe.Checkout.Session;
      await activateSubscription(
        session.client_reference_id!,
        session.subscription as string
      );
      break;
    }

    case 'customer.subscription.updated': {
      const subscription = event.data.object as Stripe.Subscription;
      // Fires on: plan change, trial end, payment method update, pause
      await updateSubscriptionStatus(subscription.id, subscription.status);
      break;
    }

    case 'customer.subscription.deleted': {
      const subscription = event.data.object as Stripe.Subscription;
      await cancelSubscription(subscription.id);
      break;
    }

    case 'invoice.payment_failed': {
      const invoice = event.data.object as Stripe.Invoice;
      await notifyPaymentFailed(invoice.customer as string);
      break;
    }
  }

  return new Response('OK');
}

Testing with stripe-cli

The Stripe CLI is the fastest way to test webhooks locally without deploying. It forwards events from Stripe's servers to your localhost and lets you trigger specific events on demand:

# Install Stripe CLI
brew install stripe/stripe-cli/stripe

# Login and forward webhooks to local server
stripe login
stripe listen --forward-to localhost:3000/api/webhook/stripe

# Trigger specific events for testing
stripe trigger customer.subscription.updated
stripe trigger invoice.payment_failed
stripe trigger checkout.session.completed

The CLI prints your webhook signing secret during stripe listen. Use that as STRIPE_WEBHOOK_SECRET in your .env.local. This lets you test the full payment and webhook flow locally without mocking.

Stripe Tax Add-on

Enable Stripe Tax for Checkout with automatic_tax: { enabled: true }. Configure your registrations and product tax codes so Stripe can calculate and collect tax where you've registered. Adding Stripe Tax to a direct sale through your own account leaves your business as merchant of record. Stripe Tax setup


LemonSqueezy: Merchant of Record for Indie SaaS

Lemon Squeezy stopped accepting new users and new store sign-ups on November 16, 2026. Existing stores must migrate before payment processing and subscription renewals end on March 31, 2027. Check eligibility for Stripe Managed Payments or choose a provider that supports your products and billing workflows. Lemon Squeezy migration guide

The checkout, webhook, and subscription examples in this section use @lemonsqueezy/lemonsqueezy.js to maintain an existing store while you prepare its migration.

npm install @lemonsqueezy/lemonsqueezy.js
// LemonSqueezy — create a checkout link
import { lemonSqueezySetup, createCheckout } from '@lemonsqueezy/lemonsqueezy.js';

lemonSqueezySetup({ apiKey: process.env.LEMONSQUEEZY_API_KEY! });

async function createLemonSqueezyCheckout(
  userId: string,
  variantId: number,
  userEmail: string
) {
  const { data, error } = await createCheckout(
    process.env.LEMONSQUEEZY_STORE_ID!,
    variantId,
    {
      checkoutData: {
        email: userEmail,
        custom: { userId },  // Passed back in webhook payload as meta.custom_data
      },
      productOptions: {
        redirectUrl: `${process.env.APP_URL}/dashboard?success=true`,
        receiptButtonText: 'Go to Dashboard',
      },
    }
  );

  if (error) throw new Error(error.message);
  return data?.data.attributes.url;
}
// LemonSqueezy — webhook handler
// app/api/webhook/lemonsqueezy/route.ts
import crypto from 'crypto';

export async function POST(req: Request) {
  const body = await req.text();
  const signature = req.headers.get('x-signature')!;

  // Verify HMAC-SHA256 signature
  const hash = crypto
    .createHmac('sha256', process.env.LEMONSQUEEZY_WEBHOOK_SECRET!)
    .update(body)
    .digest('hex');

  if (hash !== signature) {
    return new Response('Invalid signature', { status: 401 });
  }

  const event = JSON.parse(body);
  const eventName: string = event.meta.event_name;
  const customData = event.meta.custom_data;

  switch (eventName) {
    case 'order_created':
      await activateUser(customData.userId, event.data.id);
      break;

    case 'subscription_created':
      await createSubscription(customData.userId, event.data);
      break;

    case 'subscription_updated':
      await updateSubscription(event.data.id, event.data.attributes);
      break;

    case 'subscription_cancelled':
      // User cancelled — still active until ends_at
      await scheduleSubscriptionCancellation(
        event.data.id,
        event.data.attributes.ends_at
      );
      break;

    case 'subscription_payment_failed':
      await notifyPaymentFailed(customData.userId);
      break;
  }

  return new Response('OK');
}

Getting Subscription Status from LemonSqueezy

Use this lookup when maintaining or migrating subscriptions from an existing store.

// LemonSqueezy — get subscription status
import { getSubscription } from '@lemonsqueezy/lemonsqueezy.js';

async function checkSubscriptionStatus(subscriptionId: string) {
  const { data, error } = await getSubscription(subscriptionId);

  if (error) throw new Error(error.message);

  const attrs = data?.data.attributes;
  return {
    status: attrs?.status,     // 'active', 'paused', 'cancelled', 'expired'
    renewsAt: attrs?.renews_at,
    endsAt: attrs?.ends_at,
    planName: attrs?.product_name,
  };
}

Paddle: Merchant of Record with B2B Focus

Paddle acts as merchant of record and handles sales tax collection and remittance. It also supports recurring billing, localized checkout, and invoicing for B2B customers. Confirm the invoicing and seat-based billing workflows you need before switching providers. Paddle billing and pricing

The checkout example uses Paddle.js in the browser. For server-side Paddle Billing API calls, use the official Paddle Node.js SDK.

// Paddle.js — initialize and open a checkout
// Add to your layout: <script src="https://cdn.paddle.com/paddle/v2/paddle.js"></script>

Paddle.Initialize({
  token: process.env.NEXT_PUBLIC_PADDLE_CLIENT_TOKEN,
  eventCallback: function(data) {
    if (data.name === 'checkout.completed') {
      const transactionId = data.data.transaction_id;
      window.location.href = `/dashboard?transaction=${transactionId}`;
    }
  }
});

// Open checkout from a button
function openCheckout(priceId, userId) {
  Paddle.Checkout.open({
    items: [{ priceId, quantity: 1 }],
    customData: { userId },
  });
}
// Paddle — webhook handler
// app/api/webhook/paddle/route.ts
import crypto from 'crypto';

export async function POST(req: Request) {
  const body = await req.text();
  const signatureHeader = req.headers.get('paddle-signature')!;

  const parts = Object.fromEntries(
    signatureHeader.split(';').map(p => p.split('=') as [string, string])
  );

  const expectedHash = crypto
    .createHmac('sha256', process.env.PADDLE_WEBHOOK_SECRET!)
    .update(`${parts.ts}:${body}`)
    .digest('hex');

  if (expectedHash !== parts.h1) {
    return new Response('Invalid signature', { status: 401 });
  }

  const event = JSON.parse(body);

  switch (event.event_type) {
    case 'transaction.completed':
      await handleTransactionCompleted(event.data);
      break;
    case 'subscription.activated':
      await handleSubscriptionActivated(event.data);
      break;
    case 'subscription.canceled':
      await handleSubscriptionCanceled(event.data);
      break;
  }

  return new Response('OK');
}

Stripe vs MoR: The Core Decision

The most important payment architecture decision is whether you want to be the Merchant of Record or delegate that responsibility. This choice has implications that compound over time as your product expands internationally.

Choose standard Stripe Payments for direct sales when your team wants to control checkout and handle its tax obligations. For a Connect marketplace, identify the merchant of record for the charge flow you use. It can be the platform or the connected account. Stripe Connect merchant-of-record guide

Choose a merchant of record when you want the provider to be the legal seller and handle applicable transaction taxes. Evaluate Paddle for a new SaaS product. Check product and business eligibility before choosing Stripe Managed Payments. For an existing Lemon Squeezy store, verify that the destination supports your active subscriptions, currencies, and payment methods.

Compare costs using your own transaction amounts, payment methods, customer locations, and billing needs. Include separate billing and tax charges where they apply, plus the cost of registrations and filings your team would still handle.


Webhook Security: A Universal Pattern

All three payment providers use HMAC-SHA256 signature verification for webhooks. The pattern is always the same: compute a signature from the raw request body using a shared secret, then compare it to the signature in the request headers. Never skip this verification — unsigned webhooks would allow anyone to trigger subscription activations or cancellations in your system.

The critical implementation detail: always read the raw request body before any JSON parsing. Body parsers can subtly modify the byte representation in ways that break signature verification. In Next.js App Router, await req.text() returns the raw body. Parse it yourself with JSON.parse() after verifying the signature.

// The universal webhook verification pattern
const rawBody = await req.text();  // Read raw body FIRST
const signature = req.headers.get('x-signature')!;

const expectedSig = crypto
  .createHmac('sha256', secret)
  .update(rawBody)
  .digest('hex');

if (expectedSig !== signature) {
  return new Response('Unauthorized', { status: 401 });
}

const event = JSON.parse(rawBody);  // Parse AFTER verification

Stripe's stripe.webhooks.constructEvent(body, sig, secret) wraps this pattern for you. LemonSqueezy and Paddle require the manual approach shown above.


Testing Webhooks Locally

One of the most common friction points when building payment integrations is testing webhook events during development. Without a publicly accessible server, the payment provider's webhook system can't reach your localhost. The standard solutions:

Stripe CLI is the gold standard for local webhook testing. It creates a persistent tunnel, forwards production-equivalent events to your local server, and lets you trigger specific event types on demand:

brew install stripe/stripe-cli/stripe
stripe login
stripe listen --forward-to localhost:3000/api/webhook/stripe
# In another terminal:
stripe trigger checkout.session.completed
stripe trigger customer.subscription.deleted

For LemonSqueezy and Paddle, there's no official CLI. Use ngrok (free tier) or Cloudflare Tunnel to expose a public URL that forwards to localhost. Configure that URL as your webhook endpoint in each provider's dashboard during development.

For automated testing, mock the webhook handler directly by calling it with a fake event object, bypassing the signature verification step (or using a test secret). Unit test the business logic functions (activateSubscription, cancelSubscription) separately from the webhook routing.

Subscription State Modeling

Regardless of which provider you use, your database subscription model needs to track the same core concepts. A robust subscriptions table typically includes: the provider-specific subscription ID, the current status, the period end date (for cancellation-at-period-end logic), and the plan or price ID.

The most common bug in payment integrations is confusing canceled with "access denied." In all three providers, when a user cancels, their subscription typically remains active until the end of the current billing period. canceled in Stripe means the subscription won't renew — the user can still use the product until current_period_end. Your access check should be:

// Correct subscription access check:
function hasActiveAccess(subscription: UserSubscription): boolean {
  if (subscription.status === 'active') return true;
  if (subscription.status === 'trialing') return true;
  if (subscription.status === 'past_due') return true;   // Grace period during retry
  if (subscription.status === 'canceled') {
    // Still have access until period ends:
    return new Date() < new Date(subscription.currentPeriodEnd);
  }
  return false;
}

The past_due state is also frequently mishandled. Stripe's Smart Retries will automatically retry a failed payment over several days before moving to canceled. During this window the subscription is past_due — the user's payment failed but they haven't explicitly canceled. Most applications should maintain access during this window (possibly showing a warning banner) rather than immediately locking the user out.

Free Trials

All three providers support free trials. With Stripe, you add trial_period_days to the subscription creation call or to the Price object in the Dashboard. The subscription starts in trialing status and transitions to active when the trial ends and the first payment succeeds (or canceled/past_due if it fails).

Paddle supports trials through the dashboard or API. When migrating an existing Lemon Squeezy store, check how the destination will handle subscriptions still on trial. Decide whether customers must add a payment method before starting a trial, then test first billing and cancellation in a sandbox.

For B2B SaaS, a 14-day free trial with a credit card requirement is the most common pattern. For self-serve PLG products, a freemium tier often outperforms a time-limited trial.


Package Health Comparison

Servicenpm PackageMerchant of RecordPricing or StatusSubscriptionsBest For
Standard Stripe Payments and BillingstripeYour business for its own direct salesStandard Payments and Billing ratesYesDirect sales and custom checkout
Lemon Squeezy@lemonsqueezy/lemonsqueezy.jsLemon Squeezy for existing storesWind-down timelineExisting stores during wind-downMaintenance and migration
Paddle Billing@paddle/paddle-node-sdkPaddleCheckout ratesYesB2B SaaS, annual contracts, invoicing

When to Choose

Standard Stripe Payments fits teams selling directly through their own Stripe account. For a marketplace using Connect, check the merchant-of-record assignment for the chosen charge type and configuration. Test checkout and webhook behavior in a sandbox.

Lemon Squeezy is a migration project for current stores. Choose a destination, test checkout and subscription events, and move active subscriptions before the processing deadline.

Paddle is a merchant-of-record option for new B2B SaaS products with annual contracts, invoicing requirements, or seat-based pricing. Stripe Managed Payments is another option for eligible digital-product businesses.