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
createdrow intoordersduring checkout session creation. Instead, every paid cycle (initial + renewals) creates aSUB-<invoice_id>order wheninvoice.paidarrives. 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_EXISTSand must use/api/payments/subscription/changeor the Customer Portal.
- Uses
- One-Time Purchases (
basic_annual,pro_annual,pack_starter..pack_enterprise):- Uses
mode: "payment". - Pre-creates a local
ordersrow with order numberSL<timestamp><6-hex>andstatus = 'created', settled idempotently bycheckout.session.completed(orcheckout.session.async_payment_succeeded).
- Uses
- 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 viascripts/stripe-catalog-sync.ts) and cached in isolate memory for5minutes (PRICE_CACHE_MS).
Introductory Offer (basic_monthly First Month $9.90)
- Configured via
config.subscriptions.introOffCents = { basic_monthly: 500 }($5.00off$14.90=$9.90). - Server-Side Eligibility (
repo.isIntroOfferEligible):- Account registered within the last
7days (config.subscriptions.introOfferDays = 7), and - User has never had a subscription before.
- Account registered within the last
- Coupon Naming (
introCouponId):slloy-intro-basic-monthly-500(duration: "once", automatically created bystripe-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 uponinvoice.paid. - Downgrade (
pro_monthly->basic_monthly): Scheduled for the end of the current billing period (effective: "next_period", recorded insubscriptions.scheduled_plan).
- Upgrade (
2. Webhook Events & Idempotency (/api/payments/webhook/stripe)
Webhook Endpoint & Signature Verification
- URL:
https://slloy.com/api/payments/webhook/stripe(andhttps://staging.slloy.com/api/payments/webhook/stripe, which has a dedicated Cloudflare AccessBypassrule). - Reads raw request text (
c.req.text()) and verifiesstripe-signatureusingst.webhooks.constructEventAsync(rawBody, sig, STRIPE_WEBHOOK_SECRET). - Idempotency (
webhook_eventstable):repo.beginWebhookEvent(event.id, event.type)atomically claims the Stripeevt_*ID. Duplicate deliveries return200 {"received": true}immediately.- If a handler throws an unexpected error, the event is not marked finished and returns
HTTP 500so Stripe retries. If it throwsBillingDataError(unrecoverable data mismatch requiring manual review), it logs a warning, marks the event finished, and returns200to stop infinite retries.
The 7 Required Stripe Webhook Events
| Event Name | Purpose & Handler Behavior | Consequence if Omitted |
|---|---|---|
checkout.session.completed | Syncs 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.paid | Sole 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_failed | Syncs subscription status (past_due / unpaid) via syncSubscription. | Delinquent accounts remain marked active. |
customer.subscription.updated | Syncs plan switches, cancel_at_period_end, and renewal timestamps. | Cancellations and plan changes do not appear in /account. |
customer.subscription.deleted | Terminates subscription entitlement and downgrades users.plan when no other active entitlement remains. | Cancelled users keep basic/pro tier indefinitely. |
charge.refunded | Revokes 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, andradar.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_idviaensureCustomer(). POST /api/payments/billing-portalcreates 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)callsrepo.hitRateLimit("checkout:<userId>", 3, 300)backed by PostgreSQL (rate_limitstable, shared across all Worker isolates).- Any user initiating more than
3checkout sessions or plan changes within5minutes receivesHTTP 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:
- Large Single Plan (
reason = "large_plan"): The plan is inconfig.payments.threeds.planIds(default:["pack_enterprise"]at$949.90). - High Daily Volume (
reason = "daily_volume"): The user's cumulative paid amount today (repo.paidAmountToday(userId)) plus the current order exceedsconfig.payments.threeds.dailyUsdCents(default:50000cents =$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):
- Funds-Withdrawn Gate (
DISPUTE_MONEY_GONE):- Credit revocation only executes when
dispute.statusis inSet(["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.
- Credit revocation only executes when
- Proportional Credit Revocation (
repo.applyRefundRevoke):- Calculates
target = min(credits, round(credits * disputeAmount / orderTotal)). - Deducts up to
targetfrom the user's remaining credit buckets and records any unrecoverable spent credits asdeficit(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'sbasic/proplan tier.
- Calculates
- Audit Trail (
payment_disputestable):- Every dispute is persisted via
repo.recordDisputewithevidence_due_by,funds_withdrawn,revoked_credits, and raw payload so operators can track evidence deadlines before automatic loss.
- Every dispute is persisted via
AI Models & Effects Catalog
Specifications, pricing, pixel constraints, and readiness gates for Slloy's 5 image models, 12 video models, and 15 photo/video effects.
Channel Procurement, Quotas & Cost Alerting
Active procurement rules, account balance thresholds, discount verification, and multi-layer alerting for Volcengine Ark, Alibaba DashScope, and Kuaishou Kling.