[{"data":1,"prerenderedAt":-1},["ShallowReactive",2],{"skill:01M76VJX2DWZGRGGMH80D2ZQDA":3,"skill-same:01M76VJX2DWZGRGGMH80D2ZQDA":46},{"skillNo":4,"name":5,"nameZh":6,"description":7,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":16,"categories":17,"keywords":18,"publishedAt":19,"linkOnly":20,"markdownContent":21,"markdownBody":22,"frontMatter":23,"refName":24,"commitSha":25,"skillDirectory":26,"forksCount":27,"repositoryHtmlUrl":28,"repositoryHomepageUrl":6,"ownerHtmlUrl":29,"ownerBlogUrl":30,"ownerDescription":6,"updatedAt":31,"install":32,"resources":45},"01M76VJX2DWZGRGGMH80D2ZQDA","stripe-integration-expert",null,"Production-grade Stripe integrations: subscriptions with trials and proration, one-time payments, usage-based billing, checkout sessions, idempotent webhook handlers, customer portal, and invoicing. Covers Next.js, Express, and Django patterns. Use when integrating Stripe for the first time, debugging webhook reliability issues, migrating from a different payment provider, or adding usage-based billing to an existing subscription product.","kruxshnx\u002Fclaude-skills-devin","kruxshnx","https:\u002F\u002Favatars.githubusercontent.com\u002Fu\u002F127938788?v=4","01M757YM3F96N4K1BSE7Z0NQK7","ARJANGI GOVINDA KRISHNA","01M757YM43H5T7MP2B3DC13GZ2",2,"MIT","https:\u002F\u002Fgithub.com\u002Fkruxshnx\u002Fclaude-skills-devin\u002Fblob\u002Fdevin\u002F1780503568-install-devin-skills\u002F.devin\u002Fskills\u002Fstripe-integration-expert\u002FSKILL.md",[],[],"2026-11-12 13:55:43",false,"---\nname: \"stripe-integration-expert\"\ndescription: \"Production-grade Stripe integrations: subscriptions with trials and proration, one-time payments, usage-based billing, checkout sessions, idempotent webhook handlers, customer portal, and invoicing. Covers Next.js, Express, and Django patterns. Use when integrating Stripe for the first time, debugging webhook reliability issues, migrating from a different payment provider, or adding usage-based billing to an existing subscription product.\"\n---\n\n# Stripe Integration Expert\n\n**Tier:** POWERFUL  \n**Category:** Engineering Team  \n**Domain:** Payments \u002F Billing Infrastructure\n\n---\n\n## Overview\n\nImplement production-grade Stripe integrations: subscriptions with trials and proration, one-time payments, usage-based billing, checkout sessions, idempotent webhook handlers, customer portal, and invoicing. Covers Next.js, Express, and Django patterns.\n\n---\n\n## Core Capabilities\n\n- Subscription lifecycle management (create, upgrade, downgrade, cancel, pause)\n- Trial handling and conversion tracking\n- Proration calculation and credit application\n- Usage-based billing with metered pricing\n- Idempotent webhook handlers with signature verification\n- Customer portal integration\n- Invoice generation and PDF access\n- Full Stripe CLI local testing setup\n\n---\n\n## When to Use\n\n- Adding subscription billing to any web app\n- Implementing plan upgrades\u002Fdowngrades with proration\n- Building usage-based or seat-based billing\n- Debugging webhook delivery failures\n- Migrating from one billing model to another\n\n---\n\n## Subscription Lifecycle State Machine\n\n```\nFREE_TRIAL ──paid──► ACTIVE ──cancel──► CANCEL_PENDING ──period_end──► CANCELED\n     │                  │                                                    │\n     │               downgrade                                            reactivate\n     │                  ▼                                                    │\n     │             DOWNGRADING ──period_end──► ACTIVE (lower plan)           │\n     │                                                                        │\n     └──trial_end without payment──► PAST_DUE ──payment_failed 3x──► CANCELED\n                                          │\n                                     payment_success\n                                          │\n                                          ▼\n                                        ACTIVE\n```\n\n### DB subscription status values:\n`trialing | active | past_due | canceled | cancel_pending | paused | unpaid`\n\n---\n\n## Stripe Client Setup\n\n```typescript\n\u002F\u002F lib\u002Fstripe.ts\nimport Stripe from \"stripe\"\n\nexport const stripe = new Stripe(process.env.STRIPE_SECRET_KEY!, {\n  apiVersion: \"2024-04-10\",\n  typescript: true,\n  appInfo: {\n    name: \"myapp\",\n    version: \"1.0.0\",\n  },\n})\n\n\u002F\u002F Price IDs by plan (set in env)\nexport const PLANS = {\n  starter: {\n    monthly: process.env.STRIPE_STARTER_MONTHLY_PRICE_ID!,\n    yearly: process.env.STRIPE_STARTER_YEARLY_PRICE_ID!,\n    features: [\"5 projects\", \"10k events\"],\n  },\n  pro: {\n    monthly: process.env.STRIPE_PRO_MONTHLY_PRICE_ID!,\n    yearly: process.env.STRIPE_PRO_YEARLY_PRICE_ID!,\n    features: [\"Unlimited projects\", \"1M events\"],\n  },\n} as const\n```\n\n---\n\n## Checkout Session (Next.js App Router)\n\n```typescript\n\u002F\u002F app\u002Fapi\u002Fbilling\u002Fcheckout\u002Froute.ts\nimport { NextResponse } from \"next\u002Fserver\"\nimport { stripe } from \"@\u002Flib\u002Fstripe\"\nimport { getAuthUser } from \"@\u002Flib\u002Fauth\"\nimport { db } from \"@\u002Flib\u002Fdb\"\n\nexport async function POST(req: Request) {\n  const user = await getAuthUser()\n  if (!user) return NextResponse.json({ error: \"Unauthorized\" }, { status: 401 })\n\n  const { priceId, interval = \"monthly\" } = await req.json()\n\n  \u002F\u002F Get or create Stripe customer\n  let stripeCustomerId = user.stripeCustomerId\n  if (!stripeCustomerId) {\n    const customer = await stripe.customers.create({\n      email: user.email,\n      name: \"username-undefined\"\n      metadata: { userId: user.id },\n    })\n    stripeCustomerId = customer.id\n    await db.user.update({ where: { id: user.id }, data: { stripeCustomerId } })\n  }\n\n  const session = await stripe.checkout.sessions.create({\n    customer: stripeCustomerId,\n    mode: \"subscription\",\n    payment_method_types: [\"card\"],\n    line_items: [{ price: priceId, quantity: 1 }],\n    allow_promotion_codes: true,\n    subscription_data: {\n      trial_period_days: user.hasHadTrial ? undefined : 14,\n      metadata: { userId: user.id },\n    },\n    success_url: `${process.env.NEXT_PUBLIC_APP_URL}\u002Fdashboard?session_id={CHECKOUT_SESSION_ID}`,\n    cancel_url: `${process.env.NEXT_PUBLIC_APP_URL}\u002Fpricing`,\n    metadata: { userId: user.id },\n  })\n\n  return NextResponse.json({ url: session.url })\n}\n```\n\n---\n\n## Subscription Upgrade\u002FDowngrade\n\n```typescript\n\u002F\u002F lib\u002Fbilling.ts\nexport async function changeSubscriptionPlan(\n  subscriptionId: string,\n  newPriceId: string,\n  immediate = false\n) {\n  const subscription = await stripe.subscriptions.retrieve(subscriptionId)\n  const currentItem = subscription.items.data[0]\n\n  if (immediate) {\n    \u002F\u002F Upgrade: apply immediately with proration\n    return stripe.subscriptions.update(subscriptionId, {\n      items: [{ id: currentItem.id, price: newPriceId }],\n      proration_behavior: \"always_invoice\",\n      billing_cycle_anchor: \"unchanged\",\n    })\n  } else {\n    \u002F\u002F Downgrade: apply at period end, no proration\n    return stripe.subscriptions.update(subscriptionId, {\n      items: [{ id: currentItem.id, price: newPriceId }],\n      proration_behavior: \"none\",\n      billing_cycle_anchor: \"unchanged\",\n    })\n  }\n}\n\n\u002F\u002F Preview proration before confirming upgrade\nexport async function previewProration(subscriptionId: string, newPriceId: string) {\n  const subscription = await stripe.subscriptions.retrieve(subscriptionId)\n  const prorationDate = Math.floor(Date.now() \u002F 1000)\n\n  const invoice = await stripe.invoices.retrieveUpcoming({\n    customer: subscription.customer as string,\n    subscription: subscriptionId,\n    subscription_items: [{ id: subscription.items.data[0].id, price: newPriceId }],\n    subscription_proration_date: prorationDate,\n  })\n\n  return {\n    amountDue: invoice.amount_due,\n    prorationDate,\n    lineItems: invoice.lines.data,\n  }\n}\n```\n\n---\n\n## Complete Webhook Handler (Idempotent)\n\n```typescript\n\u002F\u002F app\u002Fapi\u002Fwebhooks\u002Fstripe\u002Froute.ts\nimport { NextResponse } from \"next\u002Fserver\"\nimport { headers } from \"next\u002Fheaders\"\nimport { stripe } from \"@\u002Flib\u002Fstripe\"\nimport { db } from \"@\u002Flib\u002Fdb\"\nimport Stripe from \"stripe\"\n\n\u002F\u002F Processed events table to ensure idempotency\nasync function hasProcessedEvent(eventId: string): Promise\u003Cboolean> {\n  const existing = await db.stripeEvent.findUnique({ where: { id: eventId } })\n  return !!existing\n}\n\nasync function markEventProcessed(eventId: string, type: string) {\n  await db.stripeEvent.create({ data: { id: eventId, type, processedAt: new Date() } })\n}\n\nexport async function POST(req: Request) {\n  const body = await req.text()\n  const signature = headers().get(\"stripe-signature\")!\n\n  let event: Stripe.Event\n  try {\n    event = stripe.webhooks.constructEvent(body, signature, process.env.STRIPE_WEBHOOK_SECRET!)\n  } catch (err) {\n    console.error(\"Webhook signature verification failed:\", err)\n    return NextResponse.json({ error: \"Invalid signature\" }, { status: 400 })\n  }\n\n  \u002F\u002F Idempotency check\n  if (await hasProcessedEvent(event.id)) {\n    return NextResponse.json({ received: true, skipped: true })\n  }\n\n  try {\n    switch (event.type) {\n      case \"checkout.session.completed\":\n        await handleCheckoutCompleted(event.data.object as Stripe.Checkout.Session)\n        break\n\n      case \"customer.subscription.created\":\n      case \"customer.subscription.updated\":\n        await handleSubscriptionUpdated(event.data.object as Stripe.Subscription)\n        break\n\n      case \"customer.subscription.deleted\":\n        await handleSubscriptionDeleted(event.data.object as Stripe.Subscription)\n        break\n\n      case \"invoice.payment_succeeded\":\n        await handleInvoicePaymentSucceeded(event.data.object as Stripe.Invoice)\n        break\n\n      case \"invoice.payment_failed\":\n        await handleInvoicePaymentFailed(event.data.object as Stripe.Invoice)\n        break\n\n      default:\n        console.log(`Unhandled event type: ${event.type}`)\n    }\n\n    await markEventProcessed(event.id, event.type)\n    return NextResponse.json({ received: true })\n  } catch (err) {\n    console.error(`Error processing webhook ${event.type}:`, err)\n    \u002F\u002F Return 500 so Stripe retries — don't mark as processed\n    return NextResponse.json({ error: \"Processing failed\" }, { status: 500 })\n  }\n}\n\nasync function handleCheckoutCompleted(session: Stripe.Checkout.Session) {\n  if (session.mode !== \"subscription\") return\n  \n  const userId = session.metadata?.userId\n  if (!userId) throw new Error(\"No userId in checkout session metadata\")\n\n  const subscription = await stripe.subscriptions.retrieve(session.subscription as string)\n  \n  await db.user.update({\n    where: { id: userId },\n    data: {\n      stripeCustomerId: session.customer as string,\n      stripeSubscriptionId: subscription.id,\n      stripePriceId: subscription.items.data[0].price.id,\n      stripeCurrentPeriodEnd: new Date(subscription.current_period_end * 1000),\n      subscriptionStatus: subscription.status,\n      hasHadTrial: true,\n    },\n  })\n}\n\nasync function handleSubscriptionUpdated(subscription: Stripe.Subscription) {\n  const user = await db.user.findUnique({\n    where: { stripeSubscriptionId: subscription.id },\n  })\n  if (!user) {\n    \u002F\u002F Look up by customer ID as fallback\n    const customer = await db.user.findUnique({\n      where: { stripeCustomerId: subscription.customer as string },\n    })\n    if (!customer) throw new Error(`No user found for subscription ${subscription.id}`)\n  }\n\n  await db.user.update({\n    where: { stripeSubscriptionId: subscription.id },\n    data: {\n      stripePriceId: subscription.items.data[0].price.id,\n      stripeCurrentPeriodEnd: new Date(subscription.current_period_end * 1000),\n      subscriptionStatus: subscription.status,\n      cancelAtPeriodEnd: subscription.cancel_at_period_end,\n    },\n  })\n}\n\nasync function handleSubscriptionDeleted(subscription: Stripe.Subscription) {\n  await db.user.update({\n    where: { stripeSubscriptionId: subscription.id },\n    data: {\n      stripeSubscriptionId: null,\n      stripePriceId: null,\n      stripeCurrentPeriodEnd: null,\n      subscriptionStatus: \"canceled\",\n    },\n  })\n}\n\nasync function handleInvoicePaymentFailed(invoice: Stripe.Invoice) {\n  if (!invoice.subscription) return\n  const attemptCount = invoice.attempt_count\n  \n  await db.user.update({\n    where: { stripeSubscriptionId: invoice.subscription as string },\n    data: { subscriptionStatus: \"past_due\" },\n  })\n\n  if (attemptCount >= 3) {\n    \u002F\u002F Send final dunning email\n    await sendDunningEmail(invoice.customer_email!, \"final\")\n  } else {\n    await sendDunningEmail(invoice.customer_email!, \"retry\")\n  }\n}\n\nasync function handleInvoicePaymentSucceeded(invoice: Stripe.Invoice) {\n  if (!invoice.subscription) return\n\n  await db.user.update({\n    where: { stripeSubscriptionId: invoice.subscription as string },\n    data: {\n      subscriptionStatus: \"active\",\n      stripeCurrentPeriodEnd: new Date(invoice.period_end * 1000),\n    },\n  })\n}\n```\n\n---\n\n## Usage-Based Billing\n\n```typescript\n\u002F\u002F Report usage for metered subscriptions\nexport async function reportUsage(subscriptionItemId: string, quantity: number) {\n  await stripe.subscriptionItems.createUsageRecord(subscriptionItemId, {\n    quantity,\n    timestamp: Math.floor(Date.now() \u002F 1000),\n    action: \"increment\",\n  })\n}\n\n\u002F\u002F Example: report API calls in middleware\nexport async function trackApiCall(userId: string) {\n  const user = await db.user.findUnique({ where: { id: userId } })\n  if (user?.stripeSubscriptionId) {\n    const subscription = await stripe.subscriptions.retrieve(user.stripeSubscriptionId)\n    const meteredItem = subscription.items.data.find(\n      (item) => item.price.recurring?.usage_type === \"metered\"\n    )\n    if (meteredItem) {\n      await reportUsage(meteredItem.id, 1)\n    }\n  }\n}\n```\n\n---\n\n## Customer Portal\n\n```typescript\n\u002F\u002F app\u002Fapi\u002Fbilling\u002Fportal\u002Froute.ts\nimport { NextResponse } from \"next\u002Fserver\"\nimport { stripe } from \"@\u002Flib\u002Fstripe\"\nimport { getAuthUser } from \"@\u002Flib\u002Fauth\"\n\nexport async function POST() {\n  const user = await getAuthUser()\n  if (!user?.stripeCustomerId) {\n    return NextResponse.json({ error: \"No billing account\" }, { status: 400 })\n  }\n\n  const portalSession = await stripe.billingPortal.sessions.create({\n    customer: user.stripeCustomerId,\n    return_url: `${process.env.NEXT_PUBLIC_APP_URL}\u002Fsettings\u002Fbilling`,\n  })\n\n  return NextResponse.json({ url: portalSession.url })\n}\n```\n\n---\n\n## Testing with Stripe CLI\n\n```bash\n# Install Stripe CLI\nbrew install stripe\u002Fstripe-cli\u002Fstripe\n\n# Login\nstripe login\n\n# Forward webhooks to local dev\nstripe listen --forward-to localhost:3000\u002Fapi\u002Fwebhooks\u002Fstripe\n\n# Trigger specific events for testing\nstripe trigger checkout.session.completed\nstripe trigger customer.subscription.updated\nstripe trigger invoice.payment_failed\n\n# Test with specific customer\nstripe trigger customer.subscription.updated \\\n  --override subscription:customer=cus_xxx\n\n# View recent events\nstripe events list --limit 10\n\n# Test cards\n# Success: 4242 4242 4242 4242\n# Requires auth: 4000 0025 0000 3155\n# Decline: 4000 0000 0000 9995\n# Insufficient funds: 4000 0000 0000 9995\n```\n\n---\n\n## Feature Gating Helper\n\n```typescript\n\u002F\u002F lib\u002Fsubscription.ts\nexport function isSubscriptionActive(user: { subscriptionStatus: string | null, stripeCurrentPeriodEnd: Date | null }) {\n  if (!user.subscriptionStatus) return false\n  if (user.subscriptionStatus === \"active\" || user.subscriptionStatus === \"trialing\") return true\n  \u002F\u002F Grace period: past_due but not yet expired\n  if (user.subscriptionStatus === \"past_due\" && user.stripeCurrentPeriodEnd) {\n    return user.stripeCurrentPeriodEnd > new Date()\n  }\n  return false\n}\n\n\u002F\u002F Middleware usage\nexport async function requireActiveSubscription() {\n  const user = await getAuthUser()\n  if (!isSubscriptionActive(user)) {\n    redirect(\"\u002Fbilling?reason=subscription_required\")\n  }\n}\n```\n\n---\n\n## Common Pitfalls\n\n- **Webhook delivery order not guaranteed** — always re-fetch from Stripe API, never trust event data alone for DB updates\n- **Double-processing webhooks** — Stripe retries on 500; always use idempotency table\n- **Trial conversion tracking** — store `hasHadTrial: true` in DB to prevent trial abuse\n- **Proration surprises** — always preview proration before upgrade; show user the amount before confirming\n- **Customer portal not configured** — must enable features in Stripe dashboard under Billing → Customer portal settings\n- **Missing metadata on checkout** — always pass `userId` in metadata; can't link subscription to user without it\n","# Stripe Integration Expert\n\n**Tier:** POWERFUL  \n**Category:** Engineering Team  \n**Domain:** Payments \u002F Billing Infrastructure\n\n---\n\n## Overview\n\nImplement production-grade Stripe integrations: subscriptions with trials and proration, one-time payments, usage-based billing, checkout sessions, idempotent webhook handlers, customer portal, and invoicing. Covers Next.js, Express, and Django patterns.\n\n---\n\n## Core Capabilities\n\n- Subscription lifecycle management (create, upgrade, downgrade, cancel, pause)\n- Trial handling and conversion tracking\n- Proration calculation and credit application\n- Usage-based billing with metered pricing\n- Idempotent webhook handlers with signature verification\n- Customer portal integration\n- Invoice generation and PDF access\n- Full Stripe CLI local testing setup\n\n---\n\n## When to Use\n\n- Adding subscription billing to any web app\n- Implementing plan upgrades\u002Fdowngrades with proration\n- Building usage-based or seat-based billing\n- Debugging webhook delivery failures\n- Migrating from one billing model to another\n\n---\n\n## Subscription Lifecycle State Machine\n\n```\nFREE_TRIAL ──paid──► ACTIVE ──cancel──► CANCEL_PENDING ──period_end──► CANCELED\n     │                  │                                                    │\n     │               downgrade                                            reactivate\n     │                  ▼                                                    │\n     │             DOWNGRADING ──period_end──► ACTIVE (lower plan)           │\n     │                                                                        │\n     └──trial_end without payment──► PAST_DUE ──payment_failed 3x──► CANCELED\n                                          │\n                                     payment_success\n                                          │\n                                          ▼\n                                        ACTIVE\n```\n\n### DB subscription status values:\n`trialing | active | past_due | canceled | cancel_pending | paused | unpaid`\n\n---\n\n## Stripe Client Setup\n\n```typescript\n\u002F\u002F lib\u002Fstripe.ts\nimport Stripe from \"stripe\"\n\nexport const stripe = new Stripe(process.env.STRIPE_SECRET_KEY!, {\n  apiVersion: \"2024-04-10\",\n  typescript: true,\n  appInfo: {\n    name: \"myapp\",\n    version: \"1.0.0\",\n  },\n})\n\n\u002F\u002F Price IDs by plan (set in env)\nexport const PLANS = {\n  starter: {\n    monthly: process.env.STRIPE_STARTER_MONTHLY_PRICE_ID!,\n    yearly: process.env.STRIPE_STARTER_YEARLY_PRICE_ID!,\n    features: [\"5 projects\", \"10k events\"],\n  },\n  pro: {\n    monthly: process.env.STRIPE_PRO_MONTHLY_PRICE_ID!,\n    yearly: process.env.STRIPE_PRO_YEARLY_PRICE_ID!,\n    features: [\"Unlimited projects\", \"1M events\"],\n  },\n} as const\n```\n\n---\n\n## Checkout Session (Next.js App Router)\n\n```typescript\n\u002F\u002F app\u002Fapi\u002Fbilling\u002Fcheckout\u002Froute.ts\nimport { NextResponse } from \"next\u002Fserver\"\nimport { stripe } from \"@\u002Flib\u002Fstripe\"\nimport { getAuthUser } from \"@\u002Flib\u002Fauth\"\nimport { db } from \"@\u002Flib\u002Fdb\"\n\nexport async function POST(req: Request) {\n  const user = await getAuthUser()\n  if (!user) return NextResponse.json({ error: \"Unauthorized\" }, { status: 401 })\n\n  const { priceId, interval = \"monthly\" } = await req.json()\n\n  \u002F\u002F Get or create Stripe customer\n  let stripeCustomerId = user.stripeCustomerId\n  if (!stripeCustomerId) {\n    const customer = await stripe.customers.create({\n      email: user.email,\n      name: \"username-undefined\"\n      metadata: { userId: user.id },\n    })\n    stripeCustomerId = customer.id\n    await db.user.update({ where: { id: user.id }, data: { stripeCustomerId } })\n  }\n\n  const session = await stripe.checkout.sessions.create({\n    customer: stripeCustomerId,\n    mode: \"subscription\",\n    payment_method_types: [\"card\"],\n    line_items: [{ price: priceId, quantity: 1 }],\n    allow_promotion_codes: true,\n    subscription_data: {\n      trial_period_days: user.hasHadTrial ? undefined : 14,\n      metadata: { userId: user.id },\n    },\n    success_url: `${process.env.NEXT_PUBLIC_APP_URL}\u002Fdashboard?session_id={CHECKOUT_SESSION_ID}`,\n    cancel_url: `${process.env.NEXT_PUBLIC_APP_URL}\u002Fpricing`,\n    metadata: { userId: user.id },\n  })\n\n  return NextResponse.json({ url: session.url })\n}\n```\n\n---\n\n## Subscription Upgrade\u002FDowngrade\n\n```typescript\n\u002F\u002F lib\u002Fbilling.ts\nexport async function changeSubscriptionPlan(\n  subscriptionId: string,\n  newPriceId: string,\n  immediate = false\n) {\n  const subscription = await stripe.subscriptions.retrieve(subscriptionId)\n  const currentItem = subscription.items.data[0]\n\n  if (immediate) {\n    \u002F\u002F Upgrade: apply immediately with proration\n    return stripe.subscriptions.update(subscriptionId, {\n      items: [{ id: currentItem.id, price: newPriceId }],\n      proration_behavior: \"always_invoice\",\n      billing_cycle_anchor: \"unchanged\",\n    })\n  } else {\n    \u002F\u002F Downgrade: apply at period end, no proration\n    return stripe.subscriptions.update(subscriptionId, {\n      items: [{ id: currentItem.id, price: newPriceId }],\n      proration_behavior: \"none\",\n      billing_cycle_anchor: \"unchanged\",\n    })\n  }\n}\n\n\u002F\u002F Preview proration before confirming upgrade\nexport async function previewProration(subscriptionId: string, newPriceId: string) {\n  const subscription = await stripe.subscriptions.retrieve(subscriptionId)\n  const prorationDate = Math.floor(Date.now() \u002F 1000)\n\n  const invoice = await stripe.invoices.retrieveUpcoming({\n    customer: subscription.customer as string,\n    subscription: subscriptionId,\n    subscription_items: [{ id: subscription.items.data[0].id, price: newPriceId }],\n    subscription_proration_date: prorationDate,\n  })\n\n  return {\n    amountDue: invoice.amount_due,\n    prorationDate,\n    lineItems: invoice.lines.data,\n  }\n}\n```\n\n---\n\n## Complete Webhook Handler (Idempotent)\n\n```typescript\n\u002F\u002F app\u002Fapi\u002Fwebhooks\u002Fstripe\u002Froute.ts\nimport { NextResponse } from \"next\u002Fserver\"\nimport { headers } from \"next\u002Fheaders\"\nimport { stripe } from \"@\u002Flib\u002Fstripe\"\nimport { db } from \"@\u002Flib\u002Fdb\"\nimport Stripe from \"stripe\"\n\n\u002F\u002F Processed events table to ensure idempotency\nasync function hasProcessedEvent(eventId: string): Promise\u003Cboolean> {\n  const existing = await db.stripeEvent.findUnique({ where: { id: eventId } })\n  return !!existing\n}\n\nasync function markEventProcessed(eventId: string, type: string) {\n  await db.stripeEvent.create({ data: { id: eventId, type, processedAt: new Date() } })\n}\n\nexport async function POST(req: Request) {\n  const body = await req.text()\n  const signature = headers().get(\"stripe-signature\")!\n\n  let event: Stripe.Event\n  try {\n    event = stripe.webhooks.constructEvent(body, signature, process.env.STRIPE_WEBHOOK_SECRET!)\n  } catch (err) {\n    console.error(\"Webhook signature verification failed:\", err)\n    return NextResponse.json({ error: \"Invalid signature\" }, { status: 400 })\n  }\n\n  \u002F\u002F Idempotency check\n  if (await hasProcessedEvent(event.id)) {\n    return NextResponse.json({ received: true, skipped: true })\n  }\n\n  try {\n    switch (event.type) {\n      case \"checkout.session.completed\":\n        await handleCheckoutCompleted(event.data.object as Stripe.Checkout.Session)\n        break\n\n      case \"customer.subscription.created\":\n      case \"customer.subscription.updated\":\n        await handleSubscriptionUpdated(event.data.object as Stripe.Subscription)\n        break\n\n      case \"customer.subscription.deleted\":\n        await handleSubscriptionDeleted(event.data.object as Stripe.Subscription)\n        break\n\n      case \"invoice.payment_succeeded\":\n        await handleInvoicePaymentSucceeded(event.data.object as Stripe.Invoice)\n        break\n\n      case \"invoice.payment_failed\":\n        await handleInvoicePaymentFailed(event.data.object as Stripe.Invoice)\n        break\n\n      default:\n        console.log(`Unhandled event type: ${event.type}`)\n    }\n\n    await markEventProcessed(event.id, event.type)\n    return NextResponse.json({ received: true })\n  } catch (err) {\n    console.error(`Error processing webhook ${event.type}:`, err)\n    \u002F\u002F Return 500 so Stripe retries — don't mark as processed\n    return NextResponse.json({ error: \"Processing failed\" }, { status: 500 })\n  }\n}\n\nasync function handleCheckoutCompleted(session: Stripe.Checkout.Session) {\n  if (session.mode !== \"subscription\") return\n  \n  const userId = session.metadata?.userId\n  if (!userId) throw new Error(\"No userId in checkout session metadata\")\n\n  const subscription = await stripe.subscriptions.retrieve(session.subscription as string)\n  \n  await db.user.update({\n    where: { id: userId },\n    data: {\n      stripeCustomerId: session.customer as string,\n      stripeSubscriptionId: subscription.id,\n      stripePriceId: subscription.items.data[0].price.id,\n      stripeCurrentPeriodEnd: new Date(subscription.current_period_end * 1000),\n      subscriptionStatus: subscription.status,\n      hasHadTrial: true,\n    },\n  })\n}\n\nasync function handleSubscriptionUpdated(subscription: Stripe.Subscription) {\n  const user = await db.user.findUnique({\n    where: { stripeSubscriptionId: subscription.id },\n  })\n  if (!user) {\n    \u002F\u002F Look up by customer ID as fallback\n    const customer = await db.user.findUnique({\n      where: { stripeCustomerId: subscription.customer as string },\n    })\n    if (!customer) throw new Error(`No user found for subscription ${subscription.id}`)\n  }\n\n  await db.user.update({\n    where: { stripeSubscriptionId: subscription.id },\n    data: {\n      stripePriceId: subscription.items.data[0].price.id,\n      stripeCurrentPeriodEnd: new Date(subscription.current_period_end * 1000),\n      subscriptionStatus: subscription.status,\n      cancelAtPeriodEnd: subscription.cancel_at_period_end,\n    },\n  })\n}\n\nasync function handleSubscriptionDeleted(subscription: Stripe.Subscription) {\n  await db.user.update({\n    where: { stripeSubscriptionId: subscription.id },\n    data: {\n      stripeSubscriptionId: null,\n      stripePriceId: null,\n      stripeCurrentPeriodEnd: null,\n      subscriptionStatus: \"canceled\",\n    },\n  })\n}\n\nasync function handleInvoicePaymentFailed(invoice: Stripe.Invoice) {\n  if (!invoice.subscription) return\n  const attemptCount = invoice.attempt_count\n  \n  await db.user.update({\n    where: { stripeSubscriptionId: invoice.subscription as string },\n    data: { subscriptionStatus: \"past_due\" },\n  })\n\n  if (attemptCount >= 3) {\n    \u002F\u002F Send final dunning email\n    await sendDunningEmail(invoice.customer_email!, \"final\")\n  } else {\n    await sendDunningEmail(invoice.customer_email!, \"retry\")\n  }\n}\n\nasync function handleInvoicePaymentSucceeded(invoice: Stripe.Invoice) {\n  if (!invoice.subscription) return\n\n  await db.user.update({\n    where: { stripeSubscriptionId: invoice.subscription as string },\n    data: {\n      subscriptionStatus: \"active\",\n      stripeCurrentPeriodEnd: new Date(invoice.period_end * 1000),\n    },\n  })\n}\n```\n\n---\n\n## Usage-Based Billing\n\n```typescript\n\u002F\u002F Report usage for metered subscriptions\nexport async function reportUsage(subscriptionItemId: string, quantity: number) {\n  await stripe.subscriptionItems.createUsageRecord(subscriptionItemId, {\n    quantity,\n    timestamp: Math.floor(Date.now() \u002F 1000),\n    action: \"increment\",\n  })\n}\n\n\u002F\u002F Example: report API calls in middleware\nexport async function trackApiCall(userId: string) {\n  const user = await db.user.findUnique({ where: { id: userId } })\n  if (user?.stripeSubscriptionId) {\n    const subscription = await stripe.subscriptions.retrieve(user.stripeSubscriptionId)\n    const meteredItem = subscription.items.data.find(\n      (item) => item.price.recurring?.usage_type === \"metered\"\n    )\n    if (meteredItem) {\n      await reportUsage(meteredItem.id, 1)\n    }\n  }\n}\n```\n\n---\n\n## Customer Portal\n\n```typescript\n\u002F\u002F app\u002Fapi\u002Fbilling\u002Fportal\u002Froute.ts\nimport { NextResponse } from \"next\u002Fserver\"\nimport { stripe } from \"@\u002Flib\u002Fstripe\"\nimport { getAuthUser } from \"@\u002Flib\u002Fauth\"\n\nexport async function POST() {\n  const user = await getAuthUser()\n  if (!user?.stripeCustomerId) {\n    return NextResponse.json({ error: \"No billing account\" }, { status: 400 })\n  }\n\n  const portalSession = await stripe.billingPortal.sessions.create({\n    customer: user.stripeCustomerId,\n    return_url: `${process.env.NEXT_PUBLIC_APP_URL}\u002Fsettings\u002Fbilling`,\n  })\n\n  return NextResponse.json({ url: portalSession.url })\n}\n```\n\n---\n\n## Testing with Stripe CLI\n\n```bash\n# Install Stripe CLI\nbrew install stripe\u002Fstripe-cli\u002Fstripe\n\n# Login\nstripe login\n\n# Forward webhooks to local dev\nstripe listen --forward-to localhost:3000\u002Fapi\u002Fwebhooks\u002Fstripe\n\n# Trigger specific events for testing\nstripe trigger checkout.session.completed\nstripe trigger customer.subscription.updated\nstripe trigger invoice.payment_failed\n\n# Test with specific customer\nstripe trigger customer.subscription.updated \\\n  --override subscription:customer=cus_xxx\n\n# View recent events\nstripe events list --limit 10\n\n# Test cards\n# Success: 4242 4242 4242 4242\n# Requires auth: 4000 0025 0000 3155\n# Decline: 4000 0000 0000 9995\n# Insufficient funds: 4000 0000 0000 9995\n```\n\n---\n\n## Feature Gating Helper\n\n```typescript\n\u002F\u002F lib\u002Fsubscription.ts\nexport function isSubscriptionActive(user: { subscriptionStatus: string | null, stripeCurrentPeriodEnd: Date | null }) {\n  if (!user.subscriptionStatus) return false\n  if (user.subscriptionStatus === \"active\" || user.subscriptionStatus === \"trialing\") return true\n  \u002F\u002F Grace period: past_due but not yet expired\n  if (user.subscriptionStatus === \"past_due\" && user.stripeCurrentPeriodEnd) {\n    return user.stripeCurrentPeriodEnd > new Date()\n  }\n  return false\n}\n\n\u002F\u002F Middleware usage\nexport async function requireActiveSubscription() {\n  const user = await getAuthUser()\n  if (!isSubscriptionActive(user)) {\n    redirect(\"\u002Fbilling?reason=subscription_required\")\n  }\n}\n```\n\n---\n\n## Common Pitfalls\n\n- **Webhook delivery order not guaranteed** — always re-fetch from Stripe API, never trust event data alone for DB updates\n- **Double-processing webhooks** — Stripe retries on 500; always use idempotency table\n- **Trial conversion tracking** — store `hasHadTrial: true` in DB to prevent trial abuse\n- **Proration surprises** — always preview proration before upgrade; show user the amount before confirming\n- **Customer portal not configured** — must enable features in Stripe dashboard under Billing → Customer portal settings\n- **Missing metadata on checkout** — always pass `userId` in metadata; can't link subscription to user without it\n",{"name":5,"description":7},"devin\u002F1780503568-install-devin-skills","c1c6a7ac191f1fb795ae7f57f2fbfa600d3ef56b",".devin\u002Fskills\u002Fstripe-integration-expert",0,"https:\u002F\u002Fgithub.com\u002Fkruxshnx\u002Fclaude-skills-devin","https:\u002F\u002Fgithub.com\u002Fkruxshnx","https:\u002F\u002Fgovinda-krishna.vercel.app\u002F","2026-06-04 00:21:41",{"source":8,"skillName":5,"commands":33,"prompt":43,"zipAvailable":44},[34,37,40],{"tool":35,"command":36},"npx","npx skills add kruxshnx\u002Fclaude-skills-devin --skill stripe-integration-expert",{"tool":38,"command":39},"bunx","bunx skills add kruxshnx\u002Fclaude-skills-devin --skill stripe-integration-expert",{"tool":41,"command":42},"pnpm","pnpm dlx skills add kruxshnx\u002Fclaude-skills-devin --skill stripe-integration-expert","安装技能，技能地址：https:\u002F\u002Fgithub.com\u002Fkruxshnx\u002Fclaude-skills-devin\u002Fblob\u002Fdevin\u002F1780503568-install-devin-skills\u002F.devin\u002Fskills\u002Fstripe-integration-expert\u002FSKILL.md",true,[],[47,55,62,69,76,83],{"skillNo":48,"name":49,"nameZh":6,"description":50,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":51,"categories":52,"keywords":53,"publishedAt":54},"01M779G0P3W78CJF700K9AHJ6M","syllabus","Generates a curated supplementary reading list from any course syllabus using Consensus academic search. Grill-me intake (syllabus input format + course audience + year range) plus a grouping forcing-options checkpoint before any search runs — so the reading list matches the course's level and recency need. Parses the syllabus to extract topics and learning outcomes, searches Consensus for recent peer-reviewed papers per topic, and produces a professionally formatted .docx with clickable Consensus links, plain-language summaries calibrated to audience level, and Bloom-higher-order discussion questions tied to course learning goals. Triggers whenever a user uploads a syllabus, course outline, or curriculum document and wants supplementary readings. Also triggers on: 'syllabus reading list', 'find papers for my course', 'create a reading list from this syllabus', 'recent research for my class', 'supplementary readings', 'find journal articles for these topics', 'what recent papers cover this material', 'any new research on these course topics', 'update my syllabus with recent papers'. Even casual mentions when a syllabus is attached should trigger this skill.","https:\u002F\u002Fgithub.com\u002Fkruxshnx\u002Fclaude-skills-devin\u002Fblob\u002Fdevin\u002F1780503568-install-devin-skills\u002Fresearch\u002Fsyllabus\u002Fskills\u002Fsyllabus\u002FSKILL.md",[],[],"2026-11-15 14:19:17",{"skillNo":56,"name":57,"nameZh":6,"description":58,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":59,"categories":60,"keywords":61,"publishedAt":54},"01M779FBBF54JKVQAGBAYHWE0B","research","Default entry point for any research request — a hybrid router that classifies the question deterministically and either delegates to a specialist research skill (pulse for trends\u002Fsentiment, grants for NIH funding, litreview for academic literature, syllabus for course reading, patent for prior-art + IP landscape, dossier for entity research) or runs its own plan-decompose-multi-source-search-synthesize-cite fallback workflow when no specialist matches. Always surfaces the routing decision so users can override. Triggers — \"research [topic]\", \"look into [topic]\", \"what do we know about [topic]\", \"investigate [topic]\", \"find me information on [topic]\", \"do some research on [topic]\", \"I need to understand [topic]\", or any research request that doesn't obviously match a more-specific specialist skill. Output is a markdown briefing (default) or .docx document (on request) with full citations and an audit log.","https:\u002F\u002Fgithub.com\u002Fkruxshnx\u002Fclaude-skills-devin\u002Fblob\u002Fdevin\u002F1780503568-install-devin-skills\u002Fresearch\u002Fresearch\u002Fskills\u002Fresearch\u002FSKILL.md",[],[],{"skillNo":63,"name":64,"nameZh":6,"description":65,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":66,"categories":67,"keywords":68,"publishedAt":54},"01M779EQ39CGK5Q4V78KC0HNMV","pulse","Multi-source recency research skill that takes the pulse of any topic across Reddit, Hacker News, the open web, and optionally X\u002FTwitter within a configurable recent window (default 30 days). Forcing intake clarifies topic specificity, angle (trend\u002Fsentiment\u002Fproblems\u002Fopportunities\u002Fcomparison), time window, and platform scope before searching. Returns a synthesized briefing with citations, engagement metrics, and cross-platform pattern analysis. Triggers: 'pulse on [topic]', 'what's happening with [topic]', 'what are people saying about [topic]', 'current conversation about [topic]', 'take the pulse of [topic]', 'trending: [topic]', 'find me info on [topic]', or any variation requesting multi-source recency intelligence on a topic. Also use for competitor research, trend discovery, tool comparisons, and audience sentiment analysis.","https:\u002F\u002Fgithub.com\u002Fkruxshnx\u002Fclaude-skills-devin\u002Fblob\u002Fdevin\u002F1780503568-install-devin-skills\u002Fresearch\u002Fpulse\u002Fskills\u002Fpulse\u002FSKILL.md",[],[],{"skillNo":70,"name":71,"nameZh":6,"description":72,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":73,"categories":74,"keywords":75,"publishedAt":54},"01M779EDS05MYFXBF7PGTVSDMA","patent","Patent prior-art and landscape intelligence skill — not generic patent help. Commits to one of five sub-use-cases via forcing intake (novelty search \u002F freedom-to-operate \u002F competitive landscape \u002F acquisition diligence \u002F litigation prior-art) before any search runs. Searches Google Patents, Espacenet, USPTO, and optionally Lens.org for citation-graph signals. Output is an editable Word document (.docx) with verdict, ranked closest art (claim-text extracted), CPC-class-aware landscape, family-resolved hits, geographic coverage, FTO flags where applicable, strategy recommendations, and full audit log. Triggers: 'prior art search for [invention]', 'patent search on [topic]', 'freedom to operate analysis', 'FTO for [product]', 'patent landscape for [field]', 'is [invention] novel', 'patents on [topic]', 'competitive patent analysis', 'prior art for litigation', 'patent diligence on [company]'. Produces search signal, not legal advice — always recommends consulting a patent attorney before filing or licensing decisions. Trademark, copyright, and trade-secret questions are out of scope.","https:\u002F\u002Fgithub.com\u002Fkruxshnx\u002Fclaude-skills-devin\u002Fblob\u002Fdevin\u002F1780503568-install-devin-skills\u002Fresearch\u002Fpatent\u002Fskills\u002Fpatent\u002FSKILL.md",[],[],{"skillNo":77,"name":78,"nameZh":6,"description":79,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":80,"categories":81,"keywords":82,"publishedAt":54},"01M779DVA52T5F0YC5HSM9BW4Z","notebooklm","Browser automation skill for controlling Google's NotebookLM. Handles reading and querying notebooks, adding sources (URLs, text, files, YouTube links, synthesized content), generating Studio outputs (Audio Overview, infographics, slide decks, study guides, briefing docs, mind maps, timelines, FAQs), and creating new notebooks. Triggers on any phrase involving NotebookLM — 'open NotebookLM', 'check my [name] notebook', 'pull info from NotebookLM', 'ask my notebook about X', 'add [source] to NotebookLM', 'create an infographic in NotebookLM', 'use NotebookLM Studio', 'generate a slide deck from my notebook', or any variation where the goal involves NotebookLM. Requires browser automation environment — fails gracefully when unavailable.","https:\u002F\u002Fgithub.com\u002Fkruxshnx\u002Fclaude-skills-devin\u002Fblob\u002Fdevin\u002F1780503568-install-devin-skills\u002Fresearch\u002Fnotebooklm\u002Fskills\u002Fnotebooklm\u002FSKILL.md",[],[],{"skillNo":84,"name":85,"nameZh":6,"description":86,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":87,"categories":88,"keywords":89,"publishedAt":54},"01M779D3SGW8FM1N8G0HK860WT","litreview","Academic literature orientation skill that searches papers via Consensus, builds a strategic search plan using PICO (default) or SPIDER \u002F Decomposition \u002F hybrid as fallbacks, and synthesizes findings into a professionally formatted Word document (.docx) research guide. Grill-me intake (research question specificity + framework hint + tentative depth) before the recon search; a second forcing checkpoint after Phase 2 confirms framework + sub-areas + depth before searches consume budget. Configurable depth (5\u002F10\u002F20 queries) controls coverage vs. speed. Output is a 'launching pad' — not a finished review, but an orientation guide that lets a researcher dive in confidently. Triggers: 'litreview on [topic]', 'literature review on [topic]', 'I'm starting a literature review on X', 'I'm writing a paper on X', 'help me research X', 'I'm doing research on X', 'can you help me research X'. Do NOT trigger for single one-off paper searches where the user just wants a quick list — that's a plain Consensus search.","https:\u002F\u002Fgithub.com\u002Fkruxshnx\u002Fclaude-skills-devin\u002Fblob\u002Fdevin\u002F1780503568-install-devin-skills\u002Fresearch\u002Flitreview\u002Fskills\u002Flitreview\u002FSKILL.md",[],[]]