@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 191 lines 6.77 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 import { Database } from "./database.ts";
7
8 /**
9 * One merchant on the platform. `charges_enabled` is the flag that
10 * matters: until Stripe sets it, the merchant cannot take payments and
11 * the platform should keep sending them back to onboarding.
12 */
13 interface Merchant {
14 id: string;
15 email: string;
16 details_submitted: number;
17 charges_enabled: number;
18 payouts_enabled: number;
19 created_at: number;
20 updated_at: number;
21 }
22
23 /**
24 * A Stripe Connect platform Worker.
25 *
26 * A marketplace or SaaS-for-businesses onboards other companies as
27 * connected accounts, and those companies get paid through the platform.
28 * The lifecycle is:
29 *
30 * 1. `POST /merchants` — create an Express account for the merchant,
31 * store the id, and return a hosted onboarding URL.
32 * 2. The merchant fills in Stripe's onboarding form. Account Links expire
33 * and merchants abandon them, so `POST /merchants/:id/onboarding`
34 * mints a fresh link at any time.
35 * 3. Stripe sends `account.updated` when onboarding finishes.
36 * `consumeEvents` provisions the webhook endpoint; the handler records
37 * `charges_enabled` in D1.
38 * 4. `GET /merchants/:id` — the platform reads that row to decide whether
39 * the merchant is live.
40 */
41 export default class Api extends Cloudflare.Worker<Api>()(
42 "Api",
43 {
44 main: import.meta.url,
45 },
46 Effect.gen(function* () {
47 const db = yield* Cloudflare.D1.QueryDatabase(Database);
48 const createAccount = yield* Stripe.CreateAccount();
49 const createAccountLink = yield* Stripe.CreateAccountLink();
50
51 // Stripe → platform. Fires on every change to any connected account.
52 yield* Stripe.consumeEvents(
53 "Events",
54 { events: [Stripe.AccountUpdated] },
55 Effect.fn(function* (event) {
56 const account = event.object;
57 yield* db
58 .prepare(
59 `UPDATE merchants
60 SET details_submitted = ?, charges_enabled = ?, payouts_enabled = ?, updated_at = unixepoch()
61 WHERE id = ?`,
62 )
63 .bind(
64 account.details_submitted ? 1 : 0,
65 account.charges_enabled ? 1 : 0,
66 account.payouts_enabled ? 1 : 0,
67 account.id,
68 )
69 .run()
70 .pipe(Effect.orDie);
71 }),
72 );
73
74 // Stripe's hosted onboarding needs both URLs: `return_url` is where
75 // the merchant lands when done, `refresh_url` is where Stripe sends
76 // them if the link expired so the platform can mint a new one.
77 const onboardingLink = (merchantId: string, origin: string) =>
78 createAccountLink({
79 account: merchantId,
80 type: "account_onboarding",
81 return_url: `${origin}/merchants/${merchantId}/onboarded`,
82 refresh_url: `${origin}/merchants/${merchantId}/onboarding/refresh`,
83 });
84
85 return {
86 fetch: Effect.gen(function* () {
87 const request = yield* HttpServerRequest;
88 const url = new URL(request.originalUrl);
89 const segments = url.pathname.split("/").filter(Boolean);
90
91 if (request.method === "GET" && url.pathname === "/") {
92 return HttpServerResponse.text("ok");
93 }
94
95 // 1. Sign a merchant up.
96 if (request.method === "POST" && url.pathname === "/merchants") {
97 const body = (yield* request.json) as { email?: string };
98 if (!body.email) {
99 return yield* HttpServerResponse.json({ error: "email is required" }, { status: 400 });
100 }
101
102 const account = yield* createAccount({
103 type: "express",
104 country: "US",
105 email: body.email,
106 capabilities: {
107 card_payments: { requested: true },
108 transfers: { requested: true },
109 },
110 }).pipe(Effect.orDie);
111
112 yield* db
113 .prepare("INSERT INTO merchants (id, email) VALUES (?, ?)")
114 .bind(account.id, body.email)
115 .run()
116 .pipe(Effect.orDie);
117
118 const link = yield* onboardingLink(account.id, url.origin).pipe(Effect.orDie);
119
120 return yield* HttpServerResponse.json(
121 { merchantId: account.id, onboardingUrl: link.url },
122 { status: 201 },
123 );
124 }
125
126 // 2. Resume onboarding — links are single-use and expire.
127 if (
128 request.method === "POST" &&
129 segments.length === 3 &&
130 segments[0] === "merchants" &&
131 segments[2] === "onboarding"
132 ) {
133 const merchantId = segments[1];
134 const row = yield* db
135 .prepare("SELECT id FROM merchants WHERE id = ?")
136 .bind(merchantId)
137 .first<{ id: string }>()
138 .pipe(Effect.orDie);
139 if (row === null) {
140 return yield* HttpServerResponse.json({ error: "Unknown merchant" }, { status: 404 });
141 }
142 const link = yield* onboardingLink(merchantId, url.origin).pipe(Effect.orDie);
143 return yield* HttpServerResponse.json({ onboardingUrl: link.url });
144 }
145
146 // Where Stripe sends the merchant back.
147 if (
148 request.method === "GET" &&
149 segments.length === 3 &&
150 segments[0] === "merchants" &&
151 (segments[2] === "onboarded" || segments[2] === "refresh")
152 ) {
153 return HttpServerResponse.text(
154 segments[2] === "onboarded"
155 ? "Onboarding complete. You can close this tab."
156 : "That onboarding link expired. Request a new one from the platform.",
157 );
158 }
159
160 // 4. Is this merchant live?
161 if (request.method === "GET" && segments.length === 2 && segments[0] === "merchants") {
162 const merchant = yield* db
163 .prepare("SELECT * FROM merchants WHERE id = ?")
164 .bind(segments[1])
165 .first<Merchant>()
166 .pipe(Effect.orDie);
167 if (merchant === null) {
168 return yield* HttpServerResponse.json({ error: "Unknown merchant" }, { status: 404 });
169 }
170 return yield* HttpServerResponse.json({
171 id: merchant.id,
172 email: merchant.email,
173 onboarded: merchant.details_submitted === 1,
174 chargesEnabled: merchant.charges_enabled === 1,
175 payoutsEnabled: merchant.payouts_enabled === 1,
176 updatedAt: merchant.updated_at,
177 });
178 }
179
180 return yield* HttpServerResponse.json({ error: "Not found" }, { status: 404 });
181 }),
182 };
183 }).pipe(
184 Effect.provide([
185 Cloudflare.D1.QueryDatabaseBinding,
186 Stripe.CreateAccountHttp,
187 Stripe.CreateAccountLinkHttp,
188 Stripe.ConsumeEventsLive,
189 ]),
190 ),
191 ) {}