6# Payment Integration
7
8## Overview
9
10This skill covers implementing payment processing and subscription billing in web and mobile applications. It addresses Stripe integration (Checkout, Elements, PaymentIntents), subscription lifecycle management, webhook handling with idempotency, PCI compliance, metered and usage-based billing, tax calculation, refund processing, and RevenueCat for mobile subscriptions.
11
12Use this skill when adding payment processing, building subscription billing, handling Stripe webhooks, implementing pricing pages, managing payment failures, or integrating mobile in-app purchases.
13
14---
15
16## Core Principles
17
181. **Never handle raw card data** - Use Stripe Elements or Checkout to keep card numbers off your servers entirely. This keeps you at PCI SAQ-A (the simplest compliance level) rather than SAQ-D.
192. **Webhooks are the source of truth** - Never trust client-side payment confirmation. A successful PaymentIntent on the client means nothing until your webhook handler confirms payment_intent.succeeded. Build your system around webhook events.
203. **Idempotency everywhere** - Webhooks can be delivered multiple times. Every webhook handler must be idempotent. Use Stripe's event ID as a deduplication key.
214. **Handle failure gracefully** - Payments fail for many reasons (insufficient funds, expired cards, fraud detection). Build retry flows, dunning emails, and graceful degradation into the subscription lifecycle.
225. **Test with Stripe's test mode** - Use test API keys, test card numbers, and test clocks for subscription lifecycle testing. Never test with real payment methods.
23
24---
25
26## Key Patterns
27
28### Pattern 1: Stripe Checkout for Subscriptions
29
30**When to use:** When you want Stripe to handle the entire checkout UI, including payment form, coupon codes, and tax calculation.
31
32**Implementation:**
33
34```typescript
35// Server - Create Checkout Session
36// app/api/checkout/route.ts
37import Stripe from "stripe";
38import { NextRequest, NextResponse } from "next/server";
39
40const stripe = new Stripe(process.env.STRIPE_SECRET_KEY!, {
41 apiVersion: "2024-06-20",
42});
43
44export async function POST(req: NextRequest) {
45 const { priceId, userId, email } = await req.json();
46
47 // Get or create Stripe customer
48 let customerId = await getStripeCustomerId(userId);
49 if (!customerId) {
50 const customer = await stripe.customers.create({
51 email,
52 metadata: { userId },
53 });
54 customerId = customer.id;
55 await saveStripeCustomerId(userId, customerId);
56 }
57
58 const session = await stripe.checkout.sessions.create({
59 customer: customerId,
60 mode: "subscription",
61 line_items: [{ price: priceId, quantity: 1 }],
62 success_url: ${process.env.NEXT_PUBLIC_URL}/dashboard?session_id={CHECKOUT_SESSION_ID},
63 cancel_url: ${process.env.NEXT_PUBLIC_URL}/pricing,
64 subscription_data: {
65 metadata: { userId },
66 trial_period_days: 14,
67 },
68 // Enable automatic tax calculation
69 automatic_tax: { enabled: true },
70 // Allow promo codes
71 allow_promotion_codes: true,
72 // Collect billing address for tax
73 billing_address_collection: "required",
74 // Customer portal for self-service management
75 customer_update: {
76 address: "auto",
77 name: "auto",
78 },
79 });
80
81 return NextResponse.json({ url: session.url });
82}
83```
84
85```tsx
86// Client - Redirect to Checkout
87function PricingCard({ plan }: { plan: PricingPlan }) {
88 const [loading, setLoading] = useState(false);
89
90 const handleSubscribe = async () => {
91 setLoading(true);
92 try {
93 const res = await fetch("/api/checkout", {
94 method: "POST",
95 headers: { "Content-Type": "application/json" },
96 body: JSON.stringify({
97 priceId: plan.stripePriceId,
98 userId: user.id,
99 email: user.email,
100 }),
101 });
102
103 const { url } = await res.json();
104 window.location.href = url; // Redirect to Stripe Checkout
105 } catch (error) {
106 toast.error("Failed to start checkout");
107 } finally {
108 setLoading(false);
109 }
110 };
111
112 return (
113 <div className="pricing-card">
114 <h3>{plan.name}</h3>
115 <p className="price">${plan.price}/mo</p>
116 <ul>
117 {plan.features.map((f) => (
118 <li key={f}>{f}</li>
119 ))}
120 </ul>
121 <button onClick={handleSubscribe} disabled={loading}>
122 {loading ? "Redirecting..." : "Subscribe"}
123 </button>
124 </div>
125 );
126}
127```
128
129**Why:** Stripe Checkout handles PCI compliance, 3D Secure authentication, tax calculation, promo codes, and localization. Building your own checkout form is hundreds of hours of work and ongoing PCI compliance burden. Use Checkout unless you have a strong reason to build custom UI.
130
131---
132
133### Pattern 2: Webhook Handler with Idempotency
134
135**When to use:** Every Stripe integration. Webhooks are the only reliable way to know payment status.
136
137**Implementation:**
138
139```typescript
140// app/api/webhooks/stripe/route.ts
141import Stripe from "stripe";
142import { NextRequest, NextResponse } from "next/server";
143import { headers } from "next/headers";
144
145const stripe = new Stripe(process.env.STRIPE_SECRET_KEY!);
146
147// Process each event type
148const eventHandlers: Record<string, (event: Stripe.Event) => Promise<void>> = {
149 "checkout.session.completed": async (event) => {
150 const session = event.data.object as Stripe.Checkout.Session;
151 const userId = session.metadata?.userId ?? session.subscription?.toString();
152
153 await db.user.update({
154 where: { stripeCustomerId: session.customer as string },
155 data: {
156 subscriptionId: session.subscription as string,
157 subscriptionStatus: "active",
158 },
159 });
160 },
161
162 "customer.subscription.updated": async (event) => {
163 const subscription = event.data.object as Stripe.Subscription;
164
165 await db.user.update({
166 where: { stripeCustomerId: subscription.customer as string },
167 data: {
168 subscriptionStatus: subscription.status,
169 planId: subscription.items.data[0].price.id,
170 currentPeriodEnd: new Date(subscription.current_period_end * 1000),
171 cancelAtPeriodEnd: subscription.cancel_at_period_end,
172 },
173 });
174 },
175
176 "customer.subscription.deleted": async (event) => {
177 const subscription = event.data.object as Stripe.Subscription;
178
179 await db.user.update({
180 where: { stripeCustomerId: subscription.customer as string },
181 data: {
182 subscriptionStatus: "canceled",
183 planId: null,
184 },
185 });
186 },
187
188 "invoice.payment_failed": async (event) => {
189 const invoice = event.data.object as Stripe.Invoice;
190
191 await db.user.update({
192 where: { stripeCustomerId: invoice.customer as string },
193 data: { subscriptionStatus: "past_due" },
194 });
195
196 // Send dunning email
197 await sendDunningEmail(invoice.customer as string, {
198 amountDue: invoice.amount_due,
199 nextRetry: invoice.next_payment_attempt
200 ? new Date(invoice.next_payment_attempt * 1000)
201 : null,
202 });
203 },
204
205 "invoice.paid": async (event) => {
206 const invoice = event.data.object as Stripe.Invoice;
207
208 await db.user.update({
209 where: { stripeCustomerId: invoice.customer as string },
210 data: { subscriptionStatus: "active" },
211 });
212 },
213};
214
215export async function POST(req: NextRequest) {
216 const body = await req.text();
217 const signature = (await headers()).get("stripe-signature")!;
218
219 let event: Stripe.Event;
220
221 // 1. Verify webhook signature (prevents spoofing)
222 try {
223 event = stripe.webhooks.constructEvent(
224 body,
225 signature,
226 process.env.STRIPE_WEBHOOK_SECRET!
227 );
228 } catch (err) {
229 console.error("Webhook signature verification failed:", err);
230 return NextResponse.json({ error: "Invalid signature" }, { status: 400 });
231 }
232
233 // 2. Idempotency check - skip already-processed events
234 const alreadyProcessed = await db.stripeEvent.findUnique({
235 where: { eventId: event.id },
236 });
237
238 if (alreadyProcessed) {
239 return NextResponse.json({ received: true });
240 }
241
242 // 3. Process the event
243 const handler = eventHandlers[event.type];
244 if (handler) {
245 try {
246 await handler(event);
247
248 // 4. Record processed event for idempotency
249 await db.stripeEvent.create({
250 data: {
251 eventId: event.id,
252 type: event.type,
253 processedAt: new Date(),
254 },
255 });
256 } catch (err) {
257 console.error(Error processing ${event.type}:, err);
258 // Return 500 so Stripe retries
259 return NextResponse.json({ error: "Processing failed" }, { status: 500 });
260 }
261 }
262
263 return NextResponse.json({ received: true });
264}
265```
266
267**Why:** Stripe delivers webhooks at least once, meaning duplicates are possible. The idempotency check (storing processed event IDs) prevents double-processing. Signature verification prevents spoofed webhook attacks. Returning 500 on handler errors triggers Stripe's automatic retry with exponential backoff.
268
269---
270
271### Pattern 3: Customer Portal for Self-Service
272
273**When to use:** Let customers manage their own subscriptions (upgrade, downgrade, cancel, update payment method) without contacting support.
274
275**Implementation:**
276
277```typescript
278// Create portal session
279// app/api/billing/portal/route.ts
280export async function POST(req: NextRequest) {
281 const { userId } = await req.json();
282
283 const user = await db.user.findUniqueOrThrow({
284 where: { id: userId },
285 select: { stripeCustomerId: true },
286 });
287
288 if (!user.stripeCustomerId) {
289 return NextResponse.json({ error: "No billing account" }, { status: 400 });
290 }
291
292 const session = await stripe.billingPortal.sessions.create({
293 customer: user.stripeCustomerId,
294 return_url: ${process.env.NEXT_PUBLIC_URL}/settings/billing,
295 });
296
297 return NextResponse.json({ url: session.url });
298}
299```
300
301```typescript
302// Configure the portal in Stripe (do this once, via API or Dashboard)
303await stripe.billingPortal.configurations.create({
304 business_profile: {
305 headline: "Manage your subscription",
306 },
307 features: {
308 subscription_update: {
309 enabled: true,
310 default_allowed_updates: ["price", "quantity"],
311 proration_behavior: "create_prorations",
312 products: [
313 {
314 product: "prod_xxx",
315 prices: ["price_monthly", "price_annual"],
316 },
317 ],
318 },
319 subscription_cancel: {
320 enabled: true,
321 mode: "at_period_end", // Don't cancel immediately
322 cancellation_reason: {
323 enabled: true,
324 options: [
325 "too_expensive",
326 "missing_features",
327 "switched_service",
328 "unused",
329 "other",
330 ],
331 },
332 },
333 payment_method_update: { enabled: true },
334 invoice_history: { enabled: true },
335 },
336});
337```
338
339**Why:** Self-service billing reduces support tickets by 60-80%. Stripe's Customer Portal is a hosted solution that handles plan changes, proration, cancellation with reason capture, payment method updates, and invoice history -- all without building custom UI.
340
341---
342
343### Pattern 4: Usage-Based Billing
344
345**When to use:** When pricing is based on consumption (API calls, storage, compute minutes, seats) rather than flat-rate subscriptions.
346
347**Implementation:**
348
349```typescript
350// Report usage to Stripe
351async function reportUsage(
352 subscriptionItemId: string,
353 quantity: number,
354 timestamp?: number
355): Promise<void> {
356 await stripe.subscriptionItems.createUsageRecord(subscriptionItemId, {
357 quantity,
358 timestamp: timestamp ?? Math.floor(Date.now() / 1000),
359 action: "increment", // Add to existing usage (vs "set" to replace)
360 });
361}
362
363// Background job: aggregate and report usage hourly
364async function reportHourlyUsage(): Promise<void> {
365 const activeSubscriptions = await db.subscription.findMany({
366 where: { status: "active", plan: { billingModel: "usage" } },
367 include: { user: true },
368 });
369
370 for (const sub of activeSubscriptions) {
371 const usage = await getHourlyUsage(sub.userId);
372
373 if (usage > 0) {
374 await reportUsage(sub.stripeSubscriptionItemId, usage);
375
376 await db.usageReport.create({
377 data: {
378 subscriptionId: sub.id,
379 quantity: usage,
380 reportedAt: new Date(),
381 },
382 });
383 }
384 }
385}
386
387// Track usage in your application
388async function trackApiCall(userId: string, endpoint: string): Promise<void> {
389 // Increment usage counter (Redis for speed)
390 const key = usage:${userId}:${getCurrentHour()};
391 await redis.incr(key);
392 await redis.expire(key, 86400 * 7); // Keep for 7 days
393
394 // Check if user is approaching their limit
395 const currentUsage = await getCurrentMonthUsage(userId);
396 const limit = await getUserPlanLimit(userId);
397
398 if (currentUsage >= limit * 0.8) {
399 await sendUsageWarningEmail(userId, currentUsage, limit);
400 }
401
402 if (currentUsage >= limit) {
403 throw new UsageLimitExceededError(userId, currentUsage, limit);
404 }
405}
406```
407
408**Why:** Usage-based billing aligns cost with value -- customers pay for what they use. Hourly aggregation reduces API calls to Stripe while keeping usage data fresh enough for invoicing. Redis-based tracking provides sub-millisecond usage checks for rate limiting.
409
410---
411
412## Stripe Test Cards Reference
413
414| Number | Scenario |
415|---|---|
416| 4242 4242 4242 4242 | Successful payment |
417| 4000 0000 0000 3220 | 3D Secure required |
418| 4000 0000 0000 9995 | Declined (insufficient funds) |
419| 4000 0000 0000 0341 | Attaching to customer fails |
420| 4000 0025 0000 3155 | Requires authentication |
421
422Use any future expiry date and any 3-digit CVC.
423
424---
425
426## Anti-Patterns
427
428| Anti-Pattern | Why It's Bad | Better Approach |
429|---|---|---|
430| Trusting client-side payment confirmation | Users can spoof success | Webhook handler is the source of truth |
431| Handling raw card numbers on your server | PCI SAQ-D compliance (very expensive) | Use Stripe Elements or Checkout |
432| No idempotency in webhook handlers | Double charges, duplicate provisioning | Deduplicate by event ID |
433| Canceling subscriptions immediately | Users lose access mid-billing period | Cancel at period end (cancel_at_period_end) |
434| Hardcoding prices in your app | Can't change pricing without deploy | Store price IDs in database or environment |
435| No dunning flow for failed payments | Silent revenue loss (involuntary churn) | Automated retry + dunning emails |
436| Testing with real payment methods | Risk of real charges, no test clocks | Use Stripe test mode exclusively |
437
438---
439
440## Checklist
441
442- [ ] Stripe API keys stored in environment variables (never in code)
443- [ ] Webhook signature verification enabled
444- [ ] Webhook handler is idempotent (event ID deduplication)
445- [ ] All subscription status changes handled (created, updated, canceled, past_due)
446- [ ] Failed payment dunning flow implemented (email + retry)
447- [ ] Customer portal configured for self-service billing
448- [ ] Test mode used for all development and staging
449- [ ] PCI compliance level confirmed (SAQ-A with Stripe Checkout/Elements)
450- [ ] Tax calculation enabled (Stripe Tax or external provider)
451- [ ] Proration configured for plan changes (upgrade/downgrade)
452- [ ] Webhook endpoint registered in Stripe Dashboard
453- [ ] Stripe CLI installed for local webhook testing (stripe listen --forward-to)
454
455---
456
457## Related Resources
458
459- **Skills:** authentication-patterns (user identity for billing), email-systems (dunning emails)
460- **Skills:** monitoring-observability (payment failure alerting)
461- **Rules:** docs/reference/stacks/fullstack-nextjs-nestjs.md (API route patterns)
462