npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2026 – Pkg Stats / Ryan Hefner

@saas-toolkit/payment-kit

v0.1.0

Published

Universal payment service abstraction supporting multiple providers (Stripe, Razorpay, PayPal)

Readme

@saas-toolkit/payment-kit

Universal payment service abstraction supporting multiple providers (Stripe, Razorpay, PayPal) with a consistent API.

Features

  • Multiple Providers: Stripe, Razorpay (more coming soon)
  • Unified API: Same interface regardless of provider
  • Type Safety: Full TypeScript support
  • Error Handling: Comprehensive error handling with retry logic
  • Subscription Management: Full subscription lifecycle
  • One-time Payments: Support for single transactions
  • Webhook Handling: Secure webhook verification
  • Health Checks: Built-in monitoring

Installation

npm install @saas-toolkit/payment-kit @saas-toolkit/service-layer

Provider Dependencies

Install the SDK for your chosen provider:

# For Stripe
npm install stripe

# For Razorpay
npm install razorpay

Quick Start

Basic Usage

import { PaymentServiceFactory } from '@saas-toolkit/payment-kit';

// Create from environment variables
const paymentService = PaymentServiceFactory.createFromEnvironment();

// Or create with specific provider
const stripeService = PaymentServiceFactory.create('stripe', {
  apiKey: 'sk_test_...',
  mode: 'test',
});

Environment Variables

PAYMENT_PROVIDER=stripe          # or razorpay
PAYMENT_API_KEY=sk_test_...     # Your provider API key
PAYMENT_WEBHOOK_SECRET=whsec_... # Webhook signing secret
PAYMENT_MODE=test               # test or live

Creating Checkout Sessions

// Create a checkout session for a subscription
const session = await paymentService.createCheckoutSession(
  'pro_monthly', // plan ID
  'user_123', // user ID
  {
    successUrl: 'https://yourapp.com/success',
    cancelUrl: 'https://yourapp.com/cancel',
    customerEmail: '[email protected]',
  }
);

// Redirect user to session.url
window.location.href = session.url;

Managing Subscriptions

// Create a subscription
const subscription = await paymentService.createSubscription(
  'cus_customer123', // customer ID
  'pro_monthly', // plan ID
  {
    trialDays: 14,
    metadata: { source: 'website' },
  }
);

// Cancel a subscription
await paymentService.cancelSubscription('sub_123', false); // at period end
await paymentService.cancelSubscription('sub_123', true); // immediately

Customer Management

// Create a customer
const customerId = await paymentService.createCustomer(
  'user_123', // internal user ID
  '[email protected]', // email
  'John Doe', // name (optional)
  { source: 'signup' } // metadata (optional)
);

// Get customer details
const customer = await paymentService.getCustomer(customerId);

Webhook Handling

// Verify and process webhooks
app.post(
  '/webhooks/payment',
  express.raw({ type: 'application/json' }),
  async (req, res) => {
    const signature =
      req.headers['stripe-signature'] || req.headers['x-razorpay-signature'];

    try {
      const event = paymentService.verifyWebhook(req.body, signature);
      await paymentService.handleWebhookEvent(event);

      res.json({ received: true });
    } catch (error) {
      console.error('Webhook error:', error);
      res.status(400).send('Webhook verification failed');
    }
  }
);

API Reference

PaymentServiceFactory

Static factory methods for creating payment services.

Methods

  • create(provider, config) - Create service with specific provider
  • createFromEnvironment() - Create from environment variables
  • detectProvider(apiKey) - Auto-detect provider from API key format
  • createFromApiKey(apiKey, config?) - Create by auto-detecting provider

PaymentService

Base class with methods all providers implement.

Checkout & Sessions

  • createCheckoutSession(planId, userId, options?) - Create payment session
  • getCheckoutSession(sessionId) - Get session details

Subscription Management

  • createSubscription(customerId, planId, options?) - Create subscription
  • getSubscription(subscriptionId) - Get subscription details
  • updateSubscription(subscriptionId, updates) - Update subscription
  • cancelSubscription(subscriptionId, immediately?) - Cancel subscription
  • getCustomerSubscriptions(customerId) - List customer subscriptions

Customer Management

  • createCustomer(userId, email, name?, metadata?) - Create customer
  • getCustomer(customerId) - Get customer details
  • updateCustomer(customerId, updates) - Update customer
  • findCustomerByUserId(userId) - Find customer by internal user ID

Plans & Pricing

  • getPlans() - List all available plans
  • getPlan(planId) - Get specific plan details

Webhooks

  • verifyWebhook(payload, signature) - Verify webhook signature
  • handleWebhookEvent(event) - Process webhook event
  • getSupportedWebhookEvents() - List supported webhook types

Supported Providers

Stripe

  • ✅ Checkout Sessions
  • ✅ Plans & Pricing
  • 🔄 Subscriptions (in progress)
  • 🔄 Customers (in progress)
  • 🔄 Webhooks (in progress)

Razorpay

  • 🔄 Full implementation (coming soon)
  • Focus on Indian market
  • INR currency support

PayPal

  • 📋 Planned for future release

Error Handling

The package provides structured error handling:

import { PaymentError } from '@saas-toolkit/payment-kit';

try {
  const session = await paymentService.createCheckoutSession(planId, userId);
} catch (error) {
  if (error instanceof PaymentError) {
    console.error('Payment error:', error.code, error.message);
    console.error('Error type:', error.type);
    console.error('Status code:', error.statusCode);
    console.error('Details:', error.details);
  }
}

Health Checks

// Check if payment service is healthy
const isHealthy = await paymentService.isHealthy();

// Get service capabilities
const capabilities = paymentService.getCapabilities();
console.log('Supported currencies:', capabilities.supportedCurrencies);

Examples

See the examples directory for complete usage examples including:

  • Basic checkout flow
  • Subscription management
  • Webhook handling
  • Error handling patterns

License

MIT