@devries-cameron20 / t3code Mirror · read-only
Fork 0

The best way to control Claude Code, Codex and more from any computer or phone

Mirrored from https://github.com/Camo67/t3code.git

Synced Nov 21, 06:00 UTC

main
ts 244 lines 9.17 KB
Raw
1 import * as Cloudflare from "@alchemy.run/cloudflare";
2 import * as Stripe from "@alchemy.run/stripe";
3 import * as Effect from "effect/Effect";
4 import { HttpServerRequest } from "effect/http/HttpServerRequest";
5 import * as HttpServerResponse from "effect/http/HttpServerResponse";
6
7 /**
8 * What the app knows about a customer's subscription. Written by the
9 * webhook handler, read by `GET /subscription/:customerId`. This is the
10 * record your app checks to decide whether to serve paid features —
11 * never call Stripe on the request path for that.
12 */
13 interface Entitlement {
14 customerId: string;
15 status: "active" | "past_due" | "canceled";
16 priceId: string | null;
17 subscriptionId: string | null;
18 updatedAt: number;
19 }
20
21 /**
22 * A SaaS billing Worker.
23 *
24 * The catalog (`Product`, `Price`, `Coupon`) is declared on the Worker
25 * and deployed with it. At runtime the Worker:
26 *
27 * - `POST /checkout` — creates a Stripe Customer and a Checkout Session
28 * for the Pro plan, and returns the hosted payment URL.
29 * - `POST /portal` — opens the Billing Portal so the customer can change
30 * card, switch plan, or cancel without your app building those screens.
31 * - `GET /subscription/:customerId` — returns the entitlement your app
32 * should gate features on.
33 *
34 * Stripe reports what happened via webhooks; `consumeEvents` provisions
35 * the endpoint and the handler keeps the entitlement in KV up to date.
36 */
37 export default class Api extends Cloudflare.Worker<Api>()(
38 "Api",
39 {
40 main: import.meta.url,
41 },
42 Effect.gen(function* () {
43 // Catalog — lives with the Worker that sells it.
44 const product = yield* Stripe.Product("Pro", {
45 name: "Pro",
46 description: "Billed monthly",
47 });
48 const price = yield* Stripe.Price("ProMonthly", {
49 product,
50 currency: "usd",
51 unitAmount: 2000,
52 recurring: { interval: "month" },
53 });
54 yield* Stripe.Coupon("Launch20", {
55 percentOff: 20,
56 duration: "once",
57 name: "Launch 20%",
58 });
59
60 // What customers can do for themselves in the hosted portal.
61 const portalConfig = yield* Stripe.BillingPortalConfiguration("Portal", {
62 name: "Pro customer portal",
63 features: {
64 invoiceHistory: { enabled: true },
65 paymentMethodUpdate: { enabled: true },
66 customerUpdate: { enabled: true, allowedUpdates: ["email"] },
67 subscriptionCancel: { enabled: true, mode: "at_period_end" },
68 },
69 });
70
71 // `price.id` / `portalConfig.id` are plan-time Outputs. Yielding them
72 // here returns accessors the request handlers can yield at runtime.
73 const priceId = yield* price.id;
74 const portalConfigId = yield* portalConfig.id;
75
76 // Runtime bindings — each one injects the account key onto the Worker
77 // and calls Stripe over HTTP from a request handler.
78 const createCustomer = yield* Stripe.CreateCustomer();
79 const createCheckout = yield* Stripe.CreateCheckoutSession();
80 const createPortal = yield* Stripe.CreateBillingPortalSession();
81
82 // Entitlement store.
83 const entitlements = yield* Cloudflare.KV.Namespace("Entitlements");
84 const kv = yield* Cloudflare.KV.ReadWriteNamespace(entitlements);
85
86 // Stripe → app. Every subscription state change lands here.
87 yield* Stripe.consumeEvents(
88 "Events",
89 {
90 events: [
91 Stripe.CheckoutSessionCompleted,
92 Stripe.CustomerSubscriptionCreated,
93 Stripe.CustomerSubscriptionUpdated,
94 Stripe.CustomerSubscriptionDeleted,
95 Stripe.InvoicePaymentFailed,
96 ],
97 },
98 Effect.fn(function* (event) {
99 const write = (entitlement: Entitlement) =>
100 kv.put(entitlement.customerId, JSON.stringify(entitlement)).pipe(Effect.orDie);
101
102 switch (event.type) {
103 case "checkout.session.completed": {
104 // The buyer paid. Grant access now; the subscription events
105 // that follow keep it accurate.
106 const session = event.object;
107 const customerId = idOf(session.customer);
108 if (customerId === null) return;
109 yield* write({
110 customerId,
111 status: "active",
112 priceId: yield* priceId,
113 subscriptionId: idOf(session.subscription),
114 updatedAt: Date.now(),
115 });
116 return;
117 }
118 case "customer.subscription.created":
119 case "customer.subscription.updated": {
120 const subscription = event.object;
121 yield* write({
122 customerId: idOf(subscription.customer)!,
123 status:
124 subscription.status === "active" || subscription.status === "trialing"
125 ? "active"
126 : subscription.status === "past_due"
127 ? "past_due"
128 : "canceled",
129 priceId: subscription.items.data[0]?.price.id ?? null,
130 subscriptionId: subscription.id,
131 updatedAt: Date.now(),
132 });
133 return;
134 }
135 case "customer.subscription.deleted": {
136 const subscription = event.object;
137 yield* write({
138 customerId: idOf(subscription.customer)!,
139 status: "canceled",
140 priceId: null,
141 subscriptionId: subscription.id,
142 updatedAt: Date.now(),
143 });
144 return;
145 }
146 case "invoice.payment_failed": {
147 // Card declined on renewal. Stripe will retry; mark the account
148 // so the UI can nudge the customer to the portal.
149 const invoice = event.object;
150 const customerId = idOf(invoice.customer);
151 if (customerId === null) return;
152 const current = yield* kv.get<Entitlement>(customerId, "json").pipe(Effect.orDie);
153 yield* write({
154 customerId,
155 status: "past_due",
156 priceId: current?.priceId ?? null,
157 subscriptionId: current?.subscriptionId ?? null,
158 updatedAt: Date.now(),
159 });
160 return;
161 }
162 }
163 }),
164 );
165
166 return {
167 fetch: Effect.gen(function* () {
168 const request = yield* HttpServerRequest;
169 const url = new URL(request.originalUrl);
170
171 // Start a subscription. Creates the Customer up front so the
172 // webhook events carry a stable id you can key on.
173 if (request.method === "POST" && url.pathname === "/checkout") {
174 const body = (yield* request.json) as { email?: string };
175 if (!body.email) {
176 return yield* HttpServerResponse.json({ error: "email is required" }, { status: 400 });
177 }
178
179 const customer = yield* createCustomer({ email: body.email }).pipe(Effect.orDie);
180 const session = yield* createCheckout({
181 mode: "subscription",
182 customer: customer.id,
183 line_items: [{ price: yield* priceId, quantity: 1 }],
184 allow_promotion_codes: true,
185 success_url: `${url.origin}/welcome?session_id={CHECKOUT_SESSION_ID}`,
186 cancel_url: `${url.origin}/pricing`,
187 }).pipe(Effect.orDie);
188
189 return yield* HttpServerResponse.json(
190 { customerId: customer.id, checkoutUrl: session.url },
191 { status: 201 },
192 );
193 }
194
195 // Self-serve management: update card, switch plan, cancel.
196 if (request.method === "POST" && url.pathname === "/portal") {
197 const body = (yield* request.json) as { customerId?: string };
198 if (!body.customerId) {
199 return yield* HttpServerResponse.json(
200 { error: "customerId is required" },
201 { status: 400 },
202 );
203 }
204 const session = yield* createPortal({
205 customer: body.customerId,
206 configuration: yield* portalConfigId,
207 return_url: `${url.origin}/account`,
208 }).pipe(Effect.orDie);
209 return yield* HttpServerResponse.json({ portalUrl: session.url });
210 }
211
212 // What the rest of the app gates on.
213 if (request.method === "GET" && url.pathname.startsWith("/subscription/")) {
214 const customerId = url.pathname.slice("/subscription/".length);
215 const entitlement = yield* kv.get<Entitlement>(customerId, "json").pipe(Effect.orDie);
216 return yield* HttpServerResponse.json(entitlement ?? { customerId, status: "none" });
217 }
218
219 if (url.pathname === "/welcome" || url.pathname === "/pricing") {
220 return HttpServerResponse.text(
221 url.pathname === "/welcome" ? "Thanks — your subscription is active." : "Pricing page.",
222 );
223 }
224
225 return yield* HttpServerResponse.json({ error: "Not found" }, { status: 404 });
226 }),
227 };
228 }).pipe(
229 Effect.provide([
230 Cloudflare.KV.ReadWriteNamespaceBinding,
231 Stripe.CreateCustomerHttp,
232 Stripe.CreateCheckoutSessionHttp,
233 Stripe.CreateBillingPortalSessionHttp,
234 Stripe.ConsumeEventsLive,
235 ]),
236 ),
237 ) {}
238
239 /**
240 * Stripe returns related objects either as an id string or, when expanded,
241 * as the full object. Normalise to the id.
242 */
243 const idOf = (ref: string | { id: string } | { id?: string } | null | undefined): string | null =>
244 ref == null ? null : typeof ref === "string" ? ref : (ref.id ?? null);