Pular para o conteúdo

Billing Worker

The billing worker handles Stripe subscription management for RedeCasas.

API Endpoints

MethodPathAuthDescription
POST/api/billing/checkout✅Create Stripe Checkout Session
POST/api/billing/portal✅Open Stripe Customer Portal
GET/api/billing/status✅Return subscription status
POST/api/billing/webhook—Stripe webhook handler

All billing endpoints (except webhook) require auth via session cookie.


POST /api/billing/checkout

Create a Stripe checkout session for subscription.

Response 200 OK

{
"url": "https://checkout.stripe.com/..."
}
  • Creates a Stripe customer if the user doesn’t have stripe_customer_id
  • Stores stripe_customer_id on the user record

POST /api/billing/portal

Open the Stripe customer portal.

Response 200 OK

{
"url": "https://billing.stripe.com/..."
}
  • Returns 404 if user has no stripe_customer_id

GET /api/billing/status

Check current subscription status.

Response 200 OK

{
"subscribed": true,
"status": "active",
"periodEnd": "2026-07-01T00:00:00.000Z"
}

POST /api/billing/webhook

Stripe webhook handler. No auth required (validated by Stripe signature).

Headers

  • Stripe-Signature — Stripe signature for verification

Handled Events

EventAction
checkout.session.completedSet subscription_status = 'active', store subscription_period_end
invoice.payment_succeededExtend subscription_period_end
invoice.payment_failedSet subscription_status = 'past_due'
customer.subscription.deletedSet subscription_status = 'inactive'

Response 200 OK

{
"received": true
}

Subscription Status Values

StatusMeaning
activeSubscription is current
inactiveNo active subscription
past_duePayment failed, grace period
cancelledUser cancelled

Environment Variables

Set via Wrangler secrets:

Terminal window
wrangler secret put STRIPE_SECRET_KEY
wrangler secret put STRIPE_WEBHOOK_SECRET
wrangler secret put STRIPE_PRICE_ID

For local development, add them to .dev.vars.

Flow

  1. User clicks “Subscribe” on the frontend
  2. Frontend calls POST /api/billing/checkout
  3. Worker creates a Stripe Checkout Session and returns the URL
  4. User completes payment on Stripe
  5. Stripe sends webhook to POST /api/billing/webhook
  6. Worker updates user’s subscription status in D1
  7. User can manage subscription via POST /api/billing/portal

Development

Terminal window
cd billing-worker
npm run dev

Deployment

Terminal window
cd billing-worker && npm run deploy