kavachOS
Authentication

Stripe

Payments and subscriptions with Stripe.

The Stripe plugin handles checkout sessions, billing portals, and subscription webhooks. It calls Stripe's REST API directly (no stripe npm package needed).

Setup

Get your keys

From Stripe Dashboard, copy your Secret Key. Under Webhooks, create an endpoint pointing to /api/kavach/auth/stripe/webhook and copy the Signing Secret.

Configure the plugin

import { createKavach } from 'kavachos';
import { stripe } from 'kavachos/auth';

const kavach = await createKavach({
  database: { provider: 'postgres', url: process.env.DATABASE_URL },
  plugins: [
    stripe({
      secretKey: process.env.STRIPE_SECRET_KEY,
      webhookSecret: process.env.STRIPE_WEBHOOK_SECRET,
      onSubscriptionChange: async (userId, sub) => {
        console.log(`User ${userId} subscription: ${sub.status}`);
      },
    }),
  ],
});

Usage

Create a checkout session

// From an authenticated endpoint
const result = await kavach.stripe.createCheckoutSession(userId, 'price_xxx', {
  successUrl: 'https://myapp.com/billing?success=true',
  cancelUrl: 'https://myapp.com/billing',
  trialDays: 14,
});
// Redirect user to result.url

Open the billing portal

const result = await kavach.stripe.createPortalSession(userId, 'https://myapp.com/settings');
// Redirect to result.url

Check subscription status

const sub = await kavach.stripe.getSubscription(userId);
if (sub?.status === 'active') {
  // User has an active subscription
}

Webhook events

The plugin handles these Stripe events automatically:

EventAction
checkout.session.completedLinks Stripe customer to user
customer.subscription.createdStores subscription status
customer.subscription.updatedUpdates status, price, period
customer.subscription.deletedMarks subscription canceled
invoice.payment_failedSets status to past_due

Webhook signatures are verified using HMAC-SHA256 with constant-time comparison. Stale timestamps (over 5 minutes) are rejected.

Endpoints

MethodPathAuthDescription
POST/auth/stripe/checkoutYesCreate checkout session
POST/auth/stripe/portalYesCreate billing portal
GET/auth/stripe/subscriptionYesGet subscription info
POST/auth/stripe/webhookNoStripe webhook (signature verified)

Database columns

The plugin adds these columns to the users table:

ColumnTypeDescription
stripe_customer_idtextStripe customer ID
stripe_subscription_idtextActive subscription ID
stripe_subscription_statustextactive, canceled, past_due, etc.
stripe_price_idtextCurrent price/plan ID
stripe_current_period_endtimestampWhen the current period ends
stripe_cancel_at_period_endbooleanWhether cancellation is scheduled

Set STRIPE_WEBHOOK_SECRET in production. Without it, webhook events cannot be verified and will be rejected.

On this page