@somewhere-cloud/cli 0.38.155 → 0.38.157

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (142) hide show
  1. package/CHANGELOG.md +8 -1
  2. package/dist/commands/docs.js +1 -1
  3. package/dist/lib/bundle.js +286 -188
  4. package/dist/lib/bundle.js.map +3 -3
  5. package/npm-shrinkwrap.json +2 -2
  6. package/package.json +2 -3
  7. package/dist/docs/adopt.md +0 -39
  8. package/dist/docs/analytics.md +0 -161
  9. package/dist/docs/api-reference.md +0 -339
  10. package/dist/docs/api-surface.md +0 -2067
  11. package/dist/docs/app-mcp.md +0 -162
  12. package/dist/docs/architecture-patterns.md +0 -334
  13. package/dist/docs/auth-client.md +0 -531
  14. package/dist/docs/billing.md +0 -76
  15. package/dist/docs/browser.md +0 -639
  16. package/dist/docs/calendar.md +0 -298
  17. package/dist/docs/changes.md +0 -323
  18. package/dist/docs/cli.md +0 -407
  19. package/dist/docs/common-mistakes.md +0 -199
  20. package/dist/docs/connect-agent.md +0 -72
  21. package/dist/docs/cors.md +0 -114
  22. package/dist/docs/cron.md +0 -167
  23. package/dist/docs/database-engine.md +0 -167
  24. package/dist/docs/declared-data.md +0 -1656
  25. package/dist/docs/declared-files.md +0 -475
  26. package/dist/docs/deploy-intelligence.md +0 -188
  27. package/dist/docs/deploy.md +0 -733
  28. package/dist/docs/design-system.md +0 -273
  29. package/dist/docs/dev-environments.md +0 -496
  30. package/dist/docs/domain-ownership.md +0 -31
  31. package/dist/docs/domains.md +0 -370
  32. package/dist/docs/feedback.md +0 -88
  33. package/dist/docs/file-tools.md +0 -116
  34. package/dist/docs/functions.md +0 -489
  35. package/dist/docs/getting-started.md +0 -238
  36. package/dist/docs/github.md +0 -95
  37. package/dist/docs/google-calendar.md +0 -212
  38. package/dist/docs/groups.md +0 -836
  39. package/dist/docs/guarantees.md +0 -58
  40. package/dist/docs/handled-for-you.md +0 -224
  41. package/dist/docs/inspect.md +0 -171
  42. package/dist/docs/limits.md +0 -68
  43. package/dist/docs/live-data.md +0 -197
  44. package/dist/docs/live.md +0 -92
  45. package/dist/docs/local-dev.md +0 -30
  46. package/dist/docs/migration-supabase.md +0 -58
  47. package/dist/docs/payments.md +0 -1102
  48. package/dist/docs/portability.md +0 -194
  49. package/dist/docs/postgres.md +0 -301
  50. package/dist/docs/pricing-comparison.md +0 -42
  51. package/dist/docs/pricing.md +0 -39
  52. package/dist/docs/project-groups.md +0 -107
  53. package/dist/docs/projects.md +0 -380
  54. package/dist/docs/recipe-ai-agent.md +0 -112
  55. package/dist/docs/recipe-ai-features.md +0 -227
  56. package/dist/docs/recipe-ai-receipts.md +0 -783
  57. package/dist/docs/recipe-background-jobs.md +0 -369
  58. package/dist/docs/recipe-booking.md +0 -348
  59. package/dist/docs/recipe-csv-import.md +0 -390
  60. package/dist/docs/recipe-ecommerce.md +0 -127
  61. package/dist/docs/recipe-email.md +0 -282
  62. package/dist/docs/recipe-escalation.md +0 -133
  63. package/dist/docs/recipe-file-uploads.md +0 -159
  64. package/dist/docs/recipe-import-app.md +0 -110
  65. package/dist/docs/recipe-login.md +0 -457
  66. package/dist/docs/recipe-multi-chat.md +0 -198
  67. package/dist/docs/recipe-paid-api.md +0 -161
  68. package/dist/docs/recipe-pdfs.md +0 -205
  69. package/dist/docs/recipe-push-notifications.md +0 -107
  70. package/dist/docs/recipe-seo.md +0 -200
  71. package/dist/docs/recipe-signed-in-app.md +0 -330
  72. package/dist/docs/render.md +0 -99
  73. package/dist/docs/rooms.md +0 -554
  74. package/dist/docs/sdk.md +0 -287
  75. package/dist/docs/sdks.md +0 -24
  76. package/dist/docs/search.md +0 -199
  77. package/dist/docs/security-model.md +0 -168
  78. package/dist/docs/setup.md +0 -212
  79. package/dist/docs/smoke.md +0 -102
  80. package/dist/docs/speed.md +0 -298
  81. package/dist/docs/sql-compatibility.md +0 -96
  82. package/dist/docs/sw.agent.md +0 -248
  83. package/dist/docs/sw.ai.md +0 -1291
  84. package/dist/docs/sw.auth.md +0 -1811
  85. package/dist/docs/sw.billing.md +0 -171
  86. package/dist/docs/sw.db.md +0 -2128
  87. package/dist/docs/sw.email.md +0 -661
  88. package/dist/docs/sw.endpoint.md +0 -187
  89. package/dist/docs/sw.env.md +0 -303
  90. package/dist/docs/sw.fetch.md +0 -115
  91. package/dist/docs/sw.fs.md +0 -424
  92. package/dist/docs/sw.groups.md +0 -836
  93. package/dist/docs/sw.image.md +0 -69
  94. package/dist/docs/sw.jobs.md +0 -520
  95. package/dist/docs/sw.logs.md +0 -61
  96. package/dist/docs/sw.mail.md +0 -106
  97. package/dist/docs/sw.notifications.md +0 -78
  98. package/dist/docs/sw.push.md +0 -161
  99. package/dist/docs/sw.rateLimit.md +0 -67
  100. package/dist/docs/sw.web.md +0 -128
  101. package/dist/docs/tasks.md +0 -269
  102. package/dist/docs/test.md +0 -220
  103. package/dist/docs/tool-reference-account.md +0 -7
  104. package/dist/docs/tool-reference-ai.md +0 -121
  105. package/dist/docs/tool-reference-analytics.md +0 -37
  106. package/dist/docs/tool-reference-api.md +0 -19
  107. package/dist/docs/tool-reference-artifacts.md +0 -35
  108. package/dist/docs/tool-reference-auth.md +0 -163
  109. package/dist/docs/tool-reference-browser.md +0 -114
  110. package/dist/docs/tool-reference-code.md +0 -26
  111. package/dist/docs/tool-reference-connect.md +0 -21
  112. package/dist/docs/tool-reference-cron.md +0 -48
  113. package/dist/docs/tool-reference-db.md +0 -282
  114. package/dist/docs/tool-reference-domains.md +0 -107
  115. package/dist/docs/tool-reference-email.md +0 -55
  116. package/dist/docs/tool-reference-env.md +0 -19
  117. package/dist/docs/tool-reference-feedback.md +0 -56
  118. package/dist/docs/tool-reference-fs.md +0 -265
  119. package/dist/docs/tool-reference-github.md +0 -57
  120. package/dist/docs/tool-reference-groups.md +0 -85
  121. package/dist/docs/tool-reference-help.md +0 -29
  122. package/dist/docs/tool-reference-jobs.md +0 -39
  123. package/dist/docs/tool-reference-live.md +0 -48
  124. package/dist/docs/tool-reference-logs.md +0 -16
  125. package/dist/docs/tool-reference-payments.md +0 -44
  126. package/dist/docs/tool-reference-project.md +0 -706
  127. package/dist/docs/tool-reference-push.md +0 -78
  128. package/dist/docs/tool-reference-rate-limit.md +0 -18
  129. package/dist/docs/tool-reference-search.md +0 -68
  130. package/dist/docs/tool-reference-security.md +0 -42
  131. package/dist/docs/tool-reference-smoke.md +0 -17
  132. package/dist/docs/tool-reference-stock-photos.md +0 -20
  133. package/dist/docs/tool-reference-tasks.md +0 -73
  134. package/dist/docs/tool-reference-telegram.md +0 -32
  135. package/dist/docs/tool-reference-usage.md +0 -9
  136. package/dist/docs/tool-reference-web.md +0 -71
  137. package/dist/docs/tool-reference-webhooks.md +0 -9
  138. package/dist/docs/troubleshooting.md +0 -411
  139. package/dist/docs/typed-functions.md +0 -94
  140. package/dist/docs/verify-before-deploy.md +0 -67
  141. package/dist/docs/vs-supabase.md +0 -75
  142. package/dist/docs/vs-vercel.md +0 -103
