@saas-toolkit/payment-kit
v0.1.0
Published
Universal payment service abstraction supporting multiple providers (Stripe, Razorpay, PayPal)
Maintainers
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-layerProvider Dependencies
Install the SDK for your chosen provider:
# For Stripe
npm install stripe
# For Razorpay
npm install razorpayQuick 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 liveCreating 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); // immediatelyCustomer 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 providercreateFromEnvironment()- Create from environment variablesdetectProvider(apiKey)- Auto-detect provider from API key formatcreateFromApiKey(apiKey, config?)- Create by auto-detecting provider
PaymentService
Base class with methods all providers implement.
Checkout & Sessions
createCheckoutSession(planId, userId, options?)- Create payment sessiongetCheckoutSession(sessionId)- Get session details
Subscription Management
createSubscription(customerId, planId, options?)- Create subscriptiongetSubscription(subscriptionId)- Get subscription detailsupdateSubscription(subscriptionId, updates)- Update subscriptioncancelSubscription(subscriptionId, immediately?)- Cancel subscriptiongetCustomerSubscriptions(customerId)- List customer subscriptions
Customer Management
createCustomer(userId, email, name?, metadata?)- Create customergetCustomer(customerId)- Get customer detailsupdateCustomer(customerId, updates)- Update customerfindCustomerByUserId(userId)- Find customer by internal user ID
Plans & Pricing
getPlans()- List all available plansgetPlan(planId)- Get specific plan details
Webhooks
verifyWebhook(payload, signature)- Verify webhook signaturehandleWebhookEvent(event)- Process webhook eventgetSupportedWebhookEvents()- 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
