create-usebecky 0.0.0-stage → 0.2.0
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.
- package/README.md +80 -2
- package/dist/create.js +842 -0
- package/dist/extension-skill/usebecky-extension/SKILL.md +181 -0
- package/dist/extension-skill/usebecky-extension/references/accounts.md +125 -0
- package/dist/extension-skill/usebecky-extension/references/dev-server.md +102 -0
- package/dist/extension-skill/usebecky-extension/references/manifest.md +104 -0
- package/dist/extension-skill/usebecky-extension/references/oauth-and-tokens.md +179 -0
- package/dist/extension-skill/usebecky-extension/references/partner-api.md +87 -0
- package/dist/extension-skill/usebecky-extension/references/submit-and-pricing.md +31 -0
- package/dist/extension-skill/usebecky-extension/references/ui.md +172 -0
- package/dist/extension-skill/usebecky-extension/references/webhooks.md +97 -0
- package/dist/index.js +10 -0
- package/dist/keys.js +72 -0
- package/dist/platform.js +104 -0
- package/dist/pm.js +69 -0
- package/dist/prompts.js +242 -0
- package/dist/scaffold.js +108 -0
- package/dist/setup.js +130 -0
- package/dist/shared/ai.js +203 -0
- package/dist/shared/extension-skill.js +107 -0
- package/dist/shared/framework.js +460 -0
- package/dist/shared/hosted.js +8 -0
- package/dist/shared/ui.js +141 -0
- package/dist/skill/usebecky/SKILL.md +339 -0
- package/dist/skill/usebecky/references/access-rules.md +307 -0
- package/dist/skill/usebecky/references/addons.md +68 -0
- package/dist/skill/usebecky/references/analytics.md +166 -0
- package/dist/skill/usebecky/references/android.md +434 -0
- package/dist/skill/usebecky/references/auth.md +379 -0
- package/dist/skill/usebecky/references/cache.md +51 -0
- package/dist/skill/usebecky/references/components.md +127 -0
- package/dist/skill/usebecky/references/emails.md +105 -0
- package/dist/skill/usebecky/references/expo.md +147 -0
- package/dist/skill/usebecky/references/functions.md +99 -0
- package/dist/skill/usebecky/references/hosting.md +119 -0
- package/dist/skill/usebecky/references/http-api.md +233 -0
- package/dist/skill/usebecky/references/ios.md +355 -0
- package/dist/skill/usebecky/references/payments.md +493 -0
- package/dist/skill/usebecky/references/realtime.md +143 -0
- package/dist/skill/usebecky/references/scheduled-jobs.md +82 -0
- package/dist/skill/usebecky/references/sdk.md +838 -0
- package/dist/skill/usebecky/references/storage.md +210 -0
- package/dist/skill/usebecky/references/templates.md +191 -0
- package/dist/skill/usebecky/references/wordpress.md +87 -0
- package/dist/templates.js +74 -0
- package/package.json +37 -4
- package/templates/expo/App.tsx +48 -0
- package/templates/expo/README.md +59 -0
- package/templates/expo/_env.example +4 -0
- package/templates/expo/_gitignore +12 -0
- package/templates/expo/app.json +25 -0
- package/templates/expo/assets/icon.png +0 -0
- package/templates/expo/brand.ts +7 -0
- package/templates/expo/components/Avatar.tsx +75 -0
- package/templates/expo/components/ui.tsx +57 -0
- package/templates/expo/index.ts +4 -0
- package/templates/expo/lib/theme.ts +43 -0
- package/templates/expo/lib/usebecky.ts +15 -0
- package/templates/expo/package.json +29 -0
- package/templates/expo/screens/Home.tsx +187 -0
- package/templates/expo/screens/SignIn.tsx +112 -0
- package/templates/expo/tsconfig.json +6 -0
- package/templates/expo/usebecky.template.json +36 -0
- package/templates/extension/README.md +128 -0
- package/templates/extension/_env.example +21 -0
- package/templates/extension/_gitignore +11 -0
- package/templates/extension/logo.svg +1 -0
- package/templates/extension/package.json +25 -0
- package/templates/extension/src/accounts.ts +90 -0
- package/templates/extension/src/app.ts +178 -0
- package/templates/extension/src/pages.ts +108 -0
- package/templates/extension/src/replay-guard.ts +17 -0
- package/templates/extension/src/server.ts +57 -0
- package/templates/extension/src/settings.ts +69 -0
- package/templates/extension/src/ui.ts +70 -0
- package/templates/extension/test/app.test.ts +222 -0
- package/templates/extension/tsconfig.json +16 -0
- package/templates/extension/usebecky-extension.json +36 -0
- package/templates/extension/usebecky.template.json +22 -0
- package/templates/landing/README.md +43 -0
- package/templates/landing/_env.example +4 -0
- package/templates/landing/_gitignore +9 -0
- package/templates/landing/index.html +16 -0
- package/templates/landing/package.json +28 -0
- package/templates/landing/public/icon.svg +1 -0
- package/templates/landing/src/App.tsx +97 -0
- package/templates/landing/src/components/Contact.tsx +43 -0
- package/templates/landing/src/components/Counter.tsx +34 -0
- package/templates/landing/src/components/Feedback.tsx +36 -0
- package/templates/landing/src/components/Logo.tsx +11 -0
- package/templates/landing/src/components/Receipt.tsx +128 -0
- package/templates/landing/src/components/Setup.tsx +20 -0
- package/templates/landing/src/components/fields.tsx +63 -0
- package/templates/landing/src/content.ts +22 -0
- package/templates/landing/src/index.css +119 -0
- package/templates/landing/src/lib/usebecky.ts +11 -0
- package/templates/landing/src/lib/waitlist.ts +46 -0
- package/templates/landing/src/main.tsx +12 -0
- package/templates/landing/src/vite-env.d.ts +6 -0
- package/templates/landing/tsconfig.json +19 -0
- package/templates/landing/usebecky.template.json +20 -0
- package/templates/landing/vite.config.ts +10 -0
- package/templates/notes/README.md +68 -0
- package/templates/notes/_env.example +4 -0
- package/templates/notes/_gitignore +9 -0
- package/templates/notes/index.html +15 -0
- package/templates/notes/package.json +28 -0
- package/templates/notes/public/icon.svg +1 -0
- package/templates/notes/src/App.tsx +35 -0
- package/templates/notes/src/brand.ts +7 -0
- package/templates/notes/src/components/Composer.tsx +113 -0
- package/templates/notes/src/components/NoteEntry.tsx +151 -0
- package/templates/notes/src/components/Notes.tsx +163 -0
- package/templates/notes/src/components/Setup.tsx +44 -0
- package/templates/notes/src/components/SignIn.tsx +112 -0
- package/templates/notes/src/components/icons.tsx +54 -0
- package/templates/notes/src/index.css +105 -0
- package/templates/notes/src/lib/notes.ts +68 -0
- package/templates/notes/src/lib/usebecky.ts +9 -0
- package/templates/notes/src/main.tsx +22 -0
- package/templates/notes/src/vite-env.d.ts +6 -0
- package/templates/notes/tsconfig.json +19 -0
- package/templates/notes/usebecky.template.json +34 -0
- package/templates/notes/vite.config.ts +10 -0
- package/templates/saas/README.md +69 -0
- package/templates/saas/_env.example +10 -0
- package/templates/saas/_gitignore +11 -0
- package/templates/saas/app/(app)/account/ManageBilling.tsx +26 -0
- package/templates/saas/app/(app)/account/page.tsx +71 -0
- package/templates/saas/app/(app)/dashboard/Projects.tsx +227 -0
- package/templates/saas/app/(app)/dashboard/page.tsx +21 -0
- package/templates/saas/app/(app)/layout.tsx +29 -0
- package/templates/saas/app/(app)/premium/page.tsx +62 -0
- package/templates/saas/app/auth/callback/page.tsx +33 -0
- package/templates/saas/app/globals.css +143 -0
- package/templates/saas/app/icon.svg +1 -0
- package/templates/saas/app/layout.tsx +20 -0
- package/templates/saas/app/page.tsx +87 -0
- package/templates/saas/app/pricing/Plans.tsx +133 -0
- package/templates/saas/app/pricing/TestCardHint.tsx +18 -0
- package/templates/saas/app/pricing/page.tsx +21 -0
- package/templates/saas/app/setup/page.tsx +34 -0
- package/templates/saas/app/sign-in/SignInForm.tsx +195 -0
- package/templates/saas/app/sign-in/page.tsx +21 -0
- package/templates/saas/brand.ts +10 -0
- package/templates/saas/components/AppNav.tsx +45 -0
- package/templates/saas/components/Logo.tsx +22 -0
- package/templates/saas/components/SiteHeader.tsx +50 -0
- package/templates/saas/components/Status.tsx +15 -0
- package/templates/saas/lib/session.ts +26 -0
- package/templates/saas/lib/usebecky.ts +11 -0
- package/templates/saas/next-env.d.ts +5 -0
- package/templates/saas/next.config.ts +5 -0
- package/templates/saas/package.json +26 -0
- package/templates/saas/postcss.config.mjs +3 -0
- package/templates/saas/tsconfig.json +21 -0
- package/templates/saas/usebecky.template.json +31 -0
|
@@ -0,0 +1,493 @@
|
|
|
1
|
+
# Payments (Stripe)
|
|
2
|
+
|
|
3
|
+
usebecky connects the developer's own Stripe account (Stripe Connect). Products and prices are defined in usebecky and synced to Stripe; customers pay on Stripe's hosted checkout page or in an embedded payment form on the app's page (Stripe Payment Element); the customer portal is a Stripe-hosted page; Stripe webhooks are handled by usebecky, which mirrors subscriptions and purchases into the project's `billing` schema. Your app never touches Stripe keys or Stripe webhooks.
|
|
4
|
+
|
|
5
|
+
## Concepts
|
|
6
|
+
|
|
7
|
+
| Term | Meaning | Example |
|
|
8
|
+
|---|---|---|
|
|
9
|
+
| Product `key` | Stable id you use in code and SQL | `pro`, `ebook` |
|
|
10
|
+
| Product `type` | `subscription` or `one_time` | |
|
|
11
|
+
| Price `key` | What you pass to `checkout()` | `pro_monthly`, `pro_yearly`, `ebook_once` |
|
|
12
|
+
| `features` | Extra feature keys a product grants | `['pro', 'export']` |
|
|
13
|
+
| Access to a feature | Active or trialing subscription, past_due within the grace period (default 3 days), a paid unrefunded purchase, or a running gift, for a product whose key equals the feature or whose `features` contain it | `hasAccess('pro')` |
|
|
14
|
+
| Gift | A product the developer gave a user for free (dashboard or `baas.payments.gift()`), optionally until a date. A subscription with `source: 'gift'`: grants access like a paid one, never revenue, no Stripe | `source === 'gift'` |
|
|
15
|
+
| Subscription `source` | `'paid'` (Stripe), `'trial'` (Stripe trial) or `'gift'` (free) | `me().subscriptions[0].source` |
|
|
16
|
+
|
|
17
|
+
Amounts are integers in minor units: `900` = $9.00. A trial is granted once per user per product. Stripe's promotion code box is shown at checkout unless `promotionCodes: false`, except for one-time products on the Free plan: there, pass the code the customer typed in the app as `coupon` (checked before Stripe opens: `invalid_coupon`, `coupon_expired`, `coupon_not_applicable`).
|
|
18
|
+
|
|
19
|
+
## Test mode and live mode
|
|
20
|
+
|
|
21
|
+
Every project is in **test mode** (Stripe test cards, nothing is charged) or **live mode** (real money). New projects start in test mode; the developer switches in Dashboard → Payments → Go live, or `npx usebecky payments mode live` once the live Stripe account is connected (`payments mode` shows what is missing; `payments mode test` switches back). Every plan can go live. On Free, usebecky keeps a 3% platform fee of each sale (taken out of the sale; the buyer pays exactly the price); Pro and Business pay no platform fee. The fee follows the project's plan, also for subscriptions that are already running, and refunds give it back in proportion. Don't add the fee to prices. App code doesn't change between modes: the same `checkout()`, `createPayment()`, `hasAccess()` calls use the right Stripe keys and account by themselves.
|
|
22
|
+
|
|
23
|
+
- `baas.payments.mode()` → `'test' | 'live' | null`. Show test-card hints **only** in test mode:
|
|
24
|
+
|
|
25
|
+
```ts
|
|
26
|
+
// inside an async function:
|
|
27
|
+
const { data: mode } = await baas.payments.mode()
|
|
28
|
+
const hint = document.querySelector('#test-card-hint')
|
|
29
|
+
if (hint && mode === 'test') hint.textContent = 'Test mode: pay with 4242 4242 4242 4242, any future date, any CVC.'
|
|
30
|
+
```
|
|
31
|
+
|
|
32
|
+
Never hard-code a test-card hint: it would show on the live app. `<PaymentForm>` already shows it only in test mode.
|
|
33
|
+
- Test and live data never mix. In live mode, purchases made with test cards don't grant access; live purchases always do (also in test mode). Gifts work in both. `me()` lists only what counts in the current mode (`me().mode`); subscriptions and purchases carry `livemode`.
|
|
34
|
+
- Billing webhooks to your server carry `livemode` on the subscription / purchase. Test rows changing while the project is live send no events.
|
|
35
|
+
- `createPayment()` returns `livemode`; `checkout()` returns `{ url, id, livemode }`.
|
|
36
|
+
|
|
37
|
+
## Setup (dashboard, done by the developer)
|
|
38
|
+
|
|
39
|
+
1. Dashboard → Payments → Stripe connection: connect a Stripe account (a test account works while developing). Before taking real money: Dashboard → Payments → Go live (the plan's fee, explained; live Stripe account, live webhooks (set up automatically), one test purchase, then "Switch to live").
|
|
40
|
+
2. Products: write them in `usebecky/config.json` and run `npx usebecky config push` yourself (or Dashboard → Payments → Products). Keys, prices (amount in cents, `month`/`year` interval for subscriptions, optional `trial_days`) and features; a one-time product can carry a download file (`download: {bucket, path}`):
|
|
41
|
+
|
|
42
|
+
```json
|
|
43
|
+
{ "payments": { "products": {
|
|
44
|
+
"pro": { "name": "Pro", "type": "subscription", "features": ["pro"], "prices": { "pro_monthly": { "amount": 500, "currency": "eur", "interval": "month" } } },
|
|
45
|
+
"ebook": { "name": "The Ebook", "type": "one_time", "download": { "bucket": "downloads", "path": "ebook.pdf" }, "prices": { "ebook_once": { "amount": 1500, "currency": "eur" } } }
|
|
46
|
+
} } }
|
|
47
|
+
```
|
|
48
|
+
A new amount makes a new Stripe price (running subscriptions keep theirs); products not in the file are left alone. Connecting Stripe needs the user to sign in at Stripe once: `npx usebecky payments connect` opens it and waits (or Dashboard → Payments).
|
|
49
|
+
3. Payment settings: default `success_url`, `cancel_url`, `portal_return_url`, past-due grace days, the shop's terms URL (Payments → Stripe connection → More settings → Your shop's terms).
|
|
50
|
+
4. In the Stripe Dashboard: Settings → Billing → Customer portal → Save, otherwise `portal()` fails with `portal_not_configured`.
|
|
51
|
+
|
|
52
|
+
You cannot create products from app code. Read the keys from `usebecky/config.json`, `npx usebecky payments products`, or `products()`.
|
|
53
|
+
|
|
54
|
+
## Client
|
|
55
|
+
|
|
56
|
+
```ts
|
|
57
|
+
// inside an async function:
|
|
58
|
+
// Catalog (works signed out)
|
|
59
|
+
const { data: products, error } = await baas.payments.products()
|
|
60
|
+
// [{ id, key: 'pro', name: 'Pro', description, type: 'subscription', features: ['pro'], active: true, image_url: null,
|
|
61
|
+
// prices: [{ id, key: 'pro_monthly', product_key: 'pro', amount: 900, currency: 'usd', interval: 'month', trial_days: 14, active: true },
|
|
62
|
+
// { id, key: 'pro_yearly', product_key: 'pro', amount: 9000, currency: 'usd', interval: 'year', trial_days: 14, active: true }],
|
|
63
|
+
// has_download: false, download: null }]
|
|
64
|
+
|
|
65
|
+
// Checkout: the user must be signed in. Redirects the browser to Stripe.
|
|
66
|
+
// Without URLs: the dashboard's checkout settings, else back to the current page (+ ?checkout=success after paying).
|
|
67
|
+
await baas.payments.checkout('pro_monthly')
|
|
68
|
+
const { error: checkoutError } = await baas.payments.checkout('pro_monthly', {
|
|
69
|
+
successUrl: `${location.origin}/billing?checkout=success`,
|
|
70
|
+
cancelUrl: `${location.origin}/pricing`,
|
|
71
|
+
quantity: 1, // 1 to 100
|
|
72
|
+
promotionCodes: true, // default true: Stripe's own code box (not shown for one-time products on Free)
|
|
73
|
+
// coupon: 'SUMMER20', // a code the customer typed in your app; then data also has amount (after the discount) and currency
|
|
74
|
+
redirect: true, // false: just return { url, id }
|
|
75
|
+
})
|
|
76
|
+
if (checkoutError?.code === 'already_subscribed') await baas.payments.portal()
|
|
77
|
+
|
|
78
|
+
// Manage plan, cancel, update card (Stripe customer portal)
|
|
79
|
+
await baas.payments.portal({ returnUrl: `${location.origin}/billing` }) // data: { url }; redirects in browsers
|
|
80
|
+
|
|
81
|
+
// Or your own cancel button (e.g. Germany's legally required "Verträge hier kündigen" page): the user's own subscription
|
|
82
|
+
const subId = '5d2c8a1e-…' // a subscription id from me()
|
|
83
|
+
const { data: canceled } = await baas.payments.cancelSubscription(subId) // at the period end (default): access stays until current_period_end
|
|
84
|
+
await baas.payments.cancelSubscription(subId, { atPeriodEnd: false }) // ends now, access too (no refund)
|
|
85
|
+
await baas.payments.resumeSubscription(subId) // take a cancellation at the period end back
|
|
86
|
+
|
|
87
|
+
// What the user has
|
|
88
|
+
const { data: billing } = await baas.payments.me()
|
|
89
|
+
// { mode: 'test', customer_id: 'cus_...', subscriptions: [{ id, status: 'active', price_key: 'pro_monthly', product_key: 'pro', current_period_end: '2026-12-12T09:00:00.000Z', trial_end: null, cancel_at_period_end: false, created_at, source: 'paid', livemode: false, access_paused: false, gift: null }],
|
|
90
|
+
// purchases: [{ id, product_key: 'ebook', price_key: 'ebook_once', amount: 1900, currency: 'usd', status: 'paid', created_at }],
|
|
91
|
+
// entitlements: ['pro', 'ebook'] }
|
|
92
|
+
// access_paused: true → no access although status says 'active' (an open dispute with "Remove access right away", whose
|
|
93
|
+
// payments are paused too; or a lost dispute / fraud refund until Stripe's cancellation arrives). Use entitlements / hasAccess.
|
|
94
|
+
|
|
95
|
+
const { data: isPro } = await baas.payments.hasAccess('pro') // true | false; false when signed out
|
|
96
|
+
const { data: info } = await baas.payments.checkAccess('pro') // { access, source: 'subscription' | 'purchase' | 'gift' | null }
|
|
97
|
+
|
|
98
|
+
// Paid download (product with a file)
|
|
99
|
+
const { data: file, error: dlError } = await baas.payments.download('ebook') // data: { url, expiresIn } or error not_purchased (403)
|
|
100
|
+
if (file) location.href = file.url
|
|
101
|
+
```
|
|
102
|
+
|
|
103
|
+
Outside a browser (React Native, server), `checkout()` and `portal()` return `{ url }` without redirecting; open it yourself (`WebBrowser.openBrowserAsync(data.url)` in Expo).
|
|
104
|
+
|
|
105
|
+
Mobile apps returning to the app: pass app links as `successUrl` / `cancelUrl` / `returnUrl` (`com.example.mynotes://checkout/done`; Swift `successURL:`, Kotlin `successUrl =`). They must be allowed in Dashboard → Settings → General → Your app’s addresses (`com.example.mynotes://**`), else `400 redirect_not_allowed`. Stripe only takes `https://`, so the server gives Stripe `${API}/payments/v1/return?ref=<ref>&to=<app link>` (success adds `&session_id={CHECKOUT_SESSION_ID}`); that page opens the app link (with `?session_id=cs_...`) and shows a "Return to the app" button when the in-app browser blocks it. In the app: close the browser sheet when the link arrives, then re-check `hasAccess`. `POST /payments/v1/intent` also takes `return_url` and answers with the (wrapped) `return_url` to give Stripe.js.
|
|
106
|
+
|
|
107
|
+
After checkout, Stripe redirects to `successUrl` before or shortly after usebecky processes the webhook. On the success page, call `await baas.payments.waitForAccess('pro')` (polls `hasAccess()` every 1.5 s for up to 20 s; `{ data: true | false }`) instead of assuming access is instant.
|
|
108
|
+
|
|
109
|
+
```tsx
|
|
110
|
+
// src/UpgradeButton.tsx: pricing button
|
|
111
|
+
import { useState } from 'react'
|
|
112
|
+
import { baas } from './lib/usebecky'
|
|
113
|
+
|
|
114
|
+
export function UpgradeButton({ yearly = false }: { yearly?: boolean }) {
|
|
115
|
+
const [error, setError] = useState<string | null>(null)
|
|
116
|
+
|
|
117
|
+
async function upgrade() {
|
|
118
|
+
const user = baas.auth.getSession().data.session?.user
|
|
119
|
+
if (!user) return location.assign('/login?next=/pricing')
|
|
120
|
+
const { error } = await baas.payments.checkout(yearly ? 'pro_yearly' : 'pro_monthly', { successUrl: `${location.origin}/welcome-pro`, cancelUrl: location.href })
|
|
121
|
+
if (error) setError(error.message)
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
return (
|
|
125
|
+
<>
|
|
126
|
+
<button onClick={upgrade}>Upgrade</button>
|
|
127
|
+
{error && <p role="alert">{error}</p>}
|
|
128
|
+
</>
|
|
129
|
+
)
|
|
130
|
+
}
|
|
131
|
+
```
|
|
132
|
+
|
|
133
|
+
## Shops: carts, guests, orders
|
|
134
|
+
|
|
135
|
+
A cart is one checkout of several one-time prices (one currency, 1 to 50 lines, 1 to 100 of each). Every paid one-time checkout becomes an order (`#1001`, `#1002`, …; test and live count separately). Guests (signed out) can buy products **without `features`** (merchandise, tickets, files); a product with features needs a signed-in user (`not_signed_in` names it). A subscription can't be in a cart (`subscription_in_cart`); prices in two currencies can't either (`mixed_currencies`).
|
|
136
|
+
|
|
137
|
+
```ts
|
|
138
|
+
// inside an async function:
|
|
139
|
+
// Works signed out too. Without successUrl the buyer comes back to this page with ?checkout=success&order=<id>&order_token=<token>.
|
|
140
|
+
const { data: started, error: cartError } = await baas.payments.checkout({
|
|
141
|
+
items: [{ price: 'mug', quantity: 2 }, { price: 'stickers' }],
|
|
142
|
+
// successUrl: `${location.origin}/thanks?order={ORDER_ID}&order_token={ORDER_TOKEN}`, // both are filled in
|
|
143
|
+
// coupon: 'SUMMER20', email: 'jane@example.com' (prefilled for guests), metadata: { gift_note: 'Happy birthday!' },
|
|
144
|
+
})
|
|
145
|
+
// started: { url, id, livemode, order: { id, token }, amount (goods after the discount), currency }
|
|
146
|
+
|
|
147
|
+
// Thank-you page: wait until Stripe confirmed the payment (polls every 1.5 s, up to 20 s)
|
|
148
|
+
const q = new URLSearchParams(location.search)
|
|
149
|
+
const orderId = q.get('order')
|
|
150
|
+
if (orderId) {
|
|
151
|
+
const { data: order } = await baas.payments.orders.wait(orderId, q.get('order_token'))
|
|
152
|
+
// order: { id, number: 1001, status: 'paid', email, name, currency, subtotal, discount, shipping, tax, total, amount_refunded,
|
|
153
|
+
// items: [{ product_key, price_key, name, variant, sku, shipping, unit_amount, quantity, amount }], metadata, livemode, created_at, paid_at,
|
|
154
|
+
// shipping_address, phone, shipping_rate: { id, name, amount, min_days, max_days },
|
|
155
|
+
// fulfillment: 'unfulfilled' | 'shipped' | 'delivered' | 'fulfilled' (digital only, once paid), carrier, tracking_number, tracking_url, shipped_at, delivered_at,
|
|
156
|
+
// downloads: [{ product_key, name, url, expires_in: 300 }] } (downloads: products with a file, once paid)
|
|
157
|
+
}
|
|
158
|
+
|
|
159
|
+
// A signed-in buyer's orders, newest first (20 per page): pass next_cursor back as cursor
|
|
160
|
+
const { data: page } = await baas.payments.orders.list({ status: 'paid' }) // { orders, next_cursor, prev_cursor }
|
|
161
|
+
```
|
|
162
|
+
|
|
163
|
+
- Order `status`: `pending` (checkout open, or a bank payment on its way), `paid`, `partly_refunded`, `refunded` (a refund or a lost dispute), `canceled` (bank payment failed), `expired` (checkout abandoned; never numbered).
|
|
164
|
+
- The order token is a secret link key: keep it out of logs; anyone with it can read that order. Guests have no other way in.
|
|
165
|
+
- A cart's lines grant access like single purchases (`hasAccess`, `download()`, `billing.has_access`), while the payment is paid; a full refund ends it.
|
|
166
|
+
- A signed-in buyer can buy anything again except a product with features or a file (`already_purchased`).
|
|
167
|
+
- Server (secret key): see [Running orders](#running-orders-server-secret-key). Fulfil from the `order.paid` event, not from the thank-you page.
|
|
168
|
+
- SQL: `billing.orders` and `billing.order_items`; a signed-in user reads only their own rows.
|
|
169
|
+
- Without an order page of its own, the order emails link to usebecky's hosted order page (order, tracking, files; the token is the key). A custom one goes in Payments → Stripe connection → Order emails → More settings, with `{ORDER_ID}` and `{ORDER_TOKEN}`.
|
|
170
|
+
|
|
171
|
+
### Cart on the app's page: quote, createCartPayment, `<PaymentForm items>`
|
|
172
|
+
|
|
173
|
+
Prefer the ready-made `<PaymentForm items={[{ price: 'tshirt_m', quantity: 2 }]} />` (HTML: `<ub-payment-form items='[{"price":"mug","quantity":2}]'>`) from `@usebecky/ui`: lines and totals from `quote()`, Stripe's Address Element (the shop's countries, phone when asked) and the rates (cheapest picked), an email field for guests, the required terms checkbox, sign-in only for products with features. Props: `items`, `successUrl` (`{ORDER_ID}` / `{ORDER_TOKEN}` filled in), `coupon`, `metadata`, `hideSummary`; `onSuccess({ order: { id, token, number, status }, amount, currency })`, `onError`. With Stripe Tax on it shows "Continue to checkout" (hosted checkout) instead.
|
|
174
|
+
|
|
175
|
+
Your own form with Stripe.js:
|
|
176
|
+
|
|
177
|
+
```ts
|
|
178
|
+
// inside an async function:
|
|
179
|
+
// What a cart costs (guests too). Show it as the cart; check stock before paying.
|
|
180
|
+
const { data: quote } = await baas.payments.quote([{ price: 'tshirt_m', quantity: 2 }, { price: 'mug' }], { coupon: 'SUMMER20' })
|
|
181
|
+
// quote: { currency: 'usd', items: [{ price, product_key, name, variant, unit_amount, quantity, amount, shipping, in_stock, available }],
|
|
182
|
+
// subtotal, discount, goods (after the discount; shipping and tax on top), in_stock (every line),
|
|
183
|
+
// shipping: { required, countries: ['US', ...], rates: [{ id, name, amount, min_days, max_days }], collect_phone }, // cheapest first, free shipping applied
|
|
184
|
+
// automatic_tax (true → use checkout({ items })), terms_url (null, or show a required checkbox) }
|
|
185
|
+
|
|
186
|
+
// When the buyer goes to pay: creates the order (stock held 31 min) and a PaymentIntent for the goods + the chosen rate
|
|
187
|
+
const { data: setup, error } = await baas.payments.createCartPayment({
|
|
188
|
+
items: [{ price: 'tshirt_m', quantity: 2 }],
|
|
189
|
+
shipping: { rate: 'rate_standard', name: 'Jane Doe', address: { line1: '1 Main St', city: 'Boston', state: 'MA', postal_code: '02108', country: 'US' } }, // + phone when collect_phone; only for carts that ship
|
|
190
|
+
email: 'jane@example.com', // guests: required (the order emails go there)
|
|
191
|
+
acceptTerms: true, // required when terms_url is set (after the buyer ticked the box)
|
|
192
|
+
// coupon, metadata, locale: 'de' (the order emails' language; default: the browser's)
|
|
193
|
+
})
|
|
194
|
+
if (error) throw error // tax_needs_checkout → checkout({ items }); not_signed_in → sign in; out_of_stock → quote() again
|
|
195
|
+
// setup: { mode: 'payment', client_secret, publishable_key, stripe_account, livemode, currency, amount (goods + shipping), goods, shipping, order: { id, token } }
|
|
196
|
+
// Then: loadStripe(setup.publishable_key, { stripeAccount: setup.stripe_account }) → elements({ clientSecret }) → Payment Element
|
|
197
|
+
// → stripe.confirmPayment({ elements, confirmParams: { return_url }, redirect: 'if_required' }) → orders.wait(setup.order.id, setup.order.token).
|
|
198
|
+
```
|
|
199
|
+
|
|
200
|
+
### Buy links and terms (dashboard, no code)
|
|
201
|
+
|
|
202
|
+
- Buy link: Payments → Products → a price → **Buy link** (optional quantity) → `GET /payments/v1/buy?ref=<project>&price=<key>[&quantity=2]`. Shows the product with "Continue to payment" (holds nothing until that button), which opens hosted checkout as a guest (social posts, newsletters, QR codes). Only products without features; stock, shipping, terms and tax work as in checkout. After paying: the shop's default success URL, else the hosted order page.
|
|
203
|
+
- Terms: Payments → Stripe connection → More settings → **Your shop's terms**. Hosted checkout asks buyers to accept them; the embedded cart form shows a required checkbox and sends `acceptTerms: true` (else `terms_not_accepted`). The developer should add the same URL in Stripe (Settings → Public details).
|
|
204
|
+
|
|
205
|
+
### Physical products, variants, stock
|
|
206
|
+
|
|
207
|
+
Set up by the developer in the dashboard (Payments → Stripe connection → Shipping: countries, rates, free shipping from an order value, phone; Payments → Products: "Ships to the buyer", variant name / SKU / stock per price). App code doesn't change: a cart with a product that has `shipping: true` makes Stripe ask for the address and offer the rates.
|
|
208
|
+
|
|
209
|
+
```ts
|
|
210
|
+
// inside an async function:
|
|
211
|
+
const { data: catalog } = await baas.payments.products()
|
|
212
|
+
// product.shipping: true → shipped. Each price may be a variant: { key: 'tshirt_m', name: 'M / Black', amount: 2500, in_stock: true, stock_left: 3 }
|
|
213
|
+
// stock_left is only set when few are left (null otherwise); in_stock: false = sold out → disable the button.
|
|
214
|
+
const shirt = catalog?.find((p) => p.key === 'tshirt')
|
|
215
|
+
const buyable = (shirt?.prices ?? []).filter((x) => x.in_stock !== false)
|
|
216
|
+
const { error: soldOut } = await baas.payments.checkout({ items: [{ price: buyable[0]?.key ?? 'tshirt_m', quantity: 2 }] })
|
|
217
|
+
if (soldOut?.code === 'out_of_stock') alert(soldOut.message) // 'Only 1 of "T-shirt – M / Black" left.'
|
|
218
|
+
```
|
|
219
|
+
|
|
220
|
+
- Items are held for 31 minutes when a checkout or `createCartPayment()` starts and come back if it isn't paid; the last item can't be sold twice.
|
|
221
|
+
- The paid order has `shipping_address`, `phone`, `shipping_rate`, `shipping` (amount) and `tax`; lines have `variant`, `sku`, `shipping`.
|
|
222
|
+
- `shipping_not_set_up` (409): the shop has no countries or no rate in the cart's currency (developer fixes it in the dashboard). `shipping_needs_checkout` (409): the single-price form (`createPayment`) can't ask for an address; use `checkout({ items })`, `createCartPayment()` or `<PaymentForm items>`.
|
|
223
|
+
- Stripe Tax for orders is a dashboard switch (Tax and stock); the price stays as set, tax is added on Stripe's page. The embedded cart form can't add tax: `createCartPayment()` answers `tax_needs_checkout` (and `quote().automatic_tax` is `true`), so use `checkout({ items })`.
|
|
224
|
+
- usebecky's fee (Free plan) is a percent of the goods after the discount, never of shipping or tax.
|
|
225
|
+
|
|
226
|
+
### Running orders (server, secret key)
|
|
227
|
+
|
|
228
|
+
Dashboard: Payments → Orders (search `#1042` / email / name, "To ship", Export CSV, bulk "Mark as shipped"); an order's page: ship with carrier and tracking, delivered, refund some lines or all (optionally back in stock), cancel, team note, resend emails. Order emails (confirmation, shipped, refund, "New order" to the team) are switched in Payments → Stripe connection → Order emails; test orders only email the team.
|
|
229
|
+
|
|
230
|
+
```ts
|
|
231
|
+
// fulfil.ts: a Node script, server only (secret key)
|
|
232
|
+
import { baas } from 'usebecky/server'
|
|
233
|
+
|
|
234
|
+
const { data: page } = await baas.payments.listOrders({ status: 'paid', limit: 50 }) // + userId, mode: 'test' | 'live', cursor: page.next_cursor
|
|
235
|
+
for (const order of page?.orders ?? []) {
|
|
236
|
+
if (order.fulfillment !== 'unfulfilled') continue // 'fulfilled' = digital only, nothing to ship
|
|
237
|
+
// order.shipping_address, order.phone, order.shipping_rate, order.items[].sku, order.user_id (null for guests), order.stripe_payment_intent_id
|
|
238
|
+
const { error } = await baas.payments.markShipped(order.id, { carrier: 'UPS', trackingNumber: '1Z999AA10123456784', trackingUrl: 'https://www.ups.com/track?tracknum=1Z999AA10123456784' })
|
|
239
|
+
if (error) console.error(order.number, error.code) // order_not_paid, nothing_to_ship
|
|
240
|
+
}
|
|
241
|
+
await baas.payments.markDelivered('ORDER_ID')
|
|
242
|
+
await baas.payments.updateOrder('ORDER_ID', { note: 'Gift wrap' }) // team note (null removes it); never shown to the buyer
|
|
243
|
+
await baas.payments.updateOrder('ORDER_ID', { fulfillment: 'unfulfilled' }) // undo a mistake (no email)
|
|
244
|
+
const { data: one } = await baas.payments.getOrder('ORDER_ID') // + user_id, promotion_code, stripe_* ids
|
|
245
|
+
```
|
|
246
|
+
|
|
247
|
+
- `markShipped(id, { carrier, trackingNumber, trackingUrl, notify })` = `updateOrder(id, { fulfillment: 'shipped', ... })`: sends `order.shipped` and the buyer's "on its way" email once (`notify: false` skips the email). Pass `trackingUrl` for the email's "Track your order" button: the API doesn't build it from the carrier (the dashboard does).
|
|
248
|
+
- `markDelivered(id)` sends `order.delivered` once. Only paid orders ship (`order_not_paid`); orders with only digital products are `fulfilled` when paid (`nothing_to_ship`).
|
|
249
|
+
- Refunds and cancels are dashboard-only (owners and admins). Refunds made in Stripe's own dashboard update the order but don't restock.
|
|
250
|
+
|
|
251
|
+
### Shop pitfalls
|
|
252
|
+
|
|
253
|
+
- One currency per cart, 1 to 50 lines, 1 to 100 of each; no subscriptions in a cart.
|
|
254
|
+
- Products with `features` need a signed-in buyer; guest carts hold only products without features. Don't add features to merchandise.
|
|
255
|
+
- Stripe Tax on → embedded cart payments refuse (`tax_needs_checkout`): use hosted `checkout({ items })` (`<PaymentForm items>` switches by itself).
|
|
256
|
+
- Stock is held 31 minutes per started checkout or cart payment; don't call `createCartPayment()` on page load (it creates an order and holds stock), only once the buyer has the address and rate and goes to pay. `quote()` holds nothing.
|
|
257
|
+
- `stock_left` in `products()` is set only when few are left (null otherwise); show "Sold out" for `in_stock === false`. In a cart, `quote().items[].in_stock` says whether that quantity is available right now.
|
|
258
|
+
- Never trust the client for fulfilment: ship from `order.paid` or `listOrders({ status: 'paid' })`.
|
|
259
|
+
|
|
260
|
+
## Embedded payment form (Stripe Elements)
|
|
261
|
+
|
|
262
|
+
The customer pays inside the app's page. Prefer the ready-made `<PaymentForm price="pro_monthly" />` component when the project uses the usebecky UI components; otherwise build it with Stripe.js (`npm install @stripe/stripe-js`). Same products, prices, fee, access checks and events as checkout.
|
|
263
|
+
|
|
264
|
+
```ts
|
|
265
|
+
// src/payment-form.ts: mounts Stripe's Payment Element into <div id="payment-element"></div>
|
|
266
|
+
import { loadStripe } from '@stripe/stripe-js'
|
|
267
|
+
import { baas } from './lib/usebecky'
|
|
268
|
+
|
|
269
|
+
/** Returns the function your Pay button calls, or null when the form can't be shown. */
|
|
270
|
+
export async function mountPaymentForm(showError: (message: string) => void) {
|
|
271
|
+
const { data: setup, error } = await baas.payments.createPayment('pro_monthly', { quantity: 1, coupon: 'SUMMER20' }) // signed in only; coupon = Stripe promotion code (optional)
|
|
272
|
+
if (error) {
|
|
273
|
+
showError(error.message) // already_subscribed → portal(); already_purchased; invalid_coupon; stripe_elements_not_configured
|
|
274
|
+
return null
|
|
275
|
+
}
|
|
276
|
+
// setup: { mode: 'payment' | 'subscription' | 'setup', client_secret, publishable_key, stripe_account, amount, currency, interval, trial_end, subscription_id, product: { key, name }, price: { key }, livemode }
|
|
277
|
+
|
|
278
|
+
const stripe = await loadStripe(setup.publishable_key, { stripeAccount: setup.stripe_account }) // stripeAccount is required: the payment happens on the developer's account
|
|
279
|
+
if (!stripe) {
|
|
280
|
+
showError('Stripe.js could not load.')
|
|
281
|
+
return null
|
|
282
|
+
}
|
|
283
|
+
const elements = stripe.elements({ clientSecret: setup.client_secret })
|
|
284
|
+
elements.create('payment').mount('#payment-element')
|
|
285
|
+
|
|
286
|
+
return async function pay(): Promise<boolean> {
|
|
287
|
+
const options = { elements, confirmParams: { return_url: location.href }, redirect: 'if_required' as const }
|
|
288
|
+
// 'setup' = free trial: nothing charged now, the card is saved. 'payment' and 'subscription' charge now.
|
|
289
|
+
const { error } = setup.mode === 'setup' ? await stripe.confirmSetup(options) : await stripe.confirmPayment(options)
|
|
290
|
+
if (error) {
|
|
291
|
+
showError(error.message ?? 'The payment failed.') // declined card, failed 3D Secure, ...
|
|
292
|
+
return false
|
|
293
|
+
}
|
|
294
|
+
const { data: ok } = await baas.payments.waitForAccess('pro') // access is granted by Stripe's webhook, not by the client
|
|
295
|
+
return ok === true
|
|
296
|
+
}
|
|
297
|
+
}
|
|
298
|
+
// After a redirect-based payment method, the page reloads with ?redirect_status=succeeded: call waitForAccess() then too.
|
|
299
|
+
```
|
|
300
|
+
|
|
301
|
+
- `baas.payments.stripeConfig()` → `{ publishable_key | null, stripe_account | null, connected, currency_default, mode }` to preload Stripe.js before a price is chosen.
|
|
302
|
+
- `amount` is due now (cents); for `mode: 'setup'` it is the price per period after the trial. 3D Secure runs in a Stripe.js pop-up, no extra code.
|
|
303
|
+
- An opened but unpaid form grants nothing and sends no events (Stripe expires unpaid subscriptions after 23 h). An embedded trial grants access once its card is saved.
|
|
304
|
+
- The same `createPayment()` call within an hour returns the same Stripe payment (no duplicates on reload).
|
|
305
|
+
|
|
306
|
+
## Enforce access (never only in the UI)
|
|
307
|
+
|
|
308
|
+
In SQL (preferred: protects every query, realtime included):
|
|
309
|
+
|
|
310
|
+
```sql
|
|
311
|
+
create policy "Pro users read premium posts" on public.premium_posts for select to authenticated using (billing.has_access('pro'));
|
|
312
|
+
create policy "Free or Pro lessons" on public.lessons for select to anon, authenticated using (not premium or billing.has_access('pro'));
|
|
313
|
+
create policy "Buyers review" on public.reviews for insert to authenticated with check ((select auth.uid()) = user_id and billing.has_purchased(product_key));
|
|
314
|
+
```
|
|
315
|
+
|
|
316
|
+
On the server:
|
|
317
|
+
|
|
318
|
+
```ts
|
|
319
|
+
// server.ts (server only: the secret key stays here)
|
|
320
|
+
import express from 'express'
|
|
321
|
+
import { baas } from 'usebecky/server'
|
|
322
|
+
|
|
323
|
+
const app = express()
|
|
324
|
+
app.post('/api/export', baas.auth.requireUser(), async (req, res) => {
|
|
325
|
+
if (!(await baas.payments.hasAccess(req.user, 'pro'))) return res.status(402).json({ error: { code: 'upgrade_required', message: 'Export needs the Pro plan.' } })
|
|
326
|
+
// ... do the premium work
|
|
327
|
+
res.json({ ok: true })
|
|
328
|
+
})
|
|
329
|
+
|
|
330
|
+
// Checkout from the server: returns the URL instead of redirecting
|
|
331
|
+
app.post('/api/checkout', async (req, res) => {
|
|
332
|
+
const { data, error } = await baas.as(req).payments.checkout('pro_monthly', { successUrl: 'https://example.com/welcome-pro', cancelUrl: 'https://example.com/pricing' })
|
|
333
|
+
if (error) return res.status(error.status).json({ error: { code: error.code, message: error.message } })
|
|
334
|
+
res.json({ url: data.url })
|
|
335
|
+
})
|
|
336
|
+
app.listen(3000)
|
|
337
|
+
```
|
|
338
|
+
|
|
339
|
+
`baas.payments.hasAccess(userOrId, feature)` returns a plain boolean, `false` on any error: right for paywalls, wrong for decisions about money. For those use `checkAccess(userOrId, feature)` → `{ data: { access, source }, error }`: a network error comes back as `error`, never as "doesn't pay".
|
|
340
|
+
|
|
341
|
+
```ts
|
|
342
|
+
// server.ts: delete an account (GDPR Art. 17). End what the user pays for first, then the user.
|
|
343
|
+
import express from 'express'
|
|
344
|
+
import { baas } from 'usebecky/server'
|
|
345
|
+
|
|
346
|
+
const app = express()
|
|
347
|
+
app.delete('/api/account', baas.auth.requireUser(), async (req, res) => {
|
|
348
|
+
const { data: subs, error } = await baas.payments.listSubscriptions(req.user!) // running ones; { status: 'all' } for every one
|
|
349
|
+
if (error) return res.status(503).json({ error: { code: error.code, message: 'Try again in a moment.' } })
|
|
350
|
+
for (const s of subs) {
|
|
351
|
+
if (s.source === 'gift') await baas.payments.revokeGift(s.id)
|
|
352
|
+
else {
|
|
353
|
+
const r = await baas.payments.cancelSubscription(s.id, { atPeriodEnd: false }) // now; default: at the period end
|
|
354
|
+
if (r.error) return res.status(503).json({ error: { code: r.error.code, message: 'Try again in a moment.' } })
|
|
355
|
+
}
|
|
356
|
+
}
|
|
357
|
+
await baas.auth.admin.deleteUser(req.user!.id)
|
|
358
|
+
res.json({ ok: true })
|
|
359
|
+
})
|
|
360
|
+
```
|
|
361
|
+
|
|
362
|
+
- Automated tests (test mode only): `baas.payments.test.subscribe(user, 'pro_monthly', { trial: false })` buys a real Stripe test subscription with the test card, no browser; access at once; `{ card: 'declined' }` fails with `card_declined`; `live_mode` error in live mode. Pair with `baas.auth.admin.createSession(userId)` to sign the test user in.
|
|
363
|
+
- `listSubscriptions(user, { status })`: newest first; `'active'` (default: anything not ended, also ones ending at the period end), `'ended'`, `'all'`. Rows carry `user_id`, `email`, `stripe_subscription_id`, `amount`, `currency`, `interval`, `canceled_at`.
|
|
364
|
+
- `cancelSubscription(id, { atPeriodEnd })`: `id` is the usebecky id or the Stripe id (`sub_…`). Default `atPeriodEnd: true` (no further charge, access until `current_period_end`); `false` ends it and the access now, no refund. Never paid yet (`incomplete`): ends now. Already ended: returned unchanged. `resumeSubscription(id)` takes a scheduled cancellation back; as a user only their own (`403 canceled_by_team` for one made with the secret key or an end date set in Stripe; the secret key can resume any). Both send `subscription.updated` / `subscription.canceled` once. Deleting a user does not cancel their Stripe subscription: cancel first.
|
|
365
|
+
- HTTP: `GET /payments/v1/subscriptions?user_id=&status=`, `POST /payments/v1/subscriptions/:id/cancel` `{at_period_end?}`, `POST /payments/v1/subscriptions/:id/resume`. Secret key: any subscription; a user's access token: only their own (`user_id` ignored).
|
|
366
|
+
|
|
367
|
+
Billing tables (`billing.subscriptions`, `billing.purchases`, `billing.entitlements`) are readable in SQL (users see their own rows) but not through `baas.from()`, which only reaches `public`.
|
|
368
|
+
|
|
369
|
+
## Gifts: give a product for free (server, secret key)
|
|
370
|
+
|
|
371
|
+
```ts
|
|
372
|
+
// gift.ts: a Node script, server only (secret key). Run: node --env-file=.env gift.ts
|
|
373
|
+
import { baas } from 'usebecky/server'
|
|
374
|
+
|
|
375
|
+
const userId = '0b6f3c2e-5d1a-4f7e-8c9b-2a1d3e4f5a6b'
|
|
376
|
+
// user: a user object, a user id, or { email }. product: the product KEY (any product, even one not for sale).
|
|
377
|
+
const { data: gift, error } = await baas.payments.gift(userId, 'pro', { endsAt: '2027-01-31', note: 'Beta tester' }) // endsAt omitted = no end date
|
|
378
|
+
if (error) throw error
|
|
379
|
+
await baas.payments.updateGift(gift.id, { endsAt: null }) // change product / endsAt (null = no end date) / note
|
|
380
|
+
await baas.payments.revokeGift(gift.id) // end now; access stops at once
|
|
381
|
+
const { data: gifts } = await baas.payments.listGifts({ userId }) // running gifts; status: 'active' (default) | 'ended' | 'all'
|
|
382
|
+
```
|
|
383
|
+
|
|
384
|
+
- A gift is a subscription with `source: 'gift'`, `status: 'active'`, `price_key: null`, `gift: { starts_at, ends_at }` (`ends_at: null` = forever; `current_period_end` mirrors it). The SDK's `Gift` adds `active`, `user_id`, `email` and `gift.note`, `gift.gifted_by`, `gift.end_reason`.
|
|
385
|
+
- Every access check counts a running gift: `billing.has_access()`, `billing.has_purchased()` (downloads), the "paid" access level, `hasAccess()`, `checkAccess()` → `{ access: true, source: 'gift' }`. Access stops exactly at `ends_at`.
|
|
386
|
+
- Rules: one running gift per user and product (`gift_exists`); not on top of a paid subscription (`already_subscribed`) or purchase (`already_purchased`) of that product. A gifted user can still buy; the paid subscription then ends the gift.
|
|
387
|
+
- In UI, show gifts from `me()`: `sub.source === 'gift' ? (sub.gift.ends_at ? 'Gift until …' : 'Gift') : …` (not "renews on"). Hide "Manage billing" when `customer_id` is null.
|
|
388
|
+
- No app-code (publishable key) access: only the secret key or the dashboard can give gifts.
|
|
389
|
+
- HTTP: `POST /payments/v1/gifts` `{user_id | email, product, ends_at?, note?}`, `GET /payments/v1/gifts?user_id=&status=`, `GET|PATCH|DELETE /payments/v1/gifts/:id` (secret key).
|
|
390
|
+
|
|
391
|
+
## Billing webhooks to your server
|
|
392
|
+
|
|
393
|
+
usebecky sends signed events to the endpoint registered in Dashboard → Settings → Webhooks (copy its `whsec_...` secret into `USEBECKY_WEBHOOK_SECRET`). Use them to send emails, provision resources or copy plan info into your own tables; do not use them for access checks (use `billing.has_access`).
|
|
394
|
+
|
|
395
|
+
```ts
|
|
396
|
+
// app/api/usebecky-events/route.ts (Next.js; server only: needs USEBECKY_WEBHOOK_SECRET and USEBECKY_SECRET_KEY)
|
|
397
|
+
import { baas } from 'usebecky/server'
|
|
398
|
+
|
|
399
|
+
baas.events.on('subscription.created', async (event) => {
|
|
400
|
+
const { user_id, subscription } = event.data // subscription: { id, status, price_key, product_key, current_period_end, trial_end, cancel_at_period_end, created_at }
|
|
401
|
+
await baas.admin.from('profiles').update({ plan: subscription.product_key }).eq('id', user_id)
|
|
402
|
+
})
|
|
403
|
+
baas.events.on('subscription.canceled', async (event) => { /* event.data.previous_status */ })
|
|
404
|
+
baas.events.on('payment.failed', async (event) => { /* event.data.invoice.hosted_invoice_url */ })
|
|
405
|
+
baas.events.on('purchase.completed', async (event) => { /* event.data.purchase.product_key */ })
|
|
406
|
+
baas.events.on('order.paid', async (event) => { /* event.data.order.items; event.data.user_id is null for guests (use order.email) */ })
|
|
407
|
+
baas.events.on('order.shipped', async (event) => { /* event.data.order.carrier, .tracking_number, .tracking_url */ })
|
|
408
|
+
baas.events.on('subscription.gift_ended', async (event) => { /* event.data.reason: 'expired' | 'revoked' | 'paid' */ })
|
|
409
|
+
|
|
410
|
+
export const POST = baas.events.fetchHandler()
|
|
411
|
+
// Express: app.post('/api/usebecky-events', baas.events.handler()) before app.use(express.json())
|
|
412
|
+
```
|
|
413
|
+
|
|
414
|
+
Example delivery:
|
|
415
|
+
|
|
416
|
+
```json
|
|
417
|
+
{
|
|
418
|
+
"id": "evt_2b7f0c1d9e8a4f6b8c3d2e1f0a9b8c7d",
|
|
419
|
+
"type": "subscription.created",
|
|
420
|
+
"created_at": "2026-11-12T09:00:03.412Z",
|
|
421
|
+
"project": "abcdefghijkl",
|
|
422
|
+
"data": {
|
|
423
|
+
"user_id": "0b6f3c2e-5d1a-4f7e-8c9b-2a1d3e4f5a6b",
|
|
424
|
+
"subscription": { "id": "4f5e...", "status": "trialing", "price_key": "pro_monthly", "product_key": "pro", "current_period_end": "2026-11-26T09:00:00.000Z", "trial_end": "2026-11-26T09:00:00.000Z", "cancel_at_period_end": false, "created_at": "2026-11-12T09:00:01.000Z" },
|
|
425
|
+
"previous_status": null
|
|
426
|
+
}
|
|
427
|
+
}
|
|
428
|
+
```
|
|
429
|
+
|
|
430
|
+
| Event | `data` |
|
|
431
|
+
|---|---|
|
|
432
|
+
| `subscription.created` / `.updated` / `.canceled` | `{ user_id, subscription, previous_status }` |
|
|
433
|
+
| `subscription.trial_will_end` | `{ user_id, subscription, previous_status: null, trial_end }` |
|
|
434
|
+
| `purchase.completed` | `{ user_id, purchase: { id, product_key, price_key, amount, currency, status, created_at }, order }` (a cart: `product_key: null`, the lines are in `order.items`) |
|
|
435
|
+
| `purchase.refunded` | `{ user_id, purchase, amount_refunded }` (full refunds only; access is removed) |
|
|
436
|
+
| `order.paid` | `{ user_id \| null, order }` (once per order; `order` adds `user_id`, `purchase_id`, `stripe_*` ids) |
|
|
437
|
+
| `order.refunded` | `{ user_id, order, amount, amount_refunded }` (every refund, partial too; a lost dispute) |
|
|
438
|
+
| `order.canceled` | `{ user_id, order }` (a placed order's bank payment failed, or the team canceled it: a paid one is refunded too) |
|
|
439
|
+
| `order.shipped` | `{ user_id, order }` (marked shipped in the dashboard or with `markShipped()`; `order.fulfillment: 'shipped'`, `carrier`, `tracking_number`, `tracking_url`). Once per order |
|
|
440
|
+
| `order.delivered` | `{ user_id, order }` (marked delivered; `order.fulfillment: 'delivered'`). Once per order |
|
|
441
|
+
| `payment.failed` | `{ user_id, subscription \| null, invoice: { id, amount_due, currency, attempt_count, next_payment_attempt, hosted_invoice_url } }` |
|
|
442
|
+
| `payment.disputed` | `{ user_id, dispute: { id, amount, currency, reason, status, evidence_due_by, livemode, purchase_id, subscription_id }, purchase \| null, subscription \| null, inquiry, escalated, access: 'kept' \| 'removed' }` (the developer answers in their own Stripe Dashboard). Sent again with `inquiry: false, escalated: true` when a bank's inquiry becomes a chargeback (same dispute id) |
|
|
443
|
+
| `payment.dispute_closed` | same + `outcome: 'won' \| 'lost' \| 'inquiry_closed' \| 'prevented'`, `access: 'removed' \| 'restored' \| 'unchanged'` (lost = access ended like a refund) |
|
|
444
|
+
| `payment.fraud_warning` | `{ user_id, warning: { id, fraud_type, amount, currency, livemode }, purchase \| null, subscription \| null, refunded, access }` (refunded automatically unless the project turned that off) |
|
|
445
|
+
| `subscription.gifted` | `{ user_id, subscription (source 'gift'), gift: { active, starts_at, ends_at, note, gifted_by, ended_at, end_reason } }` |
|
|
446
|
+
| `subscription.gift_updated` | same + `previous: { product_key, ends_at, note }` |
|
|
447
|
+
| `subscription.gift_ended` | same + `reason: 'expired' \| 'revoked' \| 'paid'` |
|
|
448
|
+
|
|
449
|
+
Gifts never send `subscription.created` / `.updated` / `.canceled`; `baas.events.on('subscription.*', ...)` receives both kinds.
|
|
450
|
+
|
|
451
|
+
Handlers must be idempotent (deliveries can repeat; dedupe by `event.id`). A throwing handler makes the response 500 and usebecky retries after 10s, 1m, 5m, 30m and 2h.
|
|
452
|
+
|
|
453
|
+
## Errors
|
|
454
|
+
|
|
455
|
+
| Code | Status | Meaning / fix |
|
|
456
|
+
|---|---|---|
|
|
457
|
+
| `not_signed_in` | 401 | `checkout(price)`, `portal`, `download`, `orders.list` need a user; a cart needs one only for products with features (the message names it) |
|
|
458
|
+
| `subscription_in_cart` / `mixed_currencies` / `invalid_items` | 409 / 400 / 400 | A cart holds one-time prices of one currency, 1 to 50 lines |
|
|
459
|
+
| `order_not_found` | 404 | `orders.get()`: unknown id, wrong token, or someone else's order |
|
|
460
|
+
| `out_of_stock` | 409 | A line can't be held: the message names it and how many are left (`details: { price, available }`) |
|
|
461
|
+
| `shipping_not_set_up` / `shipping_needs_checkout` | 409 | No countries or rates for the cart's currency (dashboard) / a shipped product in `createPayment()` |
|
|
462
|
+
| `tax_needs_checkout` | 409 | `createCartPayment()` while Stripe Tax is on: use `checkout({ items })` |
|
|
463
|
+
| `terms_not_accepted` | 400 | The shop has terms: show `quote().terms_url` with a checkbox and send `acceptTerms: true` |
|
|
464
|
+
| `email_required` | 400 | `createCartPayment()` by a guest: send `email` |
|
|
465
|
+
| `shipping_required` / `invalid_shipping` / `invalid_shipping_rate` / `country_not_shipped` / `phone_required` | 400 | `createCartPayment()` for a cart that ships: send `shipping` with a rate id from `quote()`, an address in one of `quote().shipping.countries`, and `phone` when `collect_phone` |
|
|
466
|
+
| `order_not_paid` / `nothing_to_ship` / `invalid_order_update` | 409 / 409 / 400 | `updateOrder()` / `markShipped()`: the order isn't paid / has only digital products / a wrong field |
|
|
467
|
+
| `rate_limited` | 429 | Guests: at most 10 checkouts or cart payments per minute per IP; buy links too |
|
|
468
|
+
| `invalid_metadata` / `invalid_email` | 400 | `checkout({ metadata })`: up to 20 short text values; `email`: an address |
|
|
469
|
+
| `missing_success_url` | 400 | Outside a browser: pass `successUrl` or set a default in the payment settings (browsers default to the current page) |
|
|
470
|
+
| `price_not_found` | 404 | Unknown or inactive price key; the hint lists available keys |
|
|
471
|
+
| `already_subscribed` | 409 | Already has this plan; open `portal()` instead. For `gift()`: the user already pays for it |
|
|
472
|
+
| `already_purchased` | 409 | Already owns the product (one with features or a file); offer `download()` |
|
|
473
|
+
| `no_customer` | 404 | `portal()` before any checkout |
|
|
474
|
+
| `subscription_not_found` | 404 | `cancelSubscription()` / `resumeSubscription()`: unknown id, or (as a user) someone else's subscription |
|
|
475
|
+
| `gift_subscription` | 409 | Cancel on a gift: end gifts with `revokeGift()` (server) |
|
|
476
|
+
| `subscription_ended` | 409 | `resumeSubscription()` after it ended: start a new checkout |
|
|
477
|
+
| `canceled_by_team` | 403 | `resumeSubscription()` as a user on a cancellation the team made: only the secret key can take it back |
|
|
478
|
+
| `missing_user_id` | 400 | `checkAccess` / `listSubscriptions` over HTTP with the secret key: add `?user_id=` |
|
|
479
|
+
| `portal_not_configured` | 409 | Save the customer portal settings in the Stripe Dashboard |
|
|
480
|
+
| `not_purchased` | 403 | `download()` without buying; send to `checkout()` |
|
|
481
|
+
| `no_download` | 404 | Product has no file configured |
|
|
482
|
+
| `stripe_not_connected` | 409 | Developer must connect Stripe in the dashboard (in live mode: the live account, Payments → Go live) |
|
|
483
|
+
| `stripe_not_configured` | 503 | Server has no Stripe platform keys |
|
|
484
|
+
| `price_not_synced` | 409 | Developer: sync products with Stripe in the dashboard |
|
|
485
|
+
| `invalid_url` | 400 | `successUrl` / `cancelUrl` / `returnUrl` must be full `https://` URLs (`http://` locally) or app links |
|
|
486
|
+
| `redirect_not_allowed` | 400 | An app link (`com.example.mynotes://...`) that isn't in Dashboard → Settings → General → Your app’s addresses |
|
|
487
|
+
| `invalid_quantity` | 400 | 1 to 100 |
|
|
488
|
+
| `invalid_coupon` / `coupon_expired` / `coupon_not_applicable` | 400 | `createPayment()` discount code unknown, expired, or not for this price/currency/total |
|
|
489
|
+
| `nothing_to_pay` | 400 | The code makes a one-time purchase free: use `checkout()` |
|
|
490
|
+
| `stripe_elements_not_configured` | 503 | Payment forms are temporarily unavailable; `checkout()` still works |
|
|
491
|
+
| `gift_exists` | 409 | `gift()`: the user already has this product as a gift; `updateGift()` or `revokeGift()` it |
|
|
492
|
+
| `user_not_found` / `product_not_found` | 404 | `gift()`: unknown user (must have an account) or product key |
|
|
493
|
+
| `gift_ended` / `gift_not_found` | 409 / 404 | `updateGift()` on an ended gift / unknown gift id |
|