Skip to Content
Slloy Docs
Business, Pricing & Channels

Stripe Billing, Subscriptions & Risk Controls

Stripe Checkout lifecycle, 7 required webhook events, Basic $9.90 intro coupon, Customer Portal, checkout rate limits, 3DS rules, and automated dispute credit revocation.

Slloy processes payments through Stripe (server/src/http/routes/payments.ts and server/src/billing/*). In Cloudflare Workers, the Stripe client runs over the fetch HTTP client and verifies webhook signatures asynchronously via WebCrypto (constructEventAsync).

1. Checkout & Subscription Lifecycle

Dual Checkout Modes (POST /api/payments/checkout)

  • Monthly Subscriptions (basic_monthly, pro_monthly):
    • Uses mode: "subscription".
    • No Pre-Created Local Order: Subscription checkouts do not insert a created row into orders during checkout session creation. Instead, every paid cycle (initial + renewals) creates a SUB-<invoice_id> order when invoice.paid arrives. This prevents abandoned checkouts from polluting revenue reconciliation.
    • Session Expiration: Sets expires_at = now + 31 minutes (near Stripe's 30-minute minimum) to reduce concurrent duplicate subscription checkouts.
    • Single Active Subscription Rule: Users with an existing active subscription receive HTTP 409 SUBSCRIPTION_EXISTS and must use /api/payments/subscription/change or the Customer Portal.
  • One-Time Purchases (basic_annual, pro_annual, pack_starter..pack_enterprise):
    • Uses mode: "payment".
    • Pre-creates a local orders row with order number SL<timestamp><6-hex> and status = 'created', settled idempotently by checkout.session.completed (or checkout.session.async_payment_succeeded).
  • Managed Payments Disabled: Every Checkout Session sets managed_payments: { enabled: false } so Stripe does not reject products lacking tax codes.
  • Price Resolution: Pre-built Stripe Prices are looked up by lookup_key = slloy_<planId> (synced via scripts/stripe-catalog-sync.ts) and cached in isolate memory for 5 minutes (PRICE_CACHE_MS).

Introductory Offer (basic_monthly First Month $9.90)

  • Configured via config.subscriptions.introOffCents = { basic_monthly: 500 } ($5.00 off $14.90 = $9.90).
  • Server-Side Eligibility (repo.isIntroOfferEligible):
    • Account registered within the last 7 days (config.subscriptions.introOfferDays = 7), and
    • User has never had a subscription before.
  • Coupon Naming (introCouponId): slloy-intro-basic-monthly-500 (duration: "once", automatically created by stripe-catalog-sync).

Plan Changes (POST /api/payments/subscription/change)

  • Handled by server/src/billing/changePlan.ts:
    • Upgrade (basic_monthly -> pro_monthly): Takes effect immediately (effective: "immediate"), charging prorated difference and granting new cycle credits upon invoice.paid.
    • Downgrade (pro_monthly -> basic_monthly): Scheduled for the end of the current billing period (effective: "next_period", recorded in subscriptions.scheduled_plan).

2. Webhook Events & Idempotency (/api/payments/webhook/stripe)

Webhook Endpoint & Signature Verification

  • URL: https://slloy.com/api/payments/webhook/stripe (and https://staging.slloy.com/api/payments/webhook/stripe, which has a dedicated Cloudflare Access Bypass rule).
  • Reads raw request text (c.req.text()) and verifies stripe-signature using st.webhooks.constructEventAsync(rawBody, sig, STRIPE_WEBHOOK_SECRET).
  • Idempotency (webhook_events table):
    • repo.beginWebhookEvent(event.id, event.type) atomically claims the Stripe evt_* ID. Duplicate deliveries return 200 {"received": true} immediately.
    • If a handler throws an unexpected error, the event is not marked finished and returns HTTP 500 so Stripe retries. If it throws BillingDataError (unrecoverable data mismatch requiring manual review), it logs a warning, marks the event finished, and returns 200 to stop infinite retries.

The 7 Required Stripe Webhook Events

Event NamePurpose & Handler BehaviorConsequence if Omitted
checkout.session.completedSyncs subscription relationship for mode=subscription; settles order and grants credits for mode=payment (when payment_status === "paid"). Checks amount_total === order.amount_cents.One-time buyers never receive credits; new subscriptions are not linked.
invoice.paidSole credit-granting entry point for subscriptions (grantForInvoice). Creates order SUB-<invoice_id> and grants 60-day credits. Also checks charge.amount_refunded > 0 in case a refund arrived out-of-order before invoice.paid.Subscription users never receive monthly or renewal credits.
invoice.payment_failedSyncs subscription status (past_due / unpaid) via syncSubscription.Delinquent accounts remain marked active.
customer.subscription.updatedSyncs plan switches, cancel_at_period_end, and renewal timestamps.Cancellations and plan changes do not appear in /account.
customer.subscription.deletedTerminates subscription entitlement and downgrades users.plan when no other active entitlement remains.Cancelled users keep basic/pro tier indefinitely.
charge.refundedRevokes credits proportionally (applyRefund) and cancels entitlement on full refund.Refunded users keep and spend refunded credits for free.
charge.dispute.created (plus .updated, .closed)Records dispute in payment_disputes, revokes credits immediately when funds are withdrawn, and cancels subscription on full chargeback.Stolen/disputed cards drain channel balance while platform pays $15 dispute fee.

[!TIP] The webhook handler also accepts checkout.session.async_payment_succeeded, checkout.session.async_payment_failed, invoice.payment_action_required, customer.subscription.created, and radar.early_fraud_warning.created (logged for manual review).


3. Customer Portal (POST /api/payments/billing-portal)

Self-service cancellation and payment method management are mandatory to prevent chargebacks ($15 fee per dispute + Stripe risk score degradation).

  • Each user is bound to a single users.stripe_customer_id via ensureCustomer().
  • POST /api/payments/billing-portal creates a Stripe Billing Portal session returning to ${config.publicUrl}/${localePrefix}account.
  • Required Stripe Dashboard Portal settings:
    • Enable Invoice history
    • Enable Update payment methods
    • Enable Cancel subscriptions (mode: Cancel at end of billing period, with cancellation reason survey enabled)

4. Risk Controls: Checkout Rate Limit & Tiered 3DS

Per-Account Checkout Rate Limit (3 per 5 Minutes)

Following a 2026-10-03 card-testing attack where an attacker created a checkout session 46 seconds after registration and tested 10 stolen cards in 10 seconds:

  • allowCheckout(userId) calls repo.hitRateLimit("checkout:<userId>", 3, 300) backed by PostgreSQL (rate_limits table, shared across all Worker isolates).
  • Any user initiating more than 3 checkout sessions or plan changes within 5 minutes receives HTTP 429 TOO_MANY.
  • Rate limiting is keyed by userId (not IP) so corporate/household NAT users are not cross-penalized, and runs after input/subscription validation so malformed requests do not consume quota.

Tiered 3D Secure Enforcement (evalThreeds)

Because Slloy's primary customer base is in the US (where bank 3DS enrollment rates are lower and global 3DS hurts normal conversion), 3DS (request_three_d_secure) is enforced selectively when config.payments.threeds.enabled is true:

  1. Large Single Plan (reason = "large_plan"): The plan is in config.payments.threeds.planIds (default: ["pack_enterprise"] at $949.90).
  2. High Daily Volume (reason = "daily_volume"): The user's cumulative paid amount today (repo.paidAmountToday(userId)) plus the current order exceeds config.payments.threeds.dailyUsdCents (default: 50000 cents = $500.00).

When triggered, Checkout sets payment_method_options.card.request_three_d_secure = "any" (or "challenge" when THREEDS_FORCE=1) and displays a localized 3DS notice on the submit button.


5. Dispute & Chargeback Handling (handleDispute)

When charge.dispute.created, charge.dispute.updated, or charge.dispute.closed fires (or during daily reconciliation via scripts/reconcile-disputes.ts):

  1. Funds-Withdrawn Gate (DISPUTE_MONEY_GONE):
    • Credit revocation only executes when dispute.status is in Set(["needs_response", "under_review", "lost"]).
    • Early fraud warnings (warning_*) do not withdraw funds and do not revoke credits to avoid false-positive disruption.
    • Winning a dispute (won) never automatically re-grants credits—winning only proves platform compliance, not that the buyer was benign. Any re-grant requires manual review.
  2. Proportional Credit Revocation (repo.applyRefundRevoke):
    • Calculates target = min(credits, round(credits * disputeAmount / orderTotal)).
    • Deducts up to target from the user's remaining credit buckets and records any unrecoverable spent credits as deficit (logged with a ⚠️ warning for manual account ban review).
    • If disputeAmount >= orderTotal (full chargeback), endEntitlementForOrder() immediately cancels the associated Stripe subscription and revokes the user's basic/pro plan tier.
  3. Audit Trail (payment_disputes table):
    • Every dispute is persisted via repo.recordDispute with evidence_due_by, funds_withdrawn, revoked_credits, and raw payload so operators can track evidence deadlines before automatic loss.

On this page