Claude
Skills
Sign in
Back

payment-integration

Included with Lifetime
$97 forever

Stripe, RevenueCat, subscription billing, webhooks, PCI compliance, and tax

Sales & CRM

What this skill does


# Payment Integration

## Overview

This 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.

Use this skill when adding payment processing, building subscription billing, handling Stripe webhooks, implementing pricing pages, managing payment failures, or integrating mobile in-app purchases.

---

## Core Principles

1. **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.
2. **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.
3. **Idempotency everywhere** - Webhooks can be delivered multiple times. Every webhook handler must be idempotent. Use Stripe's event ID as a deduplication key.
4. **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.
5. **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.

---

## Key Patterns

### Pattern 1: Stripe Checkout for Subscriptions

**When to use:** When you want Stripe to handle the entire checkout UI, including payment form, coupon codes, and tax calculation.

**Implementation:**

```typescript
// Server - Create Checkout Session
// app/api/checkout/route.ts
import Stripe from "stripe";
import { NextRequest, NextResponse } from "next/server";

const stripe = new Stripe(process.env.STRIPE_SECRET_KEY!, {
  apiVersion: "2024-06-20",
});

export async function POST(req: NextRequest) {
  const { priceId, userId, email } = await req.json();

  // Get or create Stripe customer
  let customerId = await getStripeCustomerId(userId);
  if (!customerId) {
    const customer = await stripe.customers.create({
      email,
      metadata: { userId },
    });
    customerId = customer.id;
    await saveStripeCustomerId(userId, customerId);
  }

  const session = await stripe.checkout.sessions.create({
    customer: customerId,
    mode: "subscription",
    line_items: [{ price: priceId, quantity: 1 }],
    success_url: `${process.env.NEXT_PUBLIC_URL}/dashboard?session_id={CHECKOUT_SESSION_ID}`,
    cancel_url: `${process.env.NEXT_PUBLIC_URL}/pricing`,
    subscription_data: {
      metadata: { userId },
      trial_period_days: 14,
    },
    // Enable automatic tax calculation
    automatic_tax: { enabled: true },
    // Allow promo codes
    allow_promotion_codes: true,
    // Collect billing address for tax
    billing_address_collection: "required",
    // Customer portal for self-service management
    customer_update: {
      address: "auto",
      name: "auto",
    },
  });

  return NextResponse.json({ url: session.url });
}
```

```tsx
// Client - Redirect to Checkout
function PricingCard({ plan }: { plan: PricingPlan }) {
  const [loading, setLoading] = useState(false);

  const handleSubscribe = async () => {
    setLoading(true);
    try {
      const res = await fetch("/api/checkout", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({
          priceId: plan.stripePriceId,
          userId: user.id,
          email: user.email,
        }),
      });

      const { url } = await res.json();
      window.location.href = url; // Redirect to Stripe Checkout
    } catch (error) {
      toast.error("Failed to start checkout");
    } finally {
      setLoading(false);
    }
  };

  return (
    <div className="pricing-card">
      <h3>{plan.name}</h3>
      <p className="price">${plan.price}/mo</p>
      <ul>
        {plan.features.map((f) => (
          <li key={f}>{f}</li>
        ))}
      </ul>
      <button onClick={handleSubscribe} disabled={loading}>
        {loading ? "Redirecting..." : "Subscribe"}
      </button>
    </div>
  );
}
```

**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.

---

### Pattern 2: Webhook Handler with Idempotency

**When to use:** Every Stripe integration. Webhooks are the only reliable way to know payment status.

**Implementation:**

```typescript
// app/api/webhooks/stripe/route.ts
import Stripe from "stripe";
import { NextRequest, NextResponse } from "next/server";
import { headers } from "next/headers";

const stripe = new Stripe(process.env.STRIPE_SECRET_KEY!);

// Process each event type
const eventHandlers: Record<string, (event: Stripe.Event) => Promise<void>> = {
  "checkout.session.completed": async (event) => {
    const session = event.data.object as Stripe.Checkout.Session;
    const userId = session.metadata?.userId ?? session.subscription?.toString();

    await db.user.update({
      where: { stripeCustomerId: session.customer as string },
      data: {
        subscriptionId: session.subscription as string,
        subscriptionStatus: "active",
      },
    });
  },

  "customer.subscription.updated": async (event) => {
    const subscription = event.data.object as Stripe.Subscription;

    await db.user.update({
      where: { stripeCustomerId: subscription.customer as string },
      data: {
        subscriptionStatus: subscription.status,
        planId: subscription.items.data[0].price.id,
        currentPeriodEnd: new Date(subscription.current_period_end * 1000),
        cancelAtPeriodEnd: subscription.cancel_at_period_end,
      },
    });
  },

  "customer.subscription.deleted": async (event) => {
    const subscription = event.data.object as Stripe.Subscription;

    await db.user.update({
      where: { stripeCustomerId: subscription.customer as string },
      data: {
        subscriptionStatus: "canceled",
        planId: null,
      },
    });
  },

  "invoice.payment_failed": async (event) => {
    const invoice = event.data.object as Stripe.Invoice;

    await db.user.update({
      where: { stripeCustomerId: invoice.customer as string },
      data: { subscriptionStatus: "past_due" },
    });

    // Send dunning email
    await sendDunningEmail(invoice.customer as string, {
      amountDue: invoice.amount_due,
      nextRetry: invoice.next_payment_attempt
        ? new Date(invoice.next_payment_attempt * 1000)
        : null,
    });
  },

  "invoice.paid": async (event) => {
    const invoice = event.data.object as Stripe.Invoice;

    await db.user.update({
      where: { stripeCustomerId: invoice.customer as string },
      data: { subscriptionStatus: "active" },
    });
  },
};

export async function POST(req: NextRequest) {
  const body = await req.text();
  const signature = (await headers()).get("stripe-signature")!;

  let event: Stripe.Event;

  // 1. Verify webhook signature (prevents spoofing)
  try {
    event = stripe.webhooks.constructEvent(
      body,
      signature,
      process.env.STRIPE_WEBHOOK_SECRET!
    );
  } catch (err) {
    console.error("Webhook signature verification failed:", err);
    return NextResponse.json({ error: "Invalid signature" }, { status: 400 });
  }

  // 2. Idempotency check - skip already-processed events
  const alreadyProcessed = await db.stripeEvent.findUnique({
    where: { eventId: event.id },
  });

  if (alreadyProcessed) {
    return NextResponse.json({ received: true });
  }

  // 3. Process the event
  const 

Related in Sales & CRM