saas-payments
A comprehensive tool for integrating Stripe billing, subscriptions, and payment management into SaaS applications.
Install
mkdir -p .claude/skills/saas-payments && curl -L -o skill.zip "https://agentskills.codes/api/skills/download/17448" && unzip -o skill.zip -d .claude/skills/saas-payments && rm skill.zipInstalls to .claude/skills/saas-payments
Activation
This is the description your AI agent reads to decide when to run this skill — the better it matches your request, the more reliably it fires.
Implement production-ready payment processing with Stripe including one-time payments, recurring subscriptions, customer portal, metered billing, and webhook handling. This skill covers the complete billing lifecycle from checkout through subscription management.Key capabilities
- →Implement one-time product purchases using Stripe Checkout
- →Set up recurring subscription plans with trial periods
- →Create customer self-service portals for billing management
- →Handle Stripe webhooks to sync subscription state
- →Implement usage-based/metered billing for API products
How it works
This skill integrates Stripe for payment processing by creating checkout sessions, managing subscriptions, setting up customer portals, and handling webhooks to keep subscription states synchronized.
Inputs & outputs
When to use saas-payments
- →Implementing one-time payments
- →Adding subscription tiers
- →Creating usage-based billing
- →Setting up customer billing portals
About this skill
SaaS Payments & Stripe Integration
Capability
Implement production-ready payment processing with Stripe including one-time payments, recurring subscriptions, customer portal, metered billing, and webhook handling. This skill covers the complete billing lifecycle from checkout through subscription management.
Use Cases
- One-time product purchases with Checkout
- Subscription plans with monthly/yearly billing
- Customer self-service portal for billing management
- Usage-based/metered billing for API products
- Invoice generation and payment tracking
- Handling failed payments and dunning
- Upgrading/downgrading subscription plans
Patterns
Stripe Checkout for One-Time Payments
When to use: Single purchases, credits, one-time fees
Implementation: Create Checkout session server-side, redirect customer to Stripe-hosted page.
// Create checkout session for one-time payment
async function createCheckoutSession(userId: string, priceId: string, quantity = 1) {
// Get or create Stripe customer
const customer = await getOrCreateStripeCustomer(userId);
const session = await stripe.checkout.sessions.create({
customer: customer.id,
mode: 'payment',
line_items: [
{
price: priceId, // price_xxx from Stripe Dashboard
quantity,
},
],
success_url: `${process.env.APP_URL}/checkout/success?session_id={CHECKOUT_SESSION_ID}`,
cancel_url: `${process.env.APP_URL}/checkout/cancel`,
metadata: {
userId, // Store for webhook processing
},
// Enable invoice for one-time payments
invoice_creation: {
enabled: true,
},
});
return { url: session.url };
}
// Get or create Stripe customer linked to user
async function getOrCreateStripeCustomer(userId: string) {
const user = await db.user.findUnique({ where: { id: userId } });
if (user.stripeCustomerId) {
return await stripe.customers.retrieve(user.stripeCustomerId);
}
const customer = await stripe.customers.create({
email: user.email,
name: user.name,
metadata: {
userId,
},
});
await db.user.update({
where: { id: userId },
data: { stripeCustomerId: customer.id },
});
return customer;
}
Subscription Checkout
When to use: Recurring monthly/yearly subscriptions
Implementation: Create subscription checkout session with trial period support.
// Create subscription checkout
async function createSubscriptionCheckout(userId: string, priceId: string) {
const customer = await getOrCreateStripeCustomer(userId);
// Check if already subscribed
const existingSubscriptions = await stripe.subscriptions.list({
customer: customer.id,
status: 'active',
limit: 1,
});
if (existingSubscriptions.data.length > 0) {
// Redirect to customer portal for upgrades
return createPortalSession(userId);
}
const session = await stripe.checkout.sessions.create({
customer: customer.id,
mode: 'subscription',
line_items: [
{
price: priceId,
quantity: 1,
},
],
success_url: `${process.env.APP_URL}/dashboard?upgraded=true`,
cancel_url: `${process.env.APP_URL}/pricing`,
subscription_data: {
trial_period_days: 14, // Optional trial
metadata: {
userId,
},
},
// Allow promotion codes
allow_promotion_codes: true,
// Collect billing address for tax
billing_address_collection: 'required',
// Enable automatic tax calculation
automatic_tax: { enabled: true },
});
return { url: session.url };
}
Customer Portal
When to use: Allow customers to manage their own billing
Implementation: Create portal session for subscription management.
// Create customer portal session
async function createPortalSession(userId: string) {
const user = await db.user.findUnique({ where: { id: userId } });
if (!user.stripeCustomerId) {
throw new Error('No billing account found');
}
const session = await stripe.billingPortal.sessions.create({
customer: user.stripeCustomerId,
return_url: `${process.env.APP_URL}/dashboard/billing`,
});
return { url: session.url };
}
Portal Configuration (via Stripe Dashboard > Settings > Billing > Customer Portal):
- Enable subscription cancellation
- Enable plan switching
- Enable payment method updates
- Enable invoice history
- Configure cancellation reasons
Webhook Handling
When to use: Process Stripe events to sync subscription state
Implementation: Verify webhook signature, handle events idempotently.
// Webhook handler - CRITICAL for subscription state
async function handleWebhook(request: Request) {
const sig = request.headers.get('stripe-signature');
const body = await request.text();
// Verify webhook signature - NEVER SKIP THIS
let event;
try {
event = stripe.webhooks.constructEvent(
body,
sig,
process.env.STRIPE_WEBHOOK_SECRET
);
} catch (err) {
console.error('Webhook signature verification failed:', err.message);
return new Response('Invalid signature', { status: 400 });
}
// Handle event idempotently
const idempotencyKey = event.id;
const processed = await db.processedWebhook.findUnique({
where: { eventId: idempotencyKey },
});
if (processed) {
return new Response('Already processed', { status: 200 });
}
try {
switch (event.type) {
case 'checkout.session.completed':
await handleCheckoutComplete(event.data.object);
break;
case 'customer.subscription.created':
case 'customer.subscription.updated':
await handleSubscriptionChange(event.data.object);
break;
case 'customer.subscription.deleted':
await handleSubscriptionCanceled(event.data.object);
break;
case 'invoice.payment_failed':
await handlePaymentFailed(event.data.object);
break;
case 'invoice.payment_succeeded':
await handlePaymentSucceeded(event.data.object);
break;
}
// Mark as processed
await db.processedWebhook.create({
data: {
eventId: idempotencyKey,
type: event.type,
processedAt: new Date(),
},
});
return new Response('OK', { status: 200 });
} catch (err) {
console.error('Webhook processing error:', err);
return new Response('Processing error', { status: 500 });
}
}
// Handle subscription state changes
async function handleSubscriptionChange(subscription: Stripe.Subscription) {
let userId = subscription.metadata.userId;
if (!userId) {
// Try to get from customer
const customer = await stripe.customers.retrieve(subscription.customer as string);
userId = (customer as Stripe.Customer).metadata.userId;
}
const priceId = subscription.items.data[0].price.id;
const plan = getPlanFromPriceId(priceId);
await db.user.update({
where: { id: userId },
data: {
subscriptionId: subscription.id,
subscriptionStatus: subscription.status,
plan: plan,
currentPeriodEnd: new Date(subscription.current_period_end * 1000),
cancelAtPeriodEnd: subscription.cancel_at_period_end,
},
});
}
// Handle payment failure
async function handlePaymentFailed(invoice: Stripe.Invoice) {
const subscription = await stripe.subscriptions.retrieve(
invoice.subscription as string
);
const userId = subscription.metadata.userId;
// Send email about failed payment
await sendEmail({
to: invoice.customer_email,
template: 'payment-failed',
data: {
amount: formatCurrency(invoice.amount_due),
nextAttempt: invoice.next_payment_attempt
? new Date(invoice.next_payment_attempt * 1000)
: null,
updatePaymentUrl: await createPortalSession(userId),
},
});
// Update user record
await db.user.update({
where: { id: userId },
data: {
subscriptionStatus: 'past_due',
},
});
}
Metered/Usage-Based Billing
When to use: API calls, storage, compute time billing
Implementation: Report usage to Stripe, let them handle invoicing.
// Report usage for metered billing
async function reportUsage(subscriptionItemId: string, quantity: number, timestamp: number) {
// Use idempotency key to prevent duplicate charges
const idempotencyKey = `usage-${subscriptionItemId}-${timestamp}`;
await stripe.subscriptionItems.createUsageRecord(
subscriptionItemId,
{
quantity,
timestamp: Math.floor(timestamp / 1000),
action: 'increment', // or 'set' to override
},
{
idempotencyKey,
}
);
}
// Batch report usage (more efficient)
async function reportDailyUsage() {
const yesterday = new Date();
yesterday.setDate(yesterday.getDate() - 1);
yesterday.setHours(0, 0, 0, 0);
// Get all active metered subscriptions
const subscriptions = await db.user.findMany({
where: {
subscriptionStatus: 'active',
plan: 'metered',
},
});
for (const user of subscriptions) {
// Get usage from your system
const usage = await db.apiUsage.aggregate({
where: {
userId: user.id,
createdAt: {
gte: yesterday,
lt: new Date(yesterday.getTime() + 24 * 60 * 60 * 1000),
},
},
_sum: {
count: true,
},
});
if (usage._sum.count > 0) {
await reportUsage(
user.subscriptionItemId,
usage._sum.count,
yesterday.getTime()
);
}
}
}
Plan Upgrades/Downgrades
When to use: Changing subscription plans mid-cycle
Implementation: Use Stripe's proration or let users manage via portal.
// Upgrade/downgrade subscription
async function changePlan(userId: string, newPriceId: string) {
const user = await db.user.findUnique({ where: { id: userId } });
if (!user.subscriptionId) {
throw new Error('No active subscription');
}
const sub
---
*Content truncated.*
When not to use it
- →When client-side prices are trusted for payment processing
- →When webhook signature verification is skipped
- →When API keys are hardcoded in the application
Limitations
- →Requires server-side implementation for session creation and webhook handling
- →Requires Stripe Dashboard configuration for customer portal settings
- →Does not handle PCI compliance directly on the application server
How it compares
This skill provides a complete, production-ready Stripe integration covering the full billing lifecycle, including specific patterns for one-time and subscription payments, unlike basic payment gateway setups.
Compared to similar skills
saas-payments side by side with the closest alternatives in the catalog.
| Skill | Installs | Updated | Safety | Difficulty |
|---|---|---|---|---|
| saas-payments (this skill) | 0 | 6mo | Review | Advanced |
| mppx | 0 | 18d | Review | Intermediate |
| paypal-integration | 10 | 2mo | No flags | Intermediate |
| mcp-builder | 136 | 3mo | Review | Advanced |
Try saying
Example prompts that trigger this skill in your AI assistant.
You might also like
mppx
tempoxyz
TypeScript SDK for the Payment HTTP Authentication Scheme. Handles 402 Payment Required flows with Tempo, Stripe, and other payment methods. Use when integrating payments or mppx into a client or server application.
paypal-integration
wshobson
Integrate PayPal payment processing with support for express checkout, subscriptions, and refund management. Use when implementing PayPal payments, processing online transactions, or building e-commerce checkout flows.
mcp-builder
anthropics
Guide for creating high-quality MCP (Model Context Protocol) servers that enable LLMs to interact with external services through well-designed tools. Use when building MCP servers to integrate external APIs or services, whether in Python (FastMCP) or Node/TypeScript (MCP SDK).
telegram-mini-app
davila7
Expert in building Telegram Mini Apps (TWA) - web apps that run inside Telegram with native-like experience. Covers the TON ecosystem, Telegram Web App API, payments, user authentication, and building viral mini apps that monetize. Use when: telegram mini app, TWA, telegram web app, TON app, mini app.
stripe-integration
wshobson
Implement Stripe payment processing for robust, PCI-compliant payment flows including checkout, subscriptions, and webhooks. Use when integrating Stripe payments, building subscription systems, or implementing secure checkout flows.
shopify-development
davila7
Build Shopify apps, extensions, themes using GraphQL Admin API, Shopify CLI, Polaris UI, and Liquid. TRIGGER: "shopify", "shopify app", "checkout extension", "admin extension", "POS extension", "shopify theme", "liquid template", "polaris", "shopify graphql", "shopify webhook", "shopify billing", "app subscription", "metafields", "shopify functions"