@taloon/stripe-middleware
v1.0.0
Published
Express middlewares for Stripe Checkout integration with callback-based webhook handling
Readme
@taloon/stripe-middleware
Express middlewares for Stripe Checkout integration with callback-based webhook handling.
Features
- Middleware-based - Clean separation of Stripe logic from business logic
- Callback pattern - Type-safe callbacks for each Stripe event
- Singleton config - Configure once, use everywhere
- Type-safe - Full TypeScript support with declaration files
- Secure - Built-in webhook signature verification
Installation
pnpm add @taloon/stripe-middlewareQuick Start
import express from 'express';
import { StripeMiddleware } from '@taloon/stripe-middleware';
const app = express();
// Configure once at startup
StripeMiddleware.configure({
secretKey: process.env.STRIPE_SECRET_KEY!,
webhookSecret: process.env.STRIPE_WEBHOOK_SECRET!,
currency: 'usd',
});
// Webhook (MUST be before express.json())
app.post('/webhook',
express.raw({ type: 'application/json' }),
StripeMiddleware.webhook({
onChargeSucceeded: async ({ charge, metadata, customerEmail }) => {
console.log(`Payment ${charge.id} succeeded from ${customerEmail}`);
// Handle successful payment
},
onChargeFailed: async ({ charge }) => {
console.log(`Payment ${charge.id} failed`);
},
})
);
app.use(express.json());
// Checkout
app.post('/checkout',
StripeMiddleware.createCheckout({
successUrl: 'https://yourapp.com/success?session_id={CHECKOUT_SESSION_ID}',
cancelUrl: 'https://yourapp.com/cancel',
}),
(req, res) => {
res.json({ url: res.locals.stripeCheckout.paymentUrl });
}
);
app.listen(3000);API
StripeMiddleware.configure(config)
Initialize the middleware once at application startup.
StripeMiddleware.configure({
secretKey: string; // sk_test_* or sk_live_*
webhookSecret: string; // whsec_*
currency?: string; // Default: 'usd'
});StripeMiddleware.createCheckout(options)
Creates a Stripe Checkout session middleware.
Options:
{
successUrl: string;
cancelUrl: string;
getSuccessUrl?: (req: Request) => string; // Dynamic URL
getCancelUrl?: (req: Request) => string;
}Request body:
{
amount: number; // Amount in dollars (converted to cents)
charge: string; // Charge type identifier
serviceName?: string; // Product name shown in Stripe
metadata?: Record<string, string>;
}Response (res.locals.stripeCheckout):
{
session: Stripe.Checkout.Session;
sessionId: string;
paymentUrl: string;
}StripeMiddleware.webhook(callbacks)
Validates signatures and executes callbacks for Stripe events.
Available callbacks:
| Callback | Event |
|----------|-------|
| onChargeSucceeded | charge.succeeded |
| onChargeFailed | charge.failed |
| onChargeRefunded | charge.refunded |
| onChargeUpdated | charge.updated |
| onChargeDisputed | charge.dispute.created |
| onCheckoutCompleted | checkout.session.completed |
| onCheckoutExpired | checkout.session.expired |
| onCheckoutAsyncPaymentSucceeded | checkout.session.async_payment_succeeded |
| onCheckoutAsyncPaymentFailed | checkout.session.async_payment_failed |
Callback payloads:
// Charge events
interface ChargeEventPayload {
charge: Stripe.Charge;
metadata: Record<string, string>;
customerEmail: string | null;
}
// Checkout session events
interface CheckoutSessionEventPayload {
session: Stripe.Checkout.Session;
metadata: Record<string, string>;
customerEmail: string | null;
}Documentation
See the docs/ directory for detailed documentation:
Local Development
# Install Stripe CLI and login
stripe login
# Forward webhooks
stripe listen --forward-to localhost:3000/webhook
# Use the webhook secret from output
STRIPE_WEBHOOK_SECRET=whsec_... npm startLicense
MIT
