[{"data":1,"prerenderedAt":-1},["ShallowReactive",2],{"skill:01M6NW9ZY59SEC5X673D7E120D":3,"skill-same:01M6NW9ZY59SEC5X673D7E120D":63},{"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":36,"linkOnly":37,"markdownContent":38,"markdownBody":39,"frontMatter":40,"refName":41,"commitSha":42,"skillDirectory":43,"forksCount":14,"repositoryHtmlUrl":44,"repositoryHomepageUrl":6,"ownerHtmlUrl":45,"ownerBlogUrl":46,"ownerDescription":47,"updatedAt":48,"install":49,"resources":62},"01M6NW9ZY59SEC5X673D7E120D","saas-payment-patterns",null,"Payment provider abstraction, webhook security, subscription lifecycle, dunning flows, pricing models, invoicing, tax handling, and refund patterns for SaaS applications.","rubicanjr\u002FFinCognis","rubicanjr","https:\u002F\u002Favatars.githubusercontent.com\u002Fu\u002F234912519?v=4","01M6NT156NND8J474G34SB3923","Rubi","01M6NT15B70RWXE1N3YV0BZY8A",0,"MIT","https:\u002F\u002Fgithub.com\u002Frubicanjr\u002FFinCognis\u002Fblob\u002Fmain\u002Fskills\u002Fsaas-payment-patterns\u002FSKILL.md",[],[19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35],"patterns","saas payment patterns","payment","saas","applications","lifecycle","tax","models","provider","security","webhook","subscription lifecycle","webhook security","flows","for","refund","pricing","2026-11-10 10:12:30",false,"---\nname: saas-payment-patterns\ndescription: Payment provider abstraction, webhook security, subscription lifecycle, dunning flows, pricing models, invoicing, tax handling, and refund patterns for SaaS applications.\n---\n\n# SaaS Payment Patterns\n\nProvider-agnostic payment patterns for subscription-based applications. Works with Stripe, Paddle, LemonSqueezy, or any billing provider.\n\n## Payment Provider Abstraction Layer\n\n```typescript\n\u002F\u002F Abstract away the provider — swap Stripe for Paddle without touching business logic\n\ninterface PaymentProvider {\n  createCustomer(data: CreateCustomerDto): Promise\u003CCustomer>\n  createSubscription(data: CreateSubscriptionDto): Promise\u003CSubscription>\n  cancelSubscription(subscriptionId: string, immediate?: boolean): Promise\u003Cvoid>\n  createCheckoutSession(data: CheckoutDto): Promise\u003C{ url: string }>\n  issueRefund(paymentId: string, amountCents?: number): Promise\u003CRefund>\n  getInvoice(invoiceId: string): Promise\u003CInvoice>\n  verifyWebhookSignature(payload: string, signature: string): boolean\n}\n\ninterface Customer { id: string; email: string; providerCustomerId: string }\ninterface Subscription {\n  id: string\n  status: SubscriptionStatus\n  planId: string\n  currentPeriodEnd: Date\n  cancelAtPeriodEnd: boolean\n}\ntype SubscriptionStatus = 'trialing' | 'active' | 'past_due' | 'canceled' | 'expired'\n\n\u002F\u002F Provider implementation (Stripe example)\nclass StripePaymentProvider implements PaymentProvider {\n  constructor(private stripe: Stripe) {}\n\n  async createCustomer(data: CreateCustomerDto): Promise\u003CCustomer> {\n    const stripeCustomer = await this.stripe.customers.create({\n      email: data.email,\n      metadata: { internalUserId: data.userId }\n    })\n    return {\n      id: data.userId,\n      email: data.email,\n      providerCustomerId: stripeCustomer.id\n    }\n  }\n\n  \u002F\u002F ... other methods follow the same translation pattern\n}\n\n\u002F\u002F Usage — business logic never imports Stripe\u002FPaddle directly\nclass BillingService {\n  constructor(private provider: PaymentProvider, private db: Database) {}\n\n  async startSubscription(userId: string, planId: string): Promise\u003CSubscription> {\n    const customer = await this.db.customers.findByUserId(userId)\n    return this.provider.createSubscription({\n      customerId: customer.providerCustomerId,\n      planId,\n      trialDays: 14\n    })\n  }\n}\n```\n\n## Webhook Security\n\n```typescript\n\u002F\u002F GOOD: Verify signature, enforce idempotency, protect against replay\nasync function handleWebhook(req: Request): Promise\u003CResponse> {\n  const payload = await req.text()\n  const signature = req.headers.get('x-webhook-signature') ?? ''\n  const eventId = req.headers.get('x-webhook-id') ?? ''\n  const timestamp = req.headers.get('x-webhook-timestamp') ?? ''\n\n  \u002F\u002F 1. Verify cryptographic signature\n  if (!provider.verifyWebhookSignature(payload, signature)) {\n    return new Response('Invalid signature', { status: 401 })\n  }\n\n  \u002F\u002F 2. Replay protection — reject events older than 5 minutes\n  const timestampMs = new Date(timestamp).getTime()\n  if (isNaN(timestampMs)) {\n    return new Response('Invalid timestamp', { status: 400 })\n  }\n  const eventAge = Date.now() - timestampMs\n  if (eventAge > 5 * 60 * 1000 || eventAge \u003C -60 * 1000) {\n    return new Response('Event too old or clock skew', { status: 400 })\n  }\n\n  \u002F\u002F 3. Idempotency — process each event exactly once\n  const alreadyProcessed = await db.webhookEvents.findUnique({\n    where: { eventId }\n  })\n  if (alreadyProcessed) {\n    return new Response('Already processed', { status: 200 })\n  }\n\n  \u002F\u002F 4. Process inside a transaction\n  await db.$transaction(async (tx) => {\n    await tx.webhookEvents.create({\n      data: { eventId, payload, processedAt: new Date() }\n    })\n    const event = JSON.parse(payload)\n    await routeWebhookEvent(event, tx)\n  })\n\n  return new Response('OK', { status: 200 })\n}\n\n\u002F\u002F BAD: Fire-and-forget webhook handler\nasync function handleWebhookBad(req: Request): Promise\u003CResponse> {\n  const event = await req.json()      \u002F\u002F No signature verification\n  await processEvent(event)            \u002F\u002F No idempotency check\n  return new Response('OK')            \u002F\u002F No replay protection\n  \u002F\u002F Result: anyone can POST fake events, duplicate processing, replay attacks\n}\n```\n\n## Subscription Lifecycle\n\n```typescript\n\u002F\u002F State machine: trialing -> active -> past_due -> canceled -> expired\n\u002F\u002F                                  \\-> canceled (voluntary)\n\ntype LifecycleEvent =\n  | { type: 'trial_started'; trialEndsAt: Date }\n  | { type: 'trial_converted' }\n  | { type: 'payment_succeeded' }\n  | { type: 'payment_failed'; attemptNumber: number }\n  | { type: 'subscription_canceled'; reason: string }\n  | { type: 'subscription_expired' }\n\nasync function handleLifecycleEvent(\n  subscriptionId: string,\n  event: LifecycleEvent,\n  tx: Transaction\n): Promise\u003Cvoid> {\n  const sub = await tx.subscriptions.findUniqueOrThrow({\n    where: { id: subscriptionId }\n  })\n\n  switch (event.type) {\n    case 'trial_started':\n      await tx.subscriptions.update({\n        where: { id: subscriptionId },\n        data: { status: 'trialing', trialEndsAt: event.trialEndsAt }\n      })\n      await scheduleEmail(sub.userId, 'trial-welcome')\n      await scheduleEmail(sub.userId, 'trial-ending-soon', {\n        sendAt: subDays(event.trialEndsAt, 3)\n      })\n      break\n\n    case 'payment_succeeded':\n      await tx.subscriptions.update({\n        where: { id: subscriptionId },\n        data: { status: 'active', pastDueAt: null }\n      })\n      await clearDunningState(sub.userId, tx)\n      break\n\n    case 'payment_failed':\n      await tx.subscriptions.update({\n        where: { id: subscriptionId },\n        data: { status: 'past_due', pastDueAt: new Date() }\n      })\n      await startDunningFlow(sub, event.attemptNumber, tx)\n      break\n\n    case 'subscription_canceled':\n      await tx.subscriptions.update({\n        where: { id: subscriptionId },\n        data: { status: 'canceled', canceledAt: new Date(), cancelReason: event.reason }\n      })\n      await revokeAccess(sub.userId, sub.currentPeriodEnd, tx) \u002F\u002F access until period end\n      await scheduleEmail(sub.userId, 'cancellation-feedback')\n      break\n\n    case 'subscription_expired':\n      await tx.subscriptions.update({\n        where: { id: subscriptionId },\n        data: { status: 'expired' }\n      })\n      await revokeAccessImmediate(sub.userId, tx)\n      await scheduleEmail(sub.userId, 'win-back', { sendAt: addDays(new Date(), 7) })\n      break\n  }\n}\n```\n\n## Dunning Flow (Failed Payment Recovery)\n\n```typescript\n\u002F\u002F Dunning = systematic retry and communication when payment fails\n\u002F\u002F Goal: recover revenue before canceling\n\ninterface DunningConfig {\n  retrySchedule: number[]     \u002F\u002F days between retries\n  gracePeriodDays: number     \u002F\u002F total days before cancellation\n  downgradeAfterDays: number  \u002F\u002F days before downgrading to free tier\n}\n\nconst defaultDunning: DunningConfig = {\n  retrySchedule: [1, 3, 5, 7],     \u002F\u002F retry on day 1, 3, 5, 7\n  gracePeriodDays: 14,               \u002F\u002F cancel after 14 days\n  downgradeAfterDays: 7              \u002F\u002F downgrade to free on day 7\n}\n\nasync function startDunningFlow(\n  sub: Subscription,\n  attemptNumber: number,\n  tx: Transaction\n): Promise\u003Cvoid> {\n  const config = defaultDunning\n\n  \u002F\u002F Email sequence based on attempt number\n  const emailTemplates = [\n    'payment-failed-soft',        \u002F\u002F Attempt 1: \"Your payment didn't go through\"\n    'payment-failed-update-card',  \u002F\u002F Attempt 2: \"Please update your card\"\n    'payment-failed-urgent',       \u002F\u002F Attempt 3: \"You will lose access soon\"\n    'payment-failed-final'         \u002F\u002F Attempt 4: \"Last chance before cancellation\"\n  ]\n\n  const template = emailTemplates[Math.min(attemptNumber - 1, emailTemplates.length - 1)]\n  await scheduleEmail(sub.userId, template)\n\n  \u002F\u002F Downgrade after threshold\n  const daysSinceFailure = differenceInDays(new Date(), sub.pastDueAt!)\n  if (daysSinceFailure >= config.downgradeAfterDays) {\n    await downgradeToFree(sub.userId, tx)\n    await scheduleEmail(sub.userId, 'downgraded-to-free')\n  }\n\n  \u002F\u002F Cancel after grace period\n  if (daysSinceFailure >= config.gracePeriodDays) {\n    await provider.cancelSubscription(sub.providerSubscriptionId, true)\n  }\n}\n```\n\n## Pricing Model Patterns\n\n```typescript\n\u002F\u002F Support multiple pricing models from a single schema\n\ntype PricingModel =\n  | { type: 'flat'; amountCents: number }\n  | { type: 'tiered'; tiers: PricingTier[] }\n  | { type: 'per_seat'; pricePerSeatCents: number; includedSeats: number }\n  | { type: 'usage_based'; unitPriceCents: number; metricKey: string }\n\ninterface PricingTier {\n  upTo: number | null   \u002F\u002F null = unlimited\n  unitPriceCents: number\n}\n\nfunction calculateAmount(model: PricingModel, quantity: number): number {\n  switch (model.type) {\n    case 'flat':\n      return model.amountCents\n\n    case 'per_seat': {\n      const billableSeats = Math.max(0, quantity - model.includedSeats)\n      return billableSeats * model.pricePerSeatCents\n    }\n\n    case 'tiered': {\n      let total = 0\n      let remaining = quantity\n      let previousLimit = 0\n      for (const tier of model.tiers) {\n        const tierLimit = tier.upTo ?? Infinity\n        const tierCapacity = tierLimit - previousLimit\n        const unitsInTier = Math.min(remaining, tierCapacity)\n        total += unitsInTier * tier.unitPriceCents\n        remaining -= unitsInTier\n        previousLimit = tierLimit\n        if (remaining \u003C= 0) break\n      }\n      return total\n    }\n\n    case 'usage_based':\n      return quantity * model.unitPriceCents\n  }\n}\n\n\u002F\u002F Example tier definition\nconst apiPricing: PricingModel = {\n  type: 'tiered',\n  tiers: [\n    { upTo: 1000, unitPriceCents: 0 },       \u002F\u002F first 1K free\n    { upTo: 10000, unitPriceCents: 1 },       \u002F\u002F next 9K at $0.01\u002Fcall\n    { upTo: null, unitPriceCents: 0.5 }       \u002F\u002F above 10K at $0.005\u002Fcall\n  ]\n}\n```\n\n## Invoice and Receipt Generation\n\n```typescript\ninterface InvoiceLineItem {\n  description: string\n  quantity: number\n  unitPriceCents: number\n  amountCents: number\n}\n\ninterface Invoice {\n  id: string\n  customerId: string\n  status: 'draft' | 'open' | 'paid' | 'void'\n  lineItems: InvoiceLineItem[]\n  subtotalCents: number\n  taxCents: number\n  totalCents: number\n  currency: string\n  issuedAt: Date\n  dueAt: Date\n  paidAt: Date | null\n  taxDetails: TaxDetails | null\n}\n\nasync function generateInvoice(\n  subscriptionId: string,\n  periodStart: Date,\n  periodEnd: Date\n): Promise\u003CInvoice> {\n  const sub = await db.subscriptions.findUniqueOrThrow({\n    where: { id: subscriptionId },\n    include: { plan: true, customer: true }\n  })\n\n  const lineItems: InvoiceLineItem[] = [{\n    description: `${sub.plan.name} (${formatDate(periodStart)} - ${formatDate(periodEnd)})`,\n    quantity: 1,\n    unitPriceCents: sub.plan.priceCents,\n    amountCents: sub.plan.priceCents\n  }]\n\n  \u002F\u002F Add usage-based line items if applicable\n  if (sub.plan.pricing.type === 'usage_based') {\n    const usage = await getUsageForPeriod(sub.id, periodStart, periodEnd)\n    const usageAmount = calculateAmount(sub.plan.pricing, usage.total)\n    lineItems.push({\n      description: `API calls: ${usage.total} units`,\n      quantity: usage.total,\n      unitPriceCents: sub.plan.pricing.unitPriceCents,\n      amountCents: usageAmount\n    })\n  }\n\n  const subtotalCents = lineItems.reduce((sum, li) => sum + li.amountCents, 0)\n  const taxDetails = await calculateTax(sub.customer, subtotalCents)\n\n  return db.invoices.create({\n    data: {\n      customerId: sub.customerId,\n      status: 'open',\n      lineItems,\n      subtotalCents,\n      taxCents: taxDetails.taxAmountCents,\n      totalCents: subtotalCents + taxDetails.taxAmountCents,\n      currency: sub.plan.currency,\n      issuedAt: new Date(),\n      dueAt: addDays(new Date(), 30),\n      paidAt: null,\n      taxDetails\n    }\n  })\n}\n```\n\n## Tax Handling (VAT\u002FGST)\n\n```typescript\n\u002F\u002F GOOD: Tax calculation abstracted, provider handles compliance\ninterface TaxDetails {\n  taxable: boolean\n  taxRate: number           \u002F\u002F 0.20 for 20% VAT\n  taxAmountCents: number\n  taxType: 'vat' | 'gst' | 'sales_tax' | 'none'\n  jurisdiction: string      \u002F\u002F \"EU-DE\", \"AU\", \"US-CA\"\n  reverseCharge: boolean    \u002F\u002F B2B within EU with valid VAT ID\n}\n\ninterface TaxProvider {\n  calculateTax(customer: Customer, amountCents: number): Promise\u003CTaxDetails>\n  validateTaxId(taxId: string, country: string): Promise\u003Cboolean>\n}\n\nasync function calculateTax(\n  customer: Customer,\n  amountCents: number\n): Promise\u003CTaxDetails> {\n  \u002F\u002F If customer has a valid tax ID and is B2B, reverse charge may apply\n  if (customer.taxId) {\n    const isValid = await taxProvider.validateTaxId(customer.taxId, customer.country)\n    if (isValid && isReverseChargeEligible(customer.country, sellerCountry)) {\n      return {\n        taxable: false,\n        taxRate: 0,\n        taxAmountCents: 0,\n        taxType: 'vat',\n        jurisdiction: `EU-${customer.country}`,\n        reverseCharge: true\n      }\n    }\n  }\n\n  return taxProvider.calculateTax(customer, amountCents)\n}\n\n\u002F\u002F Key rules:\n\u002F\u002F - Store tax details on every invoice (audit trail)\n\u002F\u002F - B2C in EU: charge VAT at customer country rate\n\u002F\u002F - B2B in EU with valid VAT ID: reverse charge (0% VAT)\n\u002F\u002F - US: sales tax varies by state, use a tax API\n\u002F\u002F - Let the payment provider (Stripe Tax, Paddle) handle compliance when possible\n```\n\n## Refund and Proration\n\n```typescript\ninterface RefundResult {\n  refundId: string\n  amountCents: number\n  reason: string\n  prorated: boolean\n}\n\nasync function processRefund(\n  subscriptionId: string,\n  requestingUserId: string,\n  reason: string,\n  fullRefund: boolean\n): Promise\u003CRefundResult> {\n  const sub = await db.subscriptions.findUniqueOrThrow({\n    where: { id: subscriptionId },\n    include: { latestInvoice: true, customer: true }\n  })\n\n  \u002F\u002F SECURITY: Verify the requesting user owns this subscription\n  if (sub.customer.userId !== requestingUserId) {\n    throw new AuthError('Not authorized to refund this subscription')\n  }\n\n  let refundAmountCents: number\n  let prorated = false\n\n  if (fullRefund) {\n    refundAmountCents = sub.latestInvoice.totalCents\n  } else {\n    \u002F\u002F Prorate: refund unused portion of current period\n    const totalDays = differenceInDays(sub.currentPeriodEnd, sub.currentPeriodStart)\n    const usedDays = differenceInDays(new Date(), sub.currentPeriodStart)\n    const unusedRatio = Math.max(0, (totalDays - usedDays) \u002F totalDays)\n    refundAmountCents = Math.round(sub.latestInvoice.totalCents * unusedRatio)\n    prorated = true\n  }\n\n  const refund = await provider.issueRefund(\n    sub.latestInvoice.providerPaymentId,\n    refundAmountCents\n  )\n\n  await db.refunds.create({\n    data: {\n      subscriptionId,\n      invoiceId: sub.latestInvoice.id,\n      amountCents: refundAmountCents,\n      reason,\n      prorated,\n      providerRefundId: refund.id,\n      processedAt: new Date()\n    }\n  })\n\n  return {\n    refundId: refund.id,\n    amountCents: refundAmountCents,\n    reason,\n    prorated\n  }\n}\n\n\u002F\u002F Plan change with proration\nasync function changePlan(\n  subscriptionId: string,\n  newPlanId: string\n): Promise\u003Cvoid> {\n  const sub = await db.subscriptions.findUniqueOrThrow({\n    where: { id: subscriptionId },\n    include: { plan: true }\n  })\n  const newPlan = await db.plans.findUniqueOrThrow({ where: { id: newPlanId } })\n\n  \u002F\u002F Upgrade: charge prorated difference immediately\n  \u002F\u002F Downgrade: credit prorated difference to next invoice\n  const isUpgrade = newPlan.priceCents > sub.plan.priceCents\n\n  await provider.updateSubscription(sub.providerSubscriptionId, {\n    planId: newPlan.providerPlanId,\n    prorationBehavior: isUpgrade ? 'create_prorations' : 'always_invoice'\n  })\n}\n```\n\n## Webhook Event Routing\n\n```typescript\n\u002F\u002F Map provider events to internal handlers — single entry point\n\ntype WebhookHandler = (data: unknown, tx: Transaction) => Promise\u003Cvoid>\n\nconst webhookHandlers: Record\u003Cstring, WebhookHandler> = {\n  'subscription.created':       handleSubscriptionCreated,\n  'subscription.updated':       handleSubscriptionUpdated,\n  'subscription.canceled':      handleSubscriptionCanceled,\n  'invoice.paid':               handleInvoicePaid,\n  'invoice.payment_failed':     handlePaymentFailed,\n  'customer.updated':           handleCustomerUpdated,\n  'refund.created':             handleRefundCreated\n}\n\nasync function routeWebhookEvent(\n  event: { type: string; data: unknown },\n  tx: Transaction\n): Promise\u003Cvoid> {\n  const handler = webhookHandlers[event.type]\n\n  if (!handler) {\n    logger.warn(`Unhandled webhook event type: ${event.type}`)\n    return  \u002F\u002F Do not throw — acknowledge unknown events to prevent retries\n  }\n\n  await handler(event.data, tx)\n}\n```\n\n## Common Pitfalls\n\n```\nMissing idempotency on webhooks:\n  Providers retry failed deliveries. Without dedup, you charge or provision twice.\n  -> Store eventId before processing, skip duplicates.\n\nTrusting client-side plan selection:\n  Never let the frontend decide the price. Always resolve plan + price server-side.\n  -> Client sends planId, server looks up price from DB.\n\nForgetting to handle past_due:\n  Users with failed payments keep accessing paid features indefinitely.\n  -> Enforce access checks against subscription status, not just \"has subscription.\"\n\nHardcoding tax rates:\n  Tax rates change, new jurisdictions appear, VAT thresholds shift.\n  -> Use a tax API or let your payment provider handle calculation.\n\nNo grace period on cancellation:\n  Canceling immediately frustrates users who paid for a full period.\n  -> Cancel at period end by default, revoke access only after the paid period.\n```\n\n**Remember**: Your payment provider is a dependency, not your architecture. Abstract it behind an interface so you can switch providers, run in test mode, or support multiple providers for different regions without rewriting business logic.\n","# SaaS Payment Patterns\n\nProvider-agnostic payment patterns for subscription-based applications. Works with Stripe, Paddle, LemonSqueezy, or any billing provider.\n\n## Payment Provider Abstraction Layer\n\n```typescript\n\u002F\u002F Abstract away the provider — swap Stripe for Paddle without touching business logic\n\ninterface PaymentProvider {\n  createCustomer(data: CreateCustomerDto): Promise\u003CCustomer>\n  createSubscription(data: CreateSubscriptionDto): Promise\u003CSubscription>\n  cancelSubscription(subscriptionId: string, immediate?: boolean): Promise\u003Cvoid>\n  createCheckoutSession(data: CheckoutDto): Promise\u003C{ url: string }>\n  issueRefund(paymentId: string, amountCents?: number): Promise\u003CRefund>\n  getInvoice(invoiceId: string): Promise\u003CInvoice>\n  verifyWebhookSignature(payload: string, signature: string): boolean\n}\n\ninterface Customer { id: string; email: string; providerCustomerId: string }\ninterface Subscription {\n  id: string\n  status: SubscriptionStatus\n  planId: string\n  currentPeriodEnd: Date\n  cancelAtPeriodEnd: boolean\n}\ntype SubscriptionStatus = 'trialing' | 'active' | 'past_due' | 'canceled' | 'expired'\n\n\u002F\u002F Provider implementation (Stripe example)\nclass StripePaymentProvider implements PaymentProvider {\n  constructor(private stripe: Stripe) {}\n\n  async createCustomer(data: CreateCustomerDto): Promise\u003CCustomer> {\n    const stripeCustomer = await this.stripe.customers.create({\n      email: data.email,\n      metadata: { internalUserId: data.userId }\n    })\n    return {\n      id: data.userId,\n      email: data.email,\n      providerCustomerId: stripeCustomer.id\n    }\n  }\n\n  \u002F\u002F ... other methods follow the same translation pattern\n}\n\n\u002F\u002F Usage — business logic never imports Stripe\u002FPaddle directly\nclass BillingService {\n  constructor(private provider: PaymentProvider, private db: Database) {}\n\n  async startSubscription(userId: string, planId: string): Promise\u003CSubscription> {\n    const customer = await this.db.customers.findByUserId(userId)\n    return this.provider.createSubscription({\n      customerId: customer.providerCustomerId,\n      planId,\n      trialDays: 14\n    })\n  }\n}\n```\n\n## Webhook Security\n\n```typescript\n\u002F\u002F GOOD: Verify signature, enforce idempotency, protect against replay\nasync function handleWebhook(req: Request): Promise\u003CResponse> {\n  const payload = await req.text()\n  const signature = req.headers.get('x-webhook-signature') ?? ''\n  const eventId = req.headers.get('x-webhook-id') ?? ''\n  const timestamp = req.headers.get('x-webhook-timestamp') ?? ''\n\n  \u002F\u002F 1. Verify cryptographic signature\n  if (!provider.verifyWebhookSignature(payload, signature)) {\n    return new Response('Invalid signature', { status: 401 })\n  }\n\n  \u002F\u002F 2. Replay protection — reject events older than 5 minutes\n  const timestampMs = new Date(timestamp).getTime()\n  if (isNaN(timestampMs)) {\n    return new Response('Invalid timestamp', { status: 400 })\n  }\n  const eventAge = Date.now() - timestampMs\n  if (eventAge > 5 * 60 * 1000 || eventAge \u003C -60 * 1000) {\n    return new Response('Event too old or clock skew', { status: 400 })\n  }\n\n  \u002F\u002F 3. Idempotency — process each event exactly once\n  const alreadyProcessed = await db.webhookEvents.findUnique({\n    where: { eventId }\n  })\n  if (alreadyProcessed) {\n    return new Response('Already processed', { status: 200 })\n  }\n\n  \u002F\u002F 4. Process inside a transaction\n  await db.$transaction(async (tx) => {\n    await tx.webhookEvents.create({\n      data: { eventId, payload, processedAt: new Date() }\n    })\n    const event = JSON.parse(payload)\n    await routeWebhookEvent(event, tx)\n  })\n\n  return new Response('OK', { status: 200 })\n}\n\n\u002F\u002F BAD: Fire-and-forget webhook handler\nasync function handleWebhookBad(req: Request): Promise\u003CResponse> {\n  const event = await req.json()      \u002F\u002F No signature verification\n  await processEvent(event)            \u002F\u002F No idempotency check\n  return new Response('OK')            \u002F\u002F No replay protection\n  \u002F\u002F Result: anyone can POST fake events, duplicate processing, replay attacks\n}\n```\n\n## Subscription Lifecycle\n\n```typescript\n\u002F\u002F State machine: trialing -> active -> past_due -> canceled -> expired\n\u002F\u002F                                  \\-> canceled (voluntary)\n\ntype LifecycleEvent =\n  | { type: 'trial_started'; trialEndsAt: Date }\n  | { type: 'trial_converted' }\n  | { type: 'payment_succeeded' }\n  | { type: 'payment_failed'; attemptNumber: number }\n  | { type: 'subscription_canceled'; reason: string }\n  | { type: 'subscription_expired' }\n\nasync function handleLifecycleEvent(\n  subscriptionId: string,\n  event: LifecycleEvent,\n  tx: Transaction\n): Promise\u003Cvoid> {\n  const sub = await tx.subscriptions.findUniqueOrThrow({\n    where: { id: subscriptionId }\n  })\n\n  switch (event.type) {\n    case 'trial_started':\n      await tx.subscriptions.update({\n        where: { id: subscriptionId },\n        data: { status: 'trialing', trialEndsAt: event.trialEndsAt }\n      })\n      await scheduleEmail(sub.userId, 'trial-welcome')\n      await scheduleEmail(sub.userId, 'trial-ending-soon', {\n        sendAt: subDays(event.trialEndsAt, 3)\n      })\n      break\n\n    case 'payment_succeeded':\n      await tx.subscriptions.update({\n        where: { id: subscriptionId },\n        data: { status: 'active', pastDueAt: null }\n      })\n      await clearDunningState(sub.userId, tx)\n      break\n\n    case 'payment_failed':\n      await tx.subscriptions.update({\n        where: { id: subscriptionId },\n        data: { status: 'past_due', pastDueAt: new Date() }\n      })\n      await startDunningFlow(sub, event.attemptNumber, tx)\n      break\n\n    case 'subscription_canceled':\n      await tx.subscriptions.update({\n        where: { id: subscriptionId },\n        data: { status: 'canceled', canceledAt: new Date(), cancelReason: event.reason }\n      })\n      await revokeAccess(sub.userId, sub.currentPeriodEnd, tx) \u002F\u002F access until period end\n      await scheduleEmail(sub.userId, 'cancellation-feedback')\n      break\n\n    case 'subscription_expired':\n      await tx.subscriptions.update({\n        where: { id: subscriptionId },\n        data: { status: 'expired' }\n      })\n      await revokeAccessImmediate(sub.userId, tx)\n      await scheduleEmail(sub.userId, 'win-back', { sendAt: addDays(new Date(), 7) })\n      break\n  }\n}\n```\n\n## Dunning Flow (Failed Payment Recovery)\n\n```typescript\n\u002F\u002F Dunning = systematic retry and communication when payment fails\n\u002F\u002F Goal: recover revenue before canceling\n\ninterface DunningConfig {\n  retrySchedule: number[]     \u002F\u002F days between retries\n  gracePeriodDays: number     \u002F\u002F total days before cancellation\n  downgradeAfterDays: number  \u002F\u002F days before downgrading to free tier\n}\n\nconst defaultDunning: DunningConfig = {\n  retrySchedule: [1, 3, 5, 7],     \u002F\u002F retry on day 1, 3, 5, 7\n  gracePeriodDays: 14,               \u002F\u002F cancel after 14 days\n  downgradeAfterDays: 7              \u002F\u002F downgrade to free on day 7\n}\n\nasync function startDunningFlow(\n  sub: Subscription,\n  attemptNumber: number,\n  tx: Transaction\n): Promise\u003Cvoid> {\n  const config = defaultDunning\n\n  \u002F\u002F Email sequence based on attempt number\n  const emailTemplates = [\n    'payment-failed-soft',        \u002F\u002F Attempt 1: \"Your payment didn't go through\"\n    'payment-failed-update-card',  \u002F\u002F Attempt 2: \"Please update your card\"\n    'payment-failed-urgent',       \u002F\u002F Attempt 3: \"You will lose access soon\"\n    'payment-failed-final'         \u002F\u002F Attempt 4: \"Last chance before cancellation\"\n  ]\n\n  const template = emailTemplates[Math.min(attemptNumber - 1, emailTemplates.length - 1)]\n  await scheduleEmail(sub.userId, template)\n\n  \u002F\u002F Downgrade after threshold\n  const daysSinceFailure = differenceInDays(new Date(), sub.pastDueAt!)\n  if (daysSinceFailure >= config.downgradeAfterDays) {\n    await downgradeToFree(sub.userId, tx)\n    await scheduleEmail(sub.userId, 'downgraded-to-free')\n  }\n\n  \u002F\u002F Cancel after grace period\n  if (daysSinceFailure >= config.gracePeriodDays) {\n    await provider.cancelSubscription(sub.providerSubscriptionId, true)\n  }\n}\n```\n\n## Pricing Model Patterns\n\n```typescript\n\u002F\u002F Support multiple pricing models from a single schema\n\ntype PricingModel =\n  | { type: 'flat'; amountCents: number }\n  | { type: 'tiered'; tiers: PricingTier[] }\n  | { type: 'per_seat'; pricePerSeatCents: number; includedSeats: number }\n  | { type: 'usage_based'; unitPriceCents: number; metricKey: string }\n\ninterface PricingTier {\n  upTo: number | null   \u002F\u002F null = unlimited\n  unitPriceCents: number\n}\n\nfunction calculateAmount(model: PricingModel, quantity: number): number {\n  switch (model.type) {\n    case 'flat':\n      return model.amountCents\n\n    case 'per_seat': {\n      const billableSeats = Math.max(0, quantity - model.includedSeats)\n      return billableSeats * model.pricePerSeatCents\n    }\n\n    case 'tiered': {\n      let total = 0\n      let remaining = quantity\n      let previousLimit = 0\n      for (const tier of model.tiers) {\n        const tierLimit = tier.upTo ?? Infinity\n        const tierCapacity = tierLimit - previousLimit\n        const unitsInTier = Math.min(remaining, tierCapacity)\n        total += unitsInTier * tier.unitPriceCents\n        remaining -= unitsInTier\n        previousLimit = tierLimit\n        if (remaining \u003C= 0) break\n      }\n      return total\n    }\n\n    case 'usage_based':\n      return quantity * model.unitPriceCents\n  }\n}\n\n\u002F\u002F Example tier definition\nconst apiPricing: PricingModel = {\n  type: 'tiered',\n  tiers: [\n    { upTo: 1000, unitPriceCents: 0 },       \u002F\u002F first 1K free\n    { upTo: 10000, unitPriceCents: 1 },       \u002F\u002F next 9K at $0.01\u002Fcall\n    { upTo: null, unitPriceCents: 0.5 }       \u002F\u002F above 10K at $0.005\u002Fcall\n  ]\n}\n```\n\n## Invoice and Receipt Generation\n\n```typescript\ninterface InvoiceLineItem {\n  description: string\n  quantity: number\n  unitPriceCents: number\n  amountCents: number\n}\n\ninterface Invoice {\n  id: string\n  customerId: string\n  status: 'draft' | 'open' | 'paid' | 'void'\n  lineItems: InvoiceLineItem[]\n  subtotalCents: number\n  taxCents: number\n  totalCents: number\n  currency: string\n  issuedAt: Date\n  dueAt: Date\n  paidAt: Date | null\n  taxDetails: TaxDetails | null\n}\n\nasync function generateInvoice(\n  subscriptionId: string,\n  periodStart: Date,\n  periodEnd: Date\n): Promise\u003CInvoice> {\n  const sub = await db.subscriptions.findUniqueOrThrow({\n    where: { id: subscriptionId },\n    include: { plan: true, customer: true }\n  })\n\n  const lineItems: InvoiceLineItem[] = [{\n    description: `${sub.plan.name} (${formatDate(periodStart)} - ${formatDate(periodEnd)})`,\n    quantity: 1,\n    unitPriceCents: sub.plan.priceCents,\n    amountCents: sub.plan.priceCents\n  }]\n\n  \u002F\u002F Add usage-based line items if applicable\n  if (sub.plan.pricing.type === 'usage_based') {\n    const usage = await getUsageForPeriod(sub.id, periodStart, periodEnd)\n    const usageAmount = calculateAmount(sub.plan.pricing, usage.total)\n    lineItems.push({\n      description: `API calls: ${usage.total} units`,\n      quantity: usage.total,\n      unitPriceCents: sub.plan.pricing.unitPriceCents,\n      amountCents: usageAmount\n    })\n  }\n\n  const subtotalCents = lineItems.reduce((sum, li) => sum + li.amountCents, 0)\n  const taxDetails = await calculateTax(sub.customer, subtotalCents)\n\n  return db.invoices.create({\n    data: {\n      customerId: sub.customerId,\n      status: 'open',\n      lineItems,\n      subtotalCents,\n      taxCents: taxDetails.taxAmountCents,\n      totalCents: subtotalCents + taxDetails.taxAmountCents,\n      currency: sub.plan.currency,\n      issuedAt: new Date(),\n      dueAt: addDays(new Date(), 30),\n      paidAt: null,\n      taxDetails\n    }\n  })\n}\n```\n\n## Tax Handling (VAT\u002FGST)\n\n```typescript\n\u002F\u002F GOOD: Tax calculation abstracted, provider handles compliance\ninterface TaxDetails {\n  taxable: boolean\n  taxRate: number           \u002F\u002F 0.20 for 20% VAT\n  taxAmountCents: number\n  taxType: 'vat' | 'gst' | 'sales_tax' | 'none'\n  jurisdiction: string      \u002F\u002F \"EU-DE\", \"AU\", \"US-CA\"\n  reverseCharge: boolean    \u002F\u002F B2B within EU with valid VAT ID\n}\n\ninterface TaxProvider {\n  calculateTax(customer: Customer, amountCents: number): Promise\u003CTaxDetails>\n  validateTaxId(taxId: string, country: string): Promise\u003Cboolean>\n}\n\nasync function calculateTax(\n  customer: Customer,\n  amountCents: number\n): Promise\u003CTaxDetails> {\n  \u002F\u002F If customer has a valid tax ID and is B2B, reverse charge may apply\n  if (customer.taxId) {\n    const isValid = await taxProvider.validateTaxId(customer.taxId, customer.country)\n    if (isValid && isReverseChargeEligible(customer.country, sellerCountry)) {\n      return {\n        taxable: false,\n        taxRate: 0,\n        taxAmountCents: 0,\n        taxType: 'vat',\n        jurisdiction: `EU-${customer.country}`,\n        reverseCharge: true\n      }\n    }\n  }\n\n  return taxProvider.calculateTax(customer, amountCents)\n}\n\n\u002F\u002F Key rules:\n\u002F\u002F - Store tax details on every invoice (audit trail)\n\u002F\u002F - B2C in EU: charge VAT at customer country rate\n\u002F\u002F - B2B in EU with valid VAT ID: reverse charge (0% VAT)\n\u002F\u002F - US: sales tax varies by state, use a tax API\n\u002F\u002F - Let the payment provider (Stripe Tax, Paddle) handle compliance when possible\n```\n\n## Refund and Proration\n\n```typescript\ninterface RefundResult {\n  refundId: string\n  amountCents: number\n  reason: string\n  prorated: boolean\n}\n\nasync function processRefund(\n  subscriptionId: string,\n  requestingUserId: string,\n  reason: string,\n  fullRefund: boolean\n): Promise\u003CRefundResult> {\n  const sub = await db.subscriptions.findUniqueOrThrow({\n    where: { id: subscriptionId },\n    include: { latestInvoice: true, customer: true }\n  })\n\n  \u002F\u002F SECURITY: Verify the requesting user owns this subscription\n  if (sub.customer.userId !== requestingUserId) {\n    throw new AuthError('Not authorized to refund this subscription')\n  }\n\n  let refundAmountCents: number\n  let prorated = false\n\n  if (fullRefund) {\n    refundAmountCents = sub.latestInvoice.totalCents\n  } else {\n    \u002F\u002F Prorate: refund unused portion of current period\n    const totalDays = differenceInDays(sub.currentPeriodEnd, sub.currentPeriodStart)\n    const usedDays = differenceInDays(new Date(), sub.currentPeriodStart)\n    const unusedRatio = Math.max(0, (totalDays - usedDays) \u002F totalDays)\n    refundAmountCents = Math.round(sub.latestInvoice.totalCents * unusedRatio)\n    prorated = true\n  }\n\n  const refund = await provider.issueRefund(\n    sub.latestInvoice.providerPaymentId,\n    refundAmountCents\n  )\n\n  await db.refunds.create({\n    data: {\n      subscriptionId,\n      invoiceId: sub.latestInvoice.id,\n      amountCents: refundAmountCents,\n      reason,\n      prorated,\n      providerRefundId: refund.id,\n      processedAt: new Date()\n    }\n  })\n\n  return {\n    refundId: refund.id,\n    amountCents: refundAmountCents,\n    reason,\n    prorated\n  }\n}\n\n\u002F\u002F Plan change with proration\nasync function changePlan(\n  subscriptionId: string,\n  newPlanId: string\n): Promise\u003Cvoid> {\n  const sub = await db.subscriptions.findUniqueOrThrow({\n    where: { id: subscriptionId },\n    include: { plan: true }\n  })\n  const newPlan = await db.plans.findUniqueOrThrow({ where: { id: newPlanId } })\n\n  \u002F\u002F Upgrade: charge prorated difference immediately\n  \u002F\u002F Downgrade: credit prorated difference to next invoice\n  const isUpgrade = newPlan.priceCents > sub.plan.priceCents\n\n  await provider.updateSubscription(sub.providerSubscriptionId, {\n    planId: newPlan.providerPlanId,\n    prorationBehavior: isUpgrade ? 'create_prorations' : 'always_invoice'\n  })\n}\n```\n\n## Webhook Event Routing\n\n```typescript\n\u002F\u002F Map provider events to internal handlers — single entry point\n\ntype WebhookHandler = (data: unknown, tx: Transaction) => Promise\u003Cvoid>\n\nconst webhookHandlers: Record\u003Cstring, WebhookHandler> = {\n  'subscription.created':       handleSubscriptionCreated,\n  'subscription.updated':       handleSubscriptionUpdated,\n  'subscription.canceled':      handleSubscriptionCanceled,\n  'invoice.paid':               handleInvoicePaid,\n  'invoice.payment_failed':     handlePaymentFailed,\n  'customer.updated':           handleCustomerUpdated,\n  'refund.created':             handleRefundCreated\n}\n\nasync function routeWebhookEvent(\n  event: { type: string; data: unknown },\n  tx: Transaction\n): Promise\u003Cvoid> {\n  const handler = webhookHandlers[event.type]\n\n  if (!handler) {\n    logger.warn(`Unhandled webhook event type: ${event.type}`)\n    return  \u002F\u002F Do not throw — acknowledge unknown events to prevent retries\n  }\n\n  await handler(event.data, tx)\n}\n```\n\n## Common Pitfalls\n\n```\nMissing idempotency on webhooks:\n  Providers retry failed deliveries. Without dedup, you charge or provision twice.\n  -> Store eventId before processing, skip duplicates.\n\nTrusting client-side plan selection:\n  Never let the frontend decide the price. Always resolve plan + price server-side.\n  -> Client sends planId, server looks up price from DB.\n\nForgetting to handle past_due:\n  Users with failed payments keep accessing paid features indefinitely.\n  -> Enforce access checks against subscription status, not just \"has subscription.\"\n\nHardcoding tax rates:\n  Tax rates change, new jurisdictions appear, VAT thresholds shift.\n  -> Use a tax API or let your payment provider handle calculation.\n\nNo grace period on cancellation:\n  Canceling immediately frustrates users who paid for a full period.\n  -> Cancel at period end by default, revoke access only after the paid period.\n```\n\n**Remember**: Your payment provider is a dependency, not your architecture. Abstract it behind an interface so you can switch providers, run in test mode, or support multiple providers for different regions without rewriting business logic.\n",{"name":5,"description":7},"main","70e1c350500ee750987420bbae48837afa906b7e","skills\u002Fsaas-payment-patterns","https:\u002F\u002Fgithub.com\u002Frubicanjr\u002FFinCognis","https:\u002F\u002Fgithub.com\u002Frubicanjr","linktr.ee\u002Ffinanskodu","Industrial Engineer & CIO @FinansKodu. Architecting AI-driven financial agents and autonomous workflows. 🏗️ Building systems, not just prompts.","2026-06-09 13:50:15",{"source":8,"skillName":5,"commands":50,"prompt":60,"zipAvailable":61},[51,54,57],{"tool":52,"command":53},"npx","npx skills add rubicanjr\u002FFinCognis --skill saas-payment-patterns",{"tool":55,"command":56},"bunx","bunx skills add rubicanjr\u002FFinCognis --skill saas-payment-patterns",{"tool":58,"command":59},"pnpm","pnpm dlx skills add rubicanjr\u002FFinCognis --skill saas-payment-patterns","安装技能，技能地址：https:\u002F\u002Fgithub.com\u002Frubicanjr\u002FFinCognis\u002Fblob\u002Fmain\u002Fskills\u002Fsaas-payment-patterns\u002FSKILL.md",true,[],[64,80,89,105,130,148],{"skillNo":65,"name":66,"nameZh":6,"description":67,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":68,"categories":69,"keywords":70,"publishedAt":36},"01M6NWS9DAXJTADT4T5MB49X8W","workflow-router","Goal-based workflow orchestration - routes tasks to specialist agents based on user goals","https:\u002F\u002Fgithub.com\u002Frubicanjr\u002FFinCognis\u002Fblob\u002Fmain\u002Fskills\u002Fworkflow-router\u002FSKILL.md",[],[71,72,73,74,75,76,77,78,79],"workflow router","workflow","router","orchestration","goals","goal","user","workflow orchestration","tasks",{"skillNo":81,"name":82,"nameZh":6,"description":83,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":84,"categories":85,"keywords":86,"publishedAt":36},"01M6NWS3RETSC0SHP16HP66E14","wiring","Wiring Verification","https:\u002F\u002Fgithub.com\u002Frubicanjr\u002FFinCognis\u002Fblob\u002Fmain\u002Fskills\u002Fwiring\u002FSKILL.md",[],[82,87,88],"verification","false",{"skillNo":90,"name":91,"nameZh":6,"description":92,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":93,"categories":94,"keywords":95,"publishedAt":36},"01M6NWS0XW9CVQZBDA1EGW0TWC","websocket-patterns","Connection management, room patterns, reconnection strategies, message buffering, and binary protocol design.","https:\u002F\u002Fgithub.com\u002Frubicanjr\u002FFinCognis\u002Fblob\u002Fmain\u002Fskills\u002Fwebsocket-patterns\u002Fskill.md",[],[96,19,97,98,99,100,101,102,103,104],"websocket","websocket patterns","design","protocol","management","message","strategies","binary","connection",{"skillNo":106,"name":107,"nameZh":6,"description":108,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":109,"categories":110,"keywords":111,"publishedAt":36},"01M6NWRDQDX9ZNETAWRRMQWV52","visual-verdict","Screenshot comparison QA for frontend development. Takes a screenshot of the current implementation, scores it across multiple visual dimensions, and returns a structured PASS\u002FREVISE\u002FFAIL verdict with concrete fixes. Use when implementing UI from a design reference or verifying visual correctness.","https:\u002F\u002Fgithub.com\u002Frubicanjr\u002FFinCognis\u002Fblob\u002Fmain\u002Fskills\u002Fvisual-verdict\u002FSKILL.md",[],[112,113,114,115,116,117,118,119,120,33,121,122,123,98,124,125,126,127,128,129],"visual","verdict","visual verdict","ui","across","revise","comparison","correctness","implementing","fixes","dimensions","frontend","development","qa","screenshot","returns","use","frontend development",{"skillNo":131,"name":132,"nameZh":6,"description":133,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":134,"categories":135,"keywords":136,"publishedAt":36},"01M6NWR8HSNRS7MNDK2J02QYMN","verification-loop","Comprehensive verification system covering build, types, lint, tests, security, and diff review before a PR.","https:\u002F\u002Fgithub.com\u002Frubicanjr\u002FFinCognis\u002Fblob\u002Fmain\u002Fskills\u002Fverification-loop\u002FSKILL.md",[],[137,138,87,139,140,28,141,142,143,144,145,146,147],"verification loop","loop","lint","review","pr","system","diff","build","tests","diff review","types",{"skillNo":149,"name":150,"nameZh":6,"description":151,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":152,"categories":153,"keywords":154,"publishedAt":36},"01M6NWR4HHSFR0VR5EXFRWA747","vector-db-patterns","Embedding strategies, ANN algorithms, hybrid search, RAG chunking strategies, and reranking for semantic search and retrieval.","https:\u002F\u002Fgithub.com\u002Frubicanjr\u002FFinCognis\u002Fblob\u002Fmain\u002Fskills\u002Fvector-db-patterns\u002Fskill.md",[],[155,156,157,158,19,159,160,161,162,102,163,164,165,166,167,33,168,169],"vector db patterns","vector db","db","vector","semantic search","search","embedding strategies","algorithms","chunking","semantic","retrieval","embedding","Hybrid Search","hybrid","rag"]