@@ -1,1102 +0,0 @@
1
- # Payments
2
-
3
- `sw.payments` starts a hosted Stripe Checkout from a function. Use a project
4
- in your Somewhere account to run test checkouts before business onboarding.
5
- If you deployed a temporary app, claim it first. With
6
- `checkoutForUser`, the platform binds checkout to the signed-in user, price
7
- and payment account. A confirmed live payment grants the selected plan without
8
- an app webhook handler. Test purchases are recorded separately and never unlock
9
- live access; auth and billing readers currently show live access only.
10
-
11
- Redeploy an older app normally before using plan checkout so its functions
12
- carry the verified user proof. The platform refuses an unbound user checkout.
13
-
14
- ## Sell an upgrade in test mode
15
-
16
- ```ts
17
- // db/schema.ts
18
- import { id, owner, schema, table, text, timestamp } from 'somewhere/db';
19
-
20
- export default schema({
21
- notes: table(
22
- {
23
- id: id(),
24
- title: text(),
25
- body: text({ default: '' }),
26
- created_at: timestamp({ default: 'now' }),
27
- },
28
- {
29
- scope: owner(),
30
- client: {
31
- read: ['id', 'title', 'body', 'created_at'],
32
- create: ['title', 'body'],
33
- update: ['title', 'body'],
34
- delete: true,
35
- },
36
- },
37
- ),
38
- });
39
- ```
40
-
41
- ```ts
42
- // api/upgrade.ts — starts a test checkout for the signed-in user
43
- export default async function upgrade(
44
- request: Request,
45
- sw: SomewhereRuntimeContext,
46
- ): Promise<Response> {
47
- if (request.method !== 'POST') {
48
- return new Response('Use POST.', { status: 405, headers: { Allow: 'POST' } });
49
- }
50
-
51
- const user = await sw.auth.fromRequest(request);
52
- if (!user) return Response.json({ error: 'Sign in to upgrade.' }, { status: 401 });
53
-
54
- const allowance = await sw.rateLimit.check(`upgrade:${user.id}`, 5, 3600);
55
- if (!allowance.allowed) {
56
- return Response.json({ error: 'Too many checkout attempts. Try again later.' }, { status: 429 });
57
- }
58
-
59
- const origin = new URL(request.url).origin;
60
- const checkout = await sw.payments.checkoutForUser({
61
- env: 'dev', // test mode: no real charge. Changing this is a deliberate step after onboarding.
62
- plan: 'pro',
63
- mode: 'payment',
64
- line_items: [{ amount: 900, currency: 'usd', name: 'Pro' }],
65
- success_url: `${origin}/upgraded`,
66
- cancel_url: `${origin}/pricing`,
67
- customer_email: user.email,
68
- });
69
- if (!checkout.url) return Response.json({ error: 'Checkout is unavailable.' }, { status: 502 });
70
- return Response.json({ url: checkout.url });
71
- }
72
- ```
73
-
74
- ```ts
75
- // api/export.ts — a Pro feature, gated on the user's current plan
76
- export default async function exportNotes(
77
- request: Request,
78
- sw: SomewhereRuntimeContext,
79
- ): Promise<Response> {
80
- const user = await sw.auth.fromRequest(request);
81
- if (!user) return Response.json({ error: 'Sign in.' }, { status: 401 });
82
-
83
- // Current effective plan (includes the payment-retry grace period), read on every call.
84
- const { plan } = await sw.billing.entitlements();
85
- const isPro = plan === 'pro';
86
- if (!isPro) return Response.json({ error: 'Export is part of Pro.' }, { status: 403 });
87
-
88
- const { data } = await sw.db.from('notes', { columns: ['title', 'body', 'created_at'], limit: 500 });
89
- return Response.json(data);
90
- }
91
- ```
92
-
93
- The page posts to `/api/upgrade` and sends the browser to the returned `url`.
94
- `env: 'dev'` runs in Stripe test mode, before and after onboarding, so pay
95
- with the test card `4242 4242 4242 4242` and any future date and CVC.
96
- Before you onboard, test checkouts run on the platform's shared test account.
97
- Use the shared test account to check the checkout screen and test charge.
98
- That test purchase leaves `GET /api/export` locked: the gate reads live access.
99
- After a confirmed live Pro purchase, the same account can export only its own
100
- notes. An account without live Pro access gets 403.
101
-
102
- - **The user and plan never come from the browser.** `checkoutForUser` stores
103
- a checkout intent on the server, and only its id travels through Stripe.
104
- The payment webhook reads the user and plan from that record.
105
- - **Gate the upgrade on the recorded payment event and user plan, then use
106
- the success page to show the result.** The platform verifies the stored
107
- checkout and current subscription before granting live access. Payment
108
- retries (`past_due`) keep access. Unpaid, paused, canceled and expired
109
- subscriptions return `plan: 'free'`. A replaced or unmatched payment is
110
- recorded for reconciliation instead of changing access.
111
- - **Check before creating another checkout.** After an interrupted request,
112
- or when the customer comes back from checkout, read the recorded state
113
- first: the explicit `sw.billing.entitlements()` observation and the payment in
114
- `sw.payments.events`. Wait for that checkout's final payment state. If it
115
- is still pending or unavailable, keep checking before starting another
116
- checkout.
117
- - **Prices are your code.** `amount: 900` is this example's price in cents.
118
- To test a recurring plan, define its `price_cents` and `interval: 'month'`
119
- or `'year'` with `sw.billing.definePlans` from a protected setup path.
120
- Then use `checkoutForUser` with `env: 'dev'`, the catalog `plan`, and
121
- `mode: 'subscription'`; omit `line_items`. For a plan without `stripe_price_id`, the platform
122
- creates the test recurring price, including on the shared test account. See
123
- `docs({ topic: 'sw.billing' })` for the catalog example. Live catalog
124
- subscriptions require a `stripe_price_id` on your connected account.
125
-
126
- ## Take real payments
127
-
128
- Live charges are a deliberate step taken by the project owner:
129
-
130
- 1. The owner runs `payments_onboard` and completes Stripe's identity and bank
131
- details on the hosted page. One onboarding covers every project the owner
132
- has, now and later.
133
- 2. `payments_status` reports `charges_enabled: true` once onboarding is
134
- complete.
135
- 3. You change `env: 'dev'` to `env: 'prod'` in your code and deploy.
136
-
137
- Money settles to the owner's connected account, minus the processing and
138
- platform fees in `payments` and `pricing`. A collaborator's live checkout
139
- before the owner has onboarded is refused with `OWNER_NOT_ONBOARDED`. Refunds
140
- (`sw.payments.refund`) and subscription cancellations move real money or end
141
- access. Run them only from an action the owner or an authorized operator
142
- takes.
143
-
144
- Your app still owns the pricing page, the cart, receipts and any order
145
- fulfillment beyond the plan. After a payment, send the receipt with
146
- `sw.email`, and dispatch slower work with `sw.jobs`.
147
-
148
- For optional onboarding on your own test account, use `payments_onboard`
149
- with `mode: 'test'`. See `payments` → `onboarding-for-live-charges`
150
- for the ready-account response and dashboard controls.
151
-
152
- ## More on payments
153
-
154
- | Need | Where |
155
- |---|---|
156
- | Test checkouts and the stand-in account | `payments` → `you-do-not-need-to-onboard-to-start-building` |
157
- | How plan tracking works | `payments` → `automatic-plan-tracking-on-appusers` |
158
- | Live onboarding, collaborators | `payments` → `onboarding-for-live-charges`, `collaborators` |
159
- | Computed baskets, deposits, holds | `payments` → `quote-backed-checkout`, `manual-capture-deposits` |
160
- | Webhook events your project receives | `payments` → `webhook-events-what-each-flow-actually-emits` |
161
- | Refunds, cancellations, customer billing portal | `payments` → `refunds-cancels-transactions-portal-events` |
162
- | Plans and feature gates in code | `sw.billing` |
163
- | Complete store and booking apps | `recipe-ecommerce`, `recipe-booking` |
164
- | Live checkout that pays for one row and marks it paid | `payments` → `charge-for-one-row-live-only` |
165
-
166
- ## Charge for one row (live only)
167
-
168
- A checkout can pay for one row and mark it paid. The platform checks the
169
- amount against the row and changes its status only after a verified payment.
170
- Declare the binding in the schema options, beside the table:
171
-
172
- ```ts
173
- schema(
174
- {
175
- orders: table(
176
- { id: id(), item: text(), amount_cents: integer(), currency: text(), status: text({ default: 'unpaid' }) },
177
- { scope: owner(), client: { read: true } },
178
- ),
179
- },
180
- {
181
- payments: {
182
- order: { table: 'orders', amount: 'amount_cents', currency: 'currency', onPaid: { status: { from: ['unpaid'], to: 'paid' } } },
183
- },
184
- },
185
- );
186
- ```
187
-
188
- Your functions create orders with the amount; the browser only reads them.
189
- Start the checkout from the signed-in user's request:
190
-
191
- ```ts
192
- // api/orders/pay.ts — POST { id }: live checkout for one of the caller's orders
193
- export default async function payOrder(
194
- request: Request,
195
- sw: SomewhereRuntimeContext,
196
- ): Promise<Response> {
197
- if (request.method !== 'POST') {
198
- return new Response('Use POST.', { status: 405, headers: { Allow: 'POST' } });
199
- }
200
- if (!(await sw.auth.fromRequest(request))) {
201
- return Response.json({ error: 'Sign in first.' }, { status: 401 });
202
- }
203
- const body = (await request.json().catch(() => null)) as { id?: unknown } | null;
204
- if (typeof body?.id !== 'string' || body.id === '') {
205
- return Response.json({ error: 'Send the order id as a whole number.' }, { status: 400 });
206
- }
207
- const { data } = await sw.db.from('orders', { where: { id: body.id }, limit: 1 });
208
- const order = data[0] as { id: string; item: string; amount_cents: number; currency: string } | undefined;
209
- if (!order) return Response.json({ error: 'Order not found.' }, { status: 404 });
210
-
211
- const checkout = await sw.payments.checkout({
212
- row: { binding: 'order', id: order.id },
213
- env: 'prod',
214
- line_items: [{ name: order.item, amount: order.amount_cents, currency: order.currency }],
215
- // Your app's own address, including a custom domain, from the request it served.
216
- success_url: new URL('/orders?paid=1', request.url).href,
217
- cancel_url: new URL('/orders', request.url).href,
218
- });
219
- if ('url' in checkout && checkout.url) return Response.json({ url: checkout.url });
220
- return Response.json({ status: 'pending' }, { status: 202 });
221
- }
222
- ```
223
-
224
- - **Live payments only.** A row-bound checkout charges real money: it needs
225
- `env: 'prod'`, a deployed app and a completed payments onboarding. Test mode
226
- is refused with `ROW_TEST_TARGET_UNAVAILABLE`, and a preview or local run
227
- can't start one. Build and test your payment flow with an ordinary checkout
228
- (no `row`) in test mode, then add the binding for live orders.
229
- - **The total must match the row.** The line items add up to the row's amount,
230
- in integer cents, in its currency; otherwise the checkout is refused with
231
- `ROW_TOTAL_MISMATCH`.
232
- - **The status changes once, after payment.** A verified payment moves the
233
- status column from one of `from` to `to`, only if the amount and currency are
234
- unchanged. The amount, currency and status columns can't be in the browser's
235
- `client.create` or `client.update`, and the status column needs a default.
236
- - **One open checkout per row.** The same request again returns the same
237
- session (`reused: true`); a different request while one is open is refused,
238
- and a paid row answers `ROW_ALREADY_PAID`. A result with `status: 'pending'`
239
- has no checkout URL yet; show the order as pending.
240
- - **The signed-in user must be able to update the row** under its table's
241
- scope.
242
- - **Return URLs stay on your app.** `success_url` and `cancel_url` must be on
243
- the project's own address or an attached custom domain; building them from
244
- `request.url` follows whichever of those served the request.
245
-
246
- ## Fees
247
-
248
- The platform wires Stripe Connect for you. You get `payments_*` MCP
249
- tools and `sw.payments` inside deployed functions. End-customers pay
250
- through a Stripe Checkout Session and money settles to the developer's
251
- connected account, minus Stripe's standard processing fee and a 0.5%
252
- platform fee — each checkout response includes `fee_percent` so you can account for it.
253
-
254
- ## You DO NOT need to onboard to start building
255
-
256
- Use a project in your Somewhere account for test-mode checkouts. Call payments_checkout (or
257
- sw.payments.checkout) with env="dev" — when the developer hasn't
258
- onboarded yet, the session runs directly on the platform's own Stripe
259
- test account (no Connect destination, no application fee), so the test
260
- charge with card 4242 4242 4242 4242 succeeds. A test purchase never
261
- changes the user's live plan: gate test access on the signed
262
- `subscription.*` notices or `payment.completed` your webhook receives
263
- (see "What reaches your app in test and live" below). The response includes
264
- `is_stand_in: true` and `platform_fee_cents: 0` so callers know
265
- the fee won't apply on those sessions. Useful for dev demos,
266
- integration tests, or showing the user the flow before they decide
267
- to wire real bank info. Once the developer calls payments_onboard,
268
- dev-mode checkouts use their own test connected account once it can
269
- accept charges (still no live charges; same 4242 card).
270
-
271
- `payments_status` explains this in `readiness`. It reads the owner's account, so it runs from MCP or the CLI, never from deployed app code:
272
- On a normal live status read, `connected: true, onboarded: false` means
273
- a live account exists but onboarding is unfinished. Live (`env: "prod"`) payments answer
274
- `OWNER_NOT_ONBOARDED` until the owner finishes `payments_onboard`.
275
- Test payments (`env: "dev"`) work without onboarding:
276
- `readiness.test.account` says whether they run on your own test account
277
- or on the platform's shared test account.
278
-
279
- An agent calling the platform over MCP:
280
-
281
- ```text
282
- payments_checkout({
283
- project_id: "my-store",
284
- env: "dev",
285
- mode: "payment",
286
- line_items: [{ amount: 4900, currency: "usd", name: "Premium plan" }],
287
- success_url: "https://my-store.somewhere.site/done",
288
- cancel_url: "https://my-store.somewhere.site/cart"
289
- })
290
- ```
291
-
292
- ```js
293
- // Inside a deployed function — env is auto-detected from PROJECT_ENV.
294
- // Use env="prod" for live charges (default once payments_onboard is done).
295
- export default async function(req, sw) {
296
- const user = await sw.auth.fromRequest(req);
297
- if (!user) return Response.json({ error: 'unauthorized' }, { status: 401 });
298
-
299
- const { url } = await sw.payments.checkoutForUser({
300
- plan: 'premium',
301
- mode: 'payment',
302
- line_items: [{ amount: 4900, currency: 'usd', name: 'Premium plan' }],
303
- success_url: new URL('/done', req.url).href,
304
- cancel_url: new URL('/cart', req.url).href
305
- })
306
- // url is null when no hosted checkout page was returned.
307
- if (!url) return Response.json({ error: 'checkout_unavailable' }, { status: 502 });
308
- return Response.redirect(url, 303)
309
- }
310
- ```
311
-
312
- For app-user entitlements, prefer checkoutForUser. The platform creates
313
- a checkout-intent row and sends only that intent id through Stripe
314
- metadata; webhooks derive app_user_id and plan from the platform
315
- database. Do not pass browser-controlled metadata.app_user_id or
316
- metadata.plan through a public handler.
317
-
318
- ## Quote-backed checkout
319
-
320
- Use `sw.payments.quote` when the customer is buying a computed basket
321
- (hotel nights, service fees, local/Stripe tax, promo discounts, deposit)
322
- and checkout must use that immutable server-side snapshot instead of fresh
323
- browser-supplied amounts.
324
-
325
- ```js
326
- const quote = await sw.payments.quote(
327
- {
328
- id: 'cabin-7',
329
- name: 'Cabin 7',
330
- currency: 'usd',
331
- baseRate: { amount: 18000, unit: 'night' },
332
- fees: [
333
- { name: 'Cleaning fee', amount: 4500, kind: 'flat', taxable: true },
334
- { name: 'Guest fee', amount: 2000, kind: 'per_guest_per_night' },
335
- ],
336
- discounts: [{ code: 'WEEKLONG', percent: 10, min_nights: 7 }],
337
- tax: { rate_bps: 875 },
338
- deposit: { percent_bps: 2500, capture_method: 'manual' },
339
- },
340
- { start: '2026-08-01', end: '2026-08-04' },
341
- {
342
- guests: 2,
343
- promo: 'WEEKLONG',
344
- booking: {
345
- id: 'booking_123', // optional; generated if omitted
346
- app_user_id: user.id, // optional; must belong to this project
347
- external_id: 'PMS-42',
348
- metadata: { room: 'cabin-7' },
349
- },
350
- },
351
- );
352
- ```
353
-
354
- `resource.currency` is a 3-letter ISO code. `range` is date-only:
355
- `{ start, end }`, `{ from, to }`, or `['YYYY-MM-DD', 'YYYY-MM-DD']`.
356
- It must span 1 to 366 nights. Amounts are integer cents. Fee `kind` can
357
- be `flat`, `per_night`, `per_guest`, or `per_guest_per_night`.
358
- Discounts accept `amount`, `percent`, or `percent_bps`, plus optional
359
- `min_nights` / `min_guests` and promo codes. `tax.rate_bps` computes
360
- local tax; `tax.stripe: true` requires `opts.tax.customer_details` and
361
- stores Stripe Tax's calculation id/breakdown on the quote.
362
-
363
- The response is a 30-minute immutable quote snapshot. This three-night stay
364
- falls short of the seven nights needed for the WEEKLONG discount.
365
-
366
- ```json
367
- {
368
- "quote_id": "pqt_...",
369
- "booking_id": "booking_123",
370
- "expires_at": "2026-08-01T12:30:00.000Z",
371
- "resource": {
372
- "id": "cabin-7",
373
- "name": "Cabin 7"
374
- },
375
- "range": {
376
- "start": "2026-08-01",
377
- "end": "2026-08-04",
378
- "nights": 3
379
- },
380
- "guests": 2,
381
- "promo": "WEEKLONG",
382
- "currency": "usd",
383
- "subtotal": 70500,
384
- "taxes": {
385
- "amount": 6169,
386
- "source": "local",
387
- "calculation_id": null
388
- },
389
- "deposit": {
390
- "amount": 19167,
391
- "capture_method": "manual"
392
- },
393
- "total": 95836,
394
- "lineItems": [
395
- {"id": "base_18000", "kind": "base", "name": "Cabin 7 nightly rate", "amount": 54000, "currency": "usd", "quantity": 1, "taxable": true, "source": "base_rate"},
396
- {"id": "fee_1", "kind": "fee", "name": "Cleaning fee", "amount": 4500, "currency": "usd", "quantity": 1, "taxable": true, "source": "flat"},
397
- {"id": "fee_2", "kind": "fee", "name": "Guest fee", "amount": 12000, "currency": "usd", "quantity": 1, "taxable": true, "source": "per_guest_per_night"},
398
- {"id": "tax", "kind": "tax", "name": "Estimated tax", "amount": 6169, "currency": "usd", "quantity": 1, "taxable": false, "source": "local"},
399
- {"id": "deposit", "kind": "deposit", "name": "Deposit hold", "amount": 19167, "currency": "usd", "quantity": 1, "taxable": false, "source": "manual"}
400
- ],
401
- "discounts": []
402
- }
403
- ```
404
-
405
- Start checkout with the `quote_id`; do not pass `line_items` again.
406
- The platform reloads the stored `lineItems`, verifies their total, and
407
- atomically marks the quote used so two concurrent checkout calls cannot
408
- create two Stripe sessions for one quote.
409
-
410
- ```js
411
- const checkout = await sw.payments.checkout({
412
- env: 'prod',
413
- quote_id: quote.quote_id,
414
- booking_id: quote.booking_id,
415
- calendar_hold_token: hold.hold_token, // optional: compose quoted price + date hold
416
- success_url: 'https://my-app.somewhere.site/paid',
417
- cancel_url: 'https://my-app.somewhere.site/quote',
418
- customer_email: user.email,
419
- });
420
- // -> { session_id, url, amount_total_cents, platform_fee_cents,
421
- // fee_percent, stripe_mode, is_stand_in, checkout_intent_id,
422
- // quote_id, booking_id, capture_method, payment_intent_id }
423
- ```
424
-
425
- Quote checkouts are one-time `mode: 'payment'` checkouts. They may include a
426
- `calendar_hold_token`; existing quote-only and calendar-only checkouts keep
427
- their prior behavior. For the combined flow, create the hold first and give it
428
- at least 31 minutes of remaining TTL.
429
-
430
- ## Onboarding for live charges
431
-
432
- Call payments_onboard when the developer is ready to take REAL money.
433
- It's per-account (NOT per-project) — one onboard covers every project
434
- the developer owns now or in the future. Returns a Stripe-hosted URL
435
- for KYC + bank info.
436
-
437
- ```text
438
- payments_onboard({
439
- return_url: "https://my-store.somewhere.site/payments/done",
440
- refresh_url: "https://my-store.somewhere.site/payments/retry"
441
- })
442
- ```
443
-
444
- After the developer finishes onboarding, payments_status reports
445
- charges_enabled=true and you can call payments_checkout({ env: "prod" }).
446
-
447
- For your own test account, call the same tool with `mode: 'test'`. Test
448
- onboarding is optional: dev-mode checkouts already work on the shared test
449
- account. A ready test account returns `checkout_ready: true` and
450
- `onboarding_url: null`; otherwise open the returned link. Both Payments
451
- screens in the dashboard also offer **Test setup — no real charges**.
452
- Omitting `mode` keeps live onboarding.
453
-
454
- ## Collaborators
455
-
456
- Anyone with access to the project can run checkouts. Funds always go
457
- to the project OWNER's connected account. If the owner has not
458
- finished live onboarding and a collaborator calls
459
- payments_checkout({ env: "prod" }), the platform returns 412 with code
460
- OWNER_NOT_ONBOARDED and a message telling the caller the owner needs
461
- to onboard first.
462
-
463
- ## What's NOT done for you
464
-
465
- The user-facing pricing page, cart UI, and post-success receipts are
466
- your code. Stripe Connect handles money + tax + payouts. You handle
467
- "what does the customer click before they get to checkout".
468
-
469
- ## The moment payment succeeds — compose the built-ins
470
-
471
- Do post-payment work from a trusted payment event/reconciliation handler,
472
- not from the browser's success-page redirect. After the paid order or plan
473
- state is durably recorded:
474
-
475
- - Send the receipt or confirmation with `sw.email.send(...)` inside the
476
- handler, or `email_send(...)` from an agent/operator flow.
477
- - Track `checkout_completed` with `sw.analytics.track(...)` or
478
- `analytics_track(...)`; track `checkout_started` when you create the
479
- session so the pair becomes a conversion funnel.
480
- - Generate a downloadable invoice/receipt with `sw.render.pdf(...)` or
481
- `browser({ html, capture: { as: "pdf" } })` and store it in the project's files when it will be
482
- reused.
483
- - Run generation or batch email in the background with
484
- `sw.jobs.create(...)` / `job_create(...)`, whether or not you read its
485
- status back.
486
- - Update an open order screen by declaring the order read as a live view
487
- (`sw.rooms.live(name, sw.db.from('orders', …))`) — the write invalidates it
488
- and the browser re-reads. Notify a buyer whose tab is closed with
489
- `sw.push.send({ payload, user_id })` after they turn on notifications
490
- (`enablePush()` from `somewhere:push` — see the push topic).
491
-
492
- Full setup and limits: `docs({ topic: 'sw.email' })`,
493
- `docs({ topic: 'analytics' })`, `docs({ topic: 'render' })`,
494
- `docs({ topic: 'sw.jobs' })`,
495
- `docs({ topic: 'live' })`, and `docs({ topic: 'sw.push' })`.
496
-
497
- ## Webhook events — what each flow actually emits
498
-
499
- The platform's own Stripe webhook (/v1/payments/webhook) is the receiver
500
- for every flow below; you never register it yourself.
501
-
502
- - **Connect status** — keeps charges_enabled / payouts_enabled in sync.
503
- Emits nothing to your app.
504
- - **`checkoutForUser` plan tracking** — confirmed live checkout grants the
505
- selected plan; test grants stay separate. A granted one-time payment also
506
- emits `payment.completed` to the project webhook. A granted subscription
507
- emits signed `subscription.*` notices (below) when it starts and whenever its
508
- status, scheduled end or period end changes, in test and live. Unmatched or replaced paid checkouts
509
- are recorded for repair without emitting a successful plan grant.
510
- - **Calendar checkout** — a completed quote checkout or a one-time checkout
511
- bound to a confirmed calendar hold emits `payment.completed` to the project webhook,
512
- including the reservation details (see the calendar section below).
513
- - **Ad-hoc checkout without plan tracking, a quote or a calendar hold** — a
514
- settled one-time checkout emits `payment.completed` to the project
515
- webhook with `amount_total`, `currency`, `checkout_session_id`,
516
- `payment_intent_id`, `customer_id` and `mode`, plus the metadata you passed at
517
- checkout minus platform-reserved keys. It grants no plan and identifies no
518
- app user (`app_user_id` and `plan` are null): match
519
- `checkout_session_id`, amount, currency and test/live mode to the order you recorded
520
- when you created the checkout before fulfilling it.
521
- - **Refunds of checkout-bound payments** — emit `payment.refunded` with
522
- the charge, payment intent, amount, cumulative refunded amount, currency and
523
- test/live mode. The original payment account and project owner must match.
524
- Recurring invoice refunds and older payments without that binding need your
525
- own Stripe event handler; they do not emit this callback.
526
- - `payment_received`, `subscription_created` and
527
- `subscription_cancelled` are not webhook events: a subscription to them is
528
- refused and receives nothing; delete any existing subscription to them.
529
-
530
- ### Ad-hoc completion body
531
-
532
- A settled ad-hoc one-time checkout sends this shape. The example values are
533
- illustrative; nullable provider values can be null. The stable top-level
534
- `id` identifies the event across retries. Fields and your metadata are
535
- inside `payment`, not `data`; `mode` is `test` or `live`, not the
536
- checkout kind `payment`.
537
-
538
- ```json
539
- {
540
- "id": "pay_example",
541
- "type": "payment.completed",
542
- "payment": {
543
- "project_id": "your-project-id",
544
- "app_user_id": null,
545
- "plan": null,
546
- "amount_total": 1250,
547
- "currency": "usd",
548
- "checkout_session_id": "cs_test_example",
549
- "payment_intent_id": "pi_example",
550
- "customer_id": null,
551
- "mode": "test",
552
- "status": "completed",
553
- "completed_at": "2026-10-08T00:00:00.000Z",
554
- "calendar": null,
555
- "metadata": { "order_id": "order-123" }
556
- }
557
- }
558
- ```
559
-
560
- This is the ad-hoc flow above, not a closed schema for every checkout:
561
- plan and calendar flows can carry their own fields. Check the recorded
562
- session, amount, currency and mode before fulfilling the order.
563
-
564
- For a copyable verifier, use [the existing lifecycle raw-body verifier](/docs/sw.auth#lifecycle-webhook-clean-up-your-own-tables-on-user-delete)
565
- before parsing this body. Both deliveries use `X-Somewhere-Signature` with
566
- `t=<milliseconds>,v1=<HMAC-SHA256>`, signing the exact UTF-8 bytes of
567
- `${t}.${rawBody}` with the secret returned by `auth_webhook_set`.
568
- Keep its timestamp window and Web Crypto signature check; do not reserialize
569
- JSON before verification. After verification, handle `type === 'payment.completed'`
570
- and read `payment`; the example lifecycle handler's auth branches do not
571
- fulfill payments.
572
-
573
- Set the project webhook URL with `auth_webhook_set` to receive these events,
574
- and verify `X-Somewhere-Signature` on every delivery
575
- ([Webhook signatures](/docs/sw.auth#lifecycle-webhook-clean-up-your-own-tables-on-user-delete)).
576
- `payment.completed` is sent only once the checkout is settled: a delayed
577
- payment method sends it when the payment succeeds, and a failed one sends
578
- nothing. Payment callbacks are saved before the provider event is acknowledged.
579
- A temporary receiver failure is retried. While the original payment owner
580
- still owns the project, deliveries can be inspected with
581
- `webhook_deliveries_list` and retried with `webhook_delivery_redrive`.
582
- Retries keep the same body and its top-level `id`; each attempt gets a fresh
583
- signature timestamp. Use the payment signature format linked above, rather
584
- than the bare signature used by webhook subscriptions.
585
-
586
- Deliveries can repeat or arrive concurrently. In one database
587
- transaction, insert a unique fulfillment record for `checkout_session_id`
588
- and apply the order and stock changes; an existing record means those changes
589
- already ran. On every valid delivery, including a duplicate, call
590
- `sw.jobs.create` for follow-up work with the same `idempotency_key`
591
- (for example, `'order-email:' + checkout_session_id`). This returns the
592
- existing job or admits it if an earlier handler stopped before creating it.
593
- Use your own metadata names; keys beginning with `somewhere_` are reserved
594
- for platform bindings and can prevent an ad-hoc completion event.
595
- A calendar checkout whose slot could not be
596
- confirmed emits no completion event.
597
- A new callback also requires the project to belong to the payment's recorded
598
- original owner. If ownership changed or that owner is unknown, the callback
599
- is withheld and recorded for review. Deliveries already recorded keep their
600
- original destination and body, but pending callbacks tied to the previous
601
- owner stop when the project changes owner. Withheld or stopped callbacks have
602
- no automatic handoff to the new owner. The new owner cannot view their delivery
603
- history or retry them, and the previous owner has no access to the project.
604
-
605
- ### Subscription notices
606
-
607
- A subscription granted through `checkoutForUser` sends one signed notice per
608
- applied change to the same webhook URL, with the same signature and retries
609
- as `payment.completed`. A webhook URL needs its secret set for these to be
610
- sent.
611
-
612
- ```json
613
- {
614
- "id": "psub_example",
615
- "type": "subscription.updated",
616
- "subscription": {
617
- "project_id": "your-project-id",
618
- "app_user_id": "user-id",
619
- "subscription_id": "sub_example",
620
- "plan": "pro",
621
- "status": "active",
622
- "cancel_at_period_end": true,
623
- "current_period_end": "2026-11-08T18:21:12.000Z",
624
- "mode": "test",
625
- "grant_revision": 4
626
- }
627
- }
628
- ```
629
-
630
- - `subscription.activated` — the subscription started with access (`active`,
631
- `trialing` or `past_due`).
632
- - `subscription.updated` — its status, `cancel_at_period_end` or
633
- `current_period_end` changed: a scheduled end, a renewal, a resumed plan,
634
- `past_due` while payment retries.
635
- - `subscription.canceled` — it ended; access ends now.
636
-
637
- Grant access while `status` is `active`, `trialing` or `past_due`. With
638
- `cancel_at_period_end: true` the user keeps access until
639
- `current_period_end`; remove access at that time even if delivery of the
640
- `subscription.canceled` notice is delayed. Keep the highest `grant_revision` per project, app user and `mode`; ignore
641
- an older revision that arrives late. Keep test access separate from live access.
642
- The cancellation flag describes a period-end cancellation. A custom cancellation
643
- date can leave it false; false alone does not mean the subscription will renew.
644
- Custom cancellation dates are not yet included in this notice body.
645
- An immediate cancellation through `sw.payments.cancelSubscription`
646
- updates access at once; the provider's own event for that change sends no
647
- second notice. Replacing a subscription with a new plan sends
648
- `subscription.activated` for the new one and nothing more for the old one.
649
-
650
- ### What reaches your app in test and live
651
-
652
- | | Test (`env: "dev"`) | Live (`env: "prod"`) |
653
- |---|---|---|
654
- | Onboarding needed | No | Yes (`payments_onboard`) |
655
- | `payment.completed`, `payment.refunded` | Yes | Yes |
656
- | `subscription.*` notices | Yes | Yes |
657
- | User's live billing grant changes | No (test stays separate) | Yes |
658
- | Billing portal (`portalForUser` with the same `env`) | Yes: cancel at period end, payment method | Yes |
659
- | Current-user cancellation (`cancelForUser` with the same `env`) | Yes | Yes |
660
-
661
- Pass the same `env` to `portalForUser`, `subscriptionForUser`,
662
- `cancelForUser` and `transactions` as the checkout used; a deployed app
663
- defaults to live. `cancelSubscription` is the trusted merchant operation
664
- when your code already has an authorized subscription ID.
665
-
666
- A second Stripe destination is not needed to receive `payment.completed`.
667
- Add one for Stripe-native events outside the flows above, such as disputes
668
- or recurring invoice refunds: register it in the developer's connected account, point it at one
669
- of your deployed functions, and verify its signature with Stripe's own scheme:
670
-
671
- ### Verifying a second Stripe destination in your function
672
-
673
- Stripe's signed content is three parts concatenated, nothing else: the
674
- timestamp from the header in unix SECONDS, then a literal dot, then the exact
675
- raw request body bytes — `${t}.${rawBody}`. The `stripe-signature`
676
- header carries `t=<unix seconds>,v1=<hex>` (possibly several `v1`), and
677
- `v1` is HMAC-SHA256 of that exact string with the endpoint's signing secret.
678
- Milliseconds, a re-serialized body, or the body alone all produce a different
679
- MAC.
680
- Verification requires the exact raw request bytes, a freshness check on
681
- `t` (Stripe's SDK default tolerance is 300 seconds) and a constant-time
682
- compare; the SDK's `constructEventAsync` does all of that, and the platform
683
- verifies its own webhook the same way. When a signature fails, diagnose the
684
- endpoint secret (test vs live, the secret of THIS endpoint), the environment,
685
- whether the body was re-serialized, and header parsing — a
686
- timestamp-dot-body scheme is not evidence that the payload is "not Stripe".
687
- Do not look for `X-Somewhere-Signature` here; that header belongs to the
688
- platform's own flows (drain: `t=<ms>,v1=…` over `${ms}.${rawBody}`;
689
- subscriptions: bare hex over the raw body). This example verifies and stops;
690
- it does not fulfil anything.
691
-
692
- A verified signature proves Stripe sent the event. Before fulfilling, match
693
- the paid session to YOUR order: session id, amount, currency, live mode and
694
- Stripe account, as the handler below does. The two files below are the shared, tested recipe
695
- (`checkout-fulfillment`; the table name is its one parameter, shown as
696
- `payment_requests`). The advisor renders the same bytes, and the platform's
697
- fixtures run them against the real runtime and the real Stripe SDK. Use them
698
- as they are; the checks they carry are the contract.
699
-
700
- ```ts
701
- // db/schema.ts
702
- import { schema, table, id, text, integer, boolean, timestamp, serverOnly } from 'somewhere/db';
703
-
704
- export default schema({
705
- payment_requests: table({
706
- id: id({ uuid: true }),
707
- checkout_session_id: text({ unique: true }),
708
- amount_cents: integer(),
709
- currency: text(),
710
- livemode: boolean(),
711
- stripe_account_id: text({ nullable: true }),
712
- status: text({ default: 'pending' }),
713
- paid_event_id: text({ nullable: true }),
714
- paid_at: timestamp({ nullable: true }),
715
- }, { scope: serverOnly() }),
716
- });
717
- ```
718
-
719
- ```ts
720
- // api/payments/stripe.ts
721
- import Stripe from 'stripe';
722
-
723
- export default async function (req: Request, sw: SomewhereRuntimeContext) {
724
- if (req.method !== 'POST') return new Response('method not allowed', { status: 405 });
725
- const raw = await req.text();
726
- const stripe = new Stripe(sw.env.STRIPE_SECRET_KEY);
727
- let event;
728
- try {
729
- event = await stripe.webhooks.constructEventAsync(
730
- raw, req.headers.get('stripe-signature') ?? '', sw.env.STRIPE_WEBHOOK_SECRET,
731
- );
732
- } catch {
733
- return new Response('bad signature', { status: 400 });
734
- }
735
- if (event.type !== 'checkout.session.completed') return new Response('ok');
736
- const session = event.data.object;
737
- if (session.mode !== 'payment' || session.payment_status !== 'paid' ||
738
- typeof session.id !== 'string' || !Number.isSafeInteger(session.amount_total) ||
739
- typeof session.currency !== 'string' || typeof session.livemode !== 'boolean' ||
740
- event.livemode !== session.livemode) return new Response('payment mismatch', { status: 409 });
741
- const found = await sw.db.from('payment_requests', { where: { checkout_session_id: session.id }, limit: 1 });
742
- const order = found.data[0];
743
- if (typeof event.id !== 'string' || (event.account !== undefined && typeof event.account !== 'string')) {
744
- return new Response('payment mismatch', { status: 409 });
745
- }
746
- const account = event.account ?? null;
747
- if (!order || order.checkout_session_id !== session.id ||
748
- order.amount_cents !== session.amount_total || order.currency !== session.currency ||
749
- ![true, false, 0, 1].includes(order.livemode) || Boolean(order.livemode) !== session.livemode || order.stripe_account_id !== account) {
750
- return new Response('payment mismatch', { status: 409 });
751
- }
752
- const where = {
753
- id: order.id, checkout_session_id: session.id, status: 'pending',
754
- amount_cents: order.amount_cents, currency: order.currency,
755
- livemode: order.livemode, stripe_account_id: account,
756
- };
757
- const updated = await sw.db.update('payment_requests', {
758
- set: { status: 'paid', paid_event_id: event.id, paid_at: new Date().toISOString() }, where,
759
- });
760
- if (updated.data.length === 1 && updated.data[0].id === order.id) return Response.json({ ok: true, transitioned: true });
761
- const current = (await sw.db.from('payment_requests', { where: { id: order.id }, limit: 1 })).data[0];
762
- if (current?.status === 'paid' && current.paid_event_id === event.id &&
763
- current.checkout_session_id === session.id && current.amount_cents === order.amount_cents &&
764
- current.currency === order.currency && current.livemode === order.livemode &&
765
- current.stripe_account_id === account) return Response.json({ ok: true, transitioned: false });
766
- return new Response('payment state unresolved', { status: 409 });
767
- }
768
- ```
769
-
770
- What the recipe enforces, and why each line is there:
771
-
772
- - **This tested recipe's fulfilment table is declared `serverOnly()`.**
773
- Merge that table into your current `db/schema.ts` rather than replacing
774
- the file. A webhook has no signed-in user, so ordinary caller-scoped
775
- `sw.db.update` / `remove` cannot write another user's `owner()` row.
776
- On visitor-enabled tables, a caller-scoped conditional update may simply
777
- change zero rows. Use explicit server authority for the managed-row webhook
778
- write. Keep the managed scopes and client grants on your other tables. A webhook
779
- does not require converting them to `serverOnly()`: a function can use
780
- an explicitly authorized `sw.db.server` write on a managed table after
781
- verifying the event and matching it to the stored order. Use the tested
782
- recipe above unchanged for its receipt and fulfilment transition.
783
- - **The stored order is the authority.** Session id, amount in minor units,
784
- lowercase currency, and `livemode` are recorded when the session is
785
- created and compared against both the event and the session. Mode is not a
786
- setting and not derived from a key prefix: the webhook is authenticated by
787
- its signing secret, and the order row says which mode it was created in.
788
- - **Connect is a variant, not a check.** `stripe_account_id` is the
789
- connected account for Connect deliveries and `null` for a direct,
790
- account-specific endpoint, where `event.account` is absent. Its absence
791
- is not a failure.
792
- - **Receipt and transition are ONE statement on the order row.** The
793
- composed `sw.db.tx` can commit several writes atomically, but a guarded
794
- update matching zero rows is a successful no-op: it does not abort sibling
795
- writes. A separate receipt insert therefore cannot use that update as its
796
- success condition. The
797
- guarded update binds id, session, status `pending` and every compared
798
- value; one returned row means this call fulfilled, none means re-read and
799
- classify: the same event already applied is a duplicate (200), anything
800
- else is unresolved (409). An events table written after the transition is
801
- fine as an audit log; it must never be the gate.
802
- - **Limit:** side effects (email, PDF, stock) are outside the statement. A
803
- crash after the update and before the side effect is lost on retry, since
804
- the retry sees zero changes. Set a fulfilment marker in the same update and
805
- drain it from a scheduled job if that loss is unacceptable. On an unmanaged
806
- (SQL-mode) schema, `sw.db.batch` runs as one all-or-nothing batch.
807
- - **Subscriptions** (`mode: 'subscription'`): treat
808
- `checkout.session.completed` as "subscription started" and take paid /
809
- unpaid state from `invoice.paid` / `invoice.payment_failed` for the
810
- subscription id, with the same single-row guard keyed on the invoice id.
811
-
812
- ## Automatic plan tracking on app_users
813
-
814
- Want the current billing plan to become "premium" when the customer pays
815
- and return to free when their paid access ends, without writing a webhook
816
- handler? Use `checkoutForUser` from inside a deployed function.
817
- The platform stores the verified user, price and payment account before
818
- checkout, then verifies that record on completion. A browser cannot spoof
819
- `app_user_id` or `plan`. Replace `price_PREMIUM_MONTHLY` with a recurring price
820
- from your connected Stripe account. The pricing page posts to this handler and
821
- opens the returned URL.
822
-
823
- ```ts
824
- // api/subscribe.ts
825
- export default async function subscribe(req: Request, sw: SomewhereRuntimeContext): Promise<Response> {
826
- if (req.method !== 'POST') {
827
- return new Response('Use POST.', { status: 405, headers: { Allow: 'POST' } });
828
- }
829
- const user = await sw.auth.fromRequest(req);
830
- if (!user) return Response.json({ error: 'Sign in.' }, { status: 401 });
831
-
832
- const { url } = await sw.payments.checkoutForUser({
833
- plan: 'premium',
834
- mode: 'subscription',
835
- env: 'prod',
836
- line_items: [{ price: 'price_PREMIUM_MONTHLY', quantity: 1 }],
837
- success_url: new URL('/billing/success', req.url).href,
838
- cancel_url: new URL('/billing/cancel', req.url).href,
839
- customer_email: user.email,
840
- });
841
- if (!url) return Response.json({ error: 'Checkout is unavailable.' }, { status: 502 });
842
- return Response.json({ url });
843
- }
844
- ```
845
-
846
- The platform checks the selected checkout, original account and current
847
- subscription before granting access. A pending replacement checkout keeps the
848
- current paid grant. Older completions cannot replace a newer selection.
849
-
850
- Read the effective live plan with `sw.billing.entitlements()`, which is current
851
- on every call. Use it after checking sign-in.
852
-
853
- ```ts
854
- // api/premium-content.ts
855
- export default async function premiumContent(req: Request, sw: SomewhereRuntimeContext): Promise<Response> {
856
- const user = await sw.auth.fromRequest(req);
857
- if (!user) return new Response('Sign in', { status: 401 });
858
- const { plan } = await sw.billing.entitlements();
859
- if (plan !== 'premium') return new Response('Upgrade required', { status: 403 });
860
- return Response.json({ content: 'Welcome to Premium.' });
861
- }
862
- ```
863
-
864
- Active, trialing, canceling and past-due subscriptions retain access. Unpaid,
865
- paused, canceled and expired subscriptions return `plan: "free"`.
866
- Test-mode purchases never change this live plan. Historical payments without
867
- a stored binding remain visible for reconciliation rather than granting access
868
- from metadata.
869
-
870
- ## Manual-capture deposits
871
-
872
- Set `deposit` to a cents number or use
873
- `deposit: { amount: 5000, capture_method: 'manual' }` in the resource
874
- passed to `sw.payments.quote`. Use `percent` or `percent_bps` for a percentage
875
- instead. When a deposit is present, the capture method defaults to `'manual'`.
876
-
877
- Manual deposits add a `kind: 'deposit'` line item and make quote checkout
878
- create a manual-capture PaymentIntent. When Stripe reports
879
- `checkout.session.completed`, the quote booking moves to `authorized`
880
- instead of `completed`, and the project webhook receives
881
- `payment.completed` with `capture_method: 'manual'`, `status:
882
- 'authorized'`, `quote_id`, `booking_id`, `payment_intent_id`, and the
883
- quote/booking snapshots.
884
-
885
- Capture or release the authorization exactly once from trusted server/operator
886
- code using the REST endpoints. There are no dedicated `sw.payments.capture`
887
- or MCP `payments_capture` helpers yet, so do not claim one exists.
888
-
889
- ```http
890
- POST /v1/payments/capture
891
- Authorization: Bearer smt_...
892
- Content-Type: application/json
893
-
894
- {
895
- "project_id": "my-app",
896
- "booking_id": "booking_123",
897
- "amount": 5000,
898
- "env": "prod"
899
- }
900
- ```
901
-
902
- `booking_id` or `payment_intent_id` is required. `amount` is optional;
903
- when omitted, the platform captures the authorized deposit amount, not the
904
- full quote total. If supplied, `amount` must be a positive integer cents
905
- value and cannot exceed `deposit_cents`. The booking must be manual capture,
906
- `authorized`, uncaptured, and unreleased. The response:
907
-
908
- ```json
909
- {
910
- "ok": true,
911
- "data": {
912
- "booking_id": "booking_123",
913
- "quote_id": "pqt_...",
914
- "payment_intent_id": "pi_...",
915
- "status": "succeeded",
916
- "captured_cents": 5000,
917
- "stripe_mode": "live"
918
- }
919
- }
920
- ```
921
-
922
- Release cancels an uncaptured authorization:
923
-
924
- ```http
925
- POST /v1/payments/release
926
- Authorization: Bearer smt_...
927
- Content-Type: application/json
928
-
929
- {
930
- "project_id": "my-app",
931
- "booking_id": "booking_123",
932
- "env": "prod"
933
- }
934
- ```
935
-
936
- Response:
937
-
938
- ```json
939
- {
940
- "ok": true,
941
- "data": {
942
- "booking_id": "booking_123",
943
- "quote_id": "pqt_...",
944
- "payment_intent_id": "pi_...",
945
- "status": "canceled",
946
- "stripe_mode": "live"
947
- }
948
- }
949
- ```
950
-
951
- Both API paths and Stripe webhook replays use conditional state transitions:
952
- `authorized -> captured` or `authorized -> released` only, with
953
- `captured_at IS NULL` and `released_at IS NULL`. A replay, double-click,
954
- capture-after-release, or release-after-capture returns/settles as a state
955
- conflict instead of charging twice.
956
-
957
- ## Refunds, cancels, transactions, portal, events
958
-
959
- Five more endpoints round out the payments surface so you don't need
960
- to drop down to the Stripe SDK or build a custom dashboard.
961
-
962
- ### Refund a charge
963
-
964
- ```js
965
- // Inside a deployed function. Use the recorded payment_intent_id
966
- // from the settled payment, and select the same environment as the charge.
967
- const refund = await sw.payments.refund({
968
- env: 'dev', // Use 'prod' for a live charge.
969
- payment_intent_id: 'pi_3PqXYZ...',
970
- // amount: 1000, // omit for full refund (in cents)
971
- // reason: 'requested_by_customer'
972
- });
973
- // → { refund_id, status, amount, currency, charge_id, ... }
974
- ```
975
-
976
- Stripe's processing fees are handled by Stripe's standard refund policy.
977
-
978
- ### Cancel a subscription
979
-
980
- ```js
981
- await sw.payments.cancelSubscription({ subscription_id: 'sub_...' });
982
- // Default: cancel_at_period_end=true — customer keeps access until period end.
983
-
984
- await sw.payments.cancelSubscription({ subscription_id: 'sub_...', immediately: true });
985
- // Check cancellation and access_sync in the response before reporting success.
986
- ```
987
-
988
- For a tracked subscription, the platform applies the provider-confirmed status
989
- to access. A confirmed cancellation with `access_sync: 'pending'` means billing
990
- stopped but the access update needs repair; do not cancel again. Historical
991
- subscriptions without a stored payment binding require reconciliation.
992
-
993
- ### List recent transactions
994
-
995
- ```js
996
- const { transactions, next_cursor } = await sw.payments.transactions({ limit: 20 });
997
- // → transactions: [{ id, amount, currency, status, paid, refunded,
998
- // created, customer_id, payment_intent_id, ... }]
999
- // Paginate with: sw.payments.transactions({ limit: 20, starting_after: next_cursor })
1000
- ```
1001
-
1002
- ### Open the Stripe Billing Portal for an end-customer
1003
-
1004
- The portal lets customers update their card, switch plans, view
1005
- invoices, and cancel themselves — no support ticket required.
1006
-
1007
- ```ts
1008
- // api/billing-portal.ts — the page POSTs here from its "Manage billing" button
1009
- export default async function billingPortal(
1010
- request: Request,
1011
- sw: SomewhereRuntimeContext,
1012
- ): Promise<Response> {
1013
- if (request.method !== 'POST') {
1014
- return new Response('Use POST.', { status: 405, headers: { Allow: 'POST' } });
1015
- }
1016
- const user = await sw.auth.fromRequest(request);
1017
- if (!user) return Response.json({ error: 'Sign in.' }, { status: 401 });
1018
-
1019
- // No user id argument: the runtime derives the signed-in user itself.
1020
- const { url } = await sw.payments.portalForUser({
1021
- return_url: new URL('/account/billing', request.url).href,
1022
- });
1023
- return Response.redirect(url, 303);
1024
- }
1025
- ```
1026
-
1027
- `portalForUser({ return_url, env })` opens billing for the signed-in user.
1028
- The runtime supplies verified user proof; the platform selects that user's
1029
- stored customer. Never accept `customer_id` from a browser body or URL.
1030
- Pass the same `env` used at checkout: `"dev"` for test payments,
1031
- `"prod"` for live payments.
1032
-
1033
- ### Show or cancel the signed-in user's subscription
1034
-
1035
- In a signed-in function, read the user's plan subscription with
1036
- `sw.payments.subscriptionForUser({ env })`, using the same `env` as checkout
1037
- (`"dev"` for test, `"prod"` for live). It returns the plan, status, access,
1038
- period end and whether it is set to cancel at the end of the period. A user
1039
- without a subscription gets `NO_SUBSCRIPTION`.
1040
-
1041
- For a confirmed cancellation action, call
1042
- `sw.payments.cancelForUser({ env })` from a POST handler. The default
1043
- keeps access until the period ends; `immediately: true` cancels now. Neither
1044
- method takes a user, customer or subscription ID: the verified session selects
1045
- whose subscription is read or changed.
1046
-
1047
- Check the cancellation result: `cancellation: "confirmed"` with
1048
- `access_sync: "applied"` means billing and access are updated.
1049
- `access_sync: "pending"` means billing changed and access repair is pending;
1050
- do not send another cancellation. `already_canceled` means no provider call
1051
- was needed. For `not_confirmed` or `not_applied`, read the current subscription
1052
- before acting; do not loop cancellations.
1053
-
1054
- The call throws `PAYMENTS_CANCEL_OUTCOME_UNKNOWN` when the provider gives no
1055
- definite answer. The stored status updates when its event arrives, so check
1056
- again later instead of immediately retrying cancellation.
1057
-
1058
- Apps deployed before this change must be deployed again: until then,
1059
- `portalForUser` is refused and the new helpers are unavailable.
1060
-
1061
- `sw.payments.portal({ customer_id, ... })` still exists for trusted
1062
- server/operator flows where your code already loaded the customer id from
1063
- your own database and checked that the caller may manage that customer. Do
1064
- not use it for "current signed-in user" account pages.
1065
-
1066
- (Stripe auto-creates a default portal configuration on first use.
1067
- Advanced settings — what plans are switchable, custom branding —
1068
- need a one-time click in the connected account's Stripe dashboard.)
1069
-
1070
- ### Read the webhook event ledger
1071
-
1072
- Every Stripe event the platform's webhook receives is persisted in a
1073
- ledger you can read back. The handler is idempotent — Stripe
1074
- redeliveries (which happen on transport failures) appear exactly
1075
- once. Use this to drive an in-product activity feed or to verify
1076
- delivery during integration.
1077
-
1078
- ```js
1079
- const { events, next_cursor } = await sw.payments.events({
1080
- limit: 50,
1081
- // type: 'checkout.session.completed', // optional filter
1082
- // before: 1715000000000, // ms-epoch cursor
1083
- });
1084
- // → events: [{ id, type, mode, account_id, project_id,
1085
- // amount_cents, currency, livemode, received_at }]
1086
- ```
1087
-
1088
- ### One-time vs subscription
1089
-
1090
- `payments_checkout` accepts `mode: 'payment'` (one-time charge)
1091
- or `mode: 'subscription'` (recurring billing). Same endpoint, same
1092
- automatic plan-tracking metadata. Default is
1093
- `'payment'`.
1094
-
1095
- ### Gating features after payment
1096
-
1097
- Payments collect the money; `sw.billing` turns a paid plan into feature
1098
- yes/no answers. Pair them: `checkoutForUser({ plan: 'pro' })` sets the
1099
- user's plan on success, then `await sw.billing.has('export')` authorizes the
1100
- server operation. The browser can present an explicit billing observation
1101
- with `<Gate billing={billing} feature="export">` — no webhook code. See `docs({ topic:
1102
- 'sw.billing' })`.