@kerf-js/pay 0.0.0-stage → 0.1.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/LICENSE +16 -0
- package/README.md +756 -2
- package/docs/pay.md +171 -0
- package/package.json +58 -3
- package/plugin.d.mts +5 -0
- package/plugin.mjs +158 -0
- package/square-plugin.d.mts +9 -0
- package/square-plugin.mjs +69 -0
- package/src/checks/config.mjs +24 -0
- package/src/checks.mjs +379 -0
- package/src/drizzle.ts +57 -0
- package/src/index.ts +265 -0
- package/src/payer.ts +71 -0
- package/src/server/catalog.ts +80 -0
- package/src/server/ledger.ts +89 -0
- package/src/server/operations.ts +215 -0
- package/src/server/rails.ts +45 -0
- package/src/server.ts +283 -0
- package/src/setup.mjs +121 -0
- package/src/square.ts +309 -0
- package/src/stripe.ts +397 -0
- package/src/test.ts +323 -0
- package/stripe-plugin.d.mts +10 -0
- package/stripe-plugin.mjs +41 -0
package/README.md
CHANGED
|
@@ -1,3 +1,757 @@
|
|
|
1
|
-
|
|
1
|
+
<p align="center">
|
|
2
|
+
<a href="https://github.com/Ravonus/kerf">
|
|
3
|
+
<img src="https://raw.githubusercontent.com/Ravonus/kerf/main/site/public/logo.svg" width="88" height="88" alt="Kerf">
|
|
4
|
+
</a>
|
|
5
|
+
</p>
|
|
2
6
|
|
|
3
|
-
|
|
7
|
+
<h1 align="center">@kerf-js/pay</h1>
|
|
8
|
+
|
|
9
|
+
<p align="center">
|
|
10
|
+
<strong>Payments for Kerf apps: products, one ledger for every rail, and entitlements you enforce on the server.</strong><br>
|
|
11
|
+
App code names products, never a provider. Stripe is one line in <code>plugins</code>, and a grant only ever comes from a verified event.
|
|
12
|
+
</p>
|
|
13
|
+
|
|
14
|
+
<p align="center">
|
|
15
|
+
<a href="https://www.npmjs.com/package/@kerf-js/pay"><img src="https://img.shields.io/npm/v/@kerf-js/pay?color=145c3c&label=npm" alt="npm version"></a>
|
|
16
|
+
<a href="https://github.com/Ravonus/kerf/blob/main/LICENSE"><img src="https://img.shields.io/badge/license-MIT-145c3c" alt="MIT license"></a>
|
|
17
|
+
<a href="https://github.com/Ravonus/kerf/actions"><img src="https://img.shields.io/github/actions/workflow/status/Ravonus/kerf/quality.yml?branch=main&label=checks" alt="checks"></a>
|
|
18
|
+
</p>
|
|
19
|
+
|
|
20
|
+
<p align="center">
|
|
21
|
+
<a href="#quick-start">Quick start</a> ·
|
|
22
|
+
<a href="https://github.com/Ravonus/kerf/tree/main/docs">Docs</a> ·
|
|
23
|
+
<a href="https://github.com/Ravonus/kerf/tree/main/examples">Examples</a> ·
|
|
24
|
+
<a href="https://github.com/Ravonus/kerf/blob/main/CHANGELOG.md">Changelog</a> ·
|
|
25
|
+
<a href="https://github.com/Ravonus/kerf">GitHub</a>
|
|
26
|
+
</p>
|
|
27
|
+
|
|
28
|
+
> [!IMPORTANT]
|
|
29
|
+
> **Early release (0.1.x).** APIs can change between minor versions. Pin the version and read the
|
|
30
|
+
> [changelog](https://github.com/Ravonus/kerf/blob/main/CHANGELOG.md) before you upgrade.
|
|
31
|
+
|
|
32
|
+
`@kerf-js/pay` sells subscriptions, one-time purchases and consumables from a Kerf app. You define products once, in a
|
|
33
|
+
catalog that is safe to ship to the browser. A checkout opens the payment provider's hosted page. The provider's signed
|
|
34
|
+
webhook is verified on the exact bytes, written to one ledger, and turned into entitlements that `ctx.entitlements` and
|
|
35
|
+
`requires: [...]` check on the server.
|
|
36
|
+
|
|
37
|
+
It is also Kerf's reference plugin. Nothing in `@kerf-js/start` or the CLI names it, so reading
|
|
38
|
+
[`plugin.mjs`](https://github.com/Ravonus/kerf/blob/main/packages/pay/plugin.mjs) next to
|
|
39
|
+
[`kerf docs plugins`](https://github.com/Ravonus/kerf/blob/main/packages/cli/docs/plugins.md) shows how to build your own.
|
|
40
|
+
|
|
41
|
+
## Highlights
|
|
42
|
+
|
|
43
|
+
- **Products, not price ids.** `product()` takes whole minor units with an ISO currency (`{ usd: 999 }`) and rejects floats
|
|
44
|
+
and missing currencies (PAY008). A rail's ids never reach client code (PAY012).
|
|
45
|
+
- **A grant comes only from a verified event.** `checkout()` returns a URL and grants nothing. The rail's webhook at
|
|
46
|
+
`/_kerf/x/pay/<rail>` is the only way a purchase changes.
|
|
47
|
+
- **At-least-once, any order.** Each event is applied by the rail's own clock, and its id is recorded after it applies, so a
|
|
48
|
+
redelivery is a no-op and an old event changes nothing.
|
|
49
|
+
- **Enforced on the server.** `requires: ['pro']` on any `query` or `mutation` answers a typed 403
|
|
50
|
+
(`ENTITLEMENT_REQUIRED`). `await ctx.entitlements.has('pro')` works in any `query`, `mutation` or `load`.
|
|
51
|
+
- **Live by default.** A verified event pokes the `entitlements:<user>` tag, so a page reading entitlements with `.live()`
|
|
52
|
+
updates without a reload.
|
|
53
|
+
- **One rail is one line.** `stripe()` from `@kerf-js/pay/stripe/plugin` provides the `pay.rail` slot. Any plugin that
|
|
54
|
+
implements `PayRail` and passes `payRailSuite` replaces it, and app code stays the same.
|
|
55
|
+
- **A real fake.** `fakePay` from `@kerf-js/pay/test` signs its events and sends them through your own webhook and ledger, with
|
|
56
|
+
renewals, refunds, pauses and disputes on demand. No key, no network.
|
|
57
|
+
- **No Stripe code by default.** The `.`, `./server`, `./drizzle` and `./test` entries reach no Stripe file (a test holds
|
|
58
|
+
that), and no page loads Stripe.js.
|
|
59
|
+
|
|
60
|
+
## Contents
|
|
61
|
+
|
|
62
|
+
- [Install](#install)
|
|
63
|
+
- [Quick start](#quick-start)
|
|
64
|
+
- [Products and prices](#products-and-prices)
|
|
65
|
+
- [The ledger: `definePay`](#the-ledger-definepay)
|
|
66
|
+
- [Checkout, portal and webhooks](#checkout-portal-and-webhooks)
|
|
67
|
+
- [Entitlements](#entitlements)
|
|
68
|
+
- [Stripe](#stripe)
|
|
69
|
+
- [Square](#square)
|
|
70
|
+
- [Sandbox and test mode](#sandbox-and-test-mode)
|
|
71
|
+
- [Storing the ledger](#storing-the-ledger)
|
|
72
|
+
- [Writing another rail](#writing-another-rail)
|
|
73
|
+
- [Testing with `fakePay`](#testing-with-fakepay)
|
|
74
|
+
- [API reference](#api-reference)
|
|
75
|
+
- [Recipes](#recipes)
|
|
76
|
+
- [Limits](#limits)
|
|
77
|
+
- [Troubleshooting](#troubleshooting)
|
|
78
|
+
- [Related packages](#related-packages)
|
|
79
|
+
|
|
80
|
+
## Install
|
|
81
|
+
|
|
82
|
+
```bash
|
|
83
|
+
# npm
|
|
84
|
+
npm install @kerf-js/pay
|
|
85
|
+
|
|
86
|
+
# pnpm
|
|
87
|
+
pnpm add @kerf-js/pay
|
|
88
|
+
|
|
89
|
+
# bun
|
|
90
|
+
bun add @kerf-js/pay
|
|
91
|
+
```
|
|
92
|
+
|
|
93
|
+
Or let the `kerf` CLI install it and add it to `kerf.config.ts` in one step:
|
|
94
|
+
|
|
95
|
+
```bash
|
|
96
|
+
npx kerf add pay
|
|
97
|
+
```
|
|
98
|
+
|
|
99
|
+
`kerf add pay` needs a database and auth in the app, and stops without changes if either is missing. It also adds the
|
|
100
|
+
Stripe rail (`@kerf-js/pay/stripe`) to `plugins`, so `kerf.config.ts` ends up with:
|
|
101
|
+
|
|
102
|
+
```ts
|
|
103
|
+
// kerf.config.ts
|
|
104
|
+
import { defineConfig } from '@kerf-js/core/config'
|
|
105
|
+
import pay from '@kerf-js/pay/plugin'
|
|
106
|
+
import stripe from '@kerf-js/pay/stripe/plugin'
|
|
107
|
+
|
|
108
|
+
export default defineConfig({
|
|
109
|
+
plugins: [pay(), stripe()],
|
|
110
|
+
})
|
|
111
|
+
```
|
|
112
|
+
|
|
113
|
+
`kerf add` writes a default import named after the package. Both plugin modules also have a named export (`{ pay }`,
|
|
114
|
+
`{ stripe }`), which works the same.
|
|
115
|
+
|
|
116
|
+
### What `kerf add pay` writes
|
|
117
|
+
|
|
118
|
+
| File | What it holds |
|
|
119
|
+
| ---------------------- | ---------------------------------------------------------------------------------------------------------------------- |
|
|
120
|
+
| `src/pay/catalog.ts` | A `pro` subscription: `month` at `{ usd: 999 }`, `year` at `{ usd: 7999, trialDays: 7 }`, granting `pro`. Client-safe. |
|
|
121
|
+
| `src/pay.server.ts` | `export default definePay({ catalog, store, urls: { success: '/', cancel: '/' } })` |
|
|
122
|
+
| `src/server/pay.ts` | The `entitlements` query and the `checkout` and `portal` mutations. |
|
|
123
|
+
| `src/db/pay.schema.ts` | The `purchases` and `pay_events` tables, for SQLite, Postgres or MySQL. Drizzle apps only. |
|
|
124
|
+
| `src/env.server.ts` | `STRIPE_SECRET_KEY` and `STRIPE_WEBHOOK_SECRET` added to the `server` block. |
|
|
125
|
+
| `.env`, `.env.example` | `STRIPE_MODE=test`, `STRIPE_SECRET_KEY=sk_test_placeholder`, `STRIPE_WEBHOOK_SECRET=whsec_placeholder` |
|
|
126
|
+
|
|
127
|
+
On Drizzle, `src/pay.server.ts` uses `drizzlePayStore(db, { purchases, payEvents })`; then run `npx kerf db generate` and
|
|
128
|
+
the migration applies on the next request. On another data layer it starts on `memoryPayStore()`, and you write a
|
|
129
|
+
`PayStore` before production (PAY016).
|
|
130
|
+
|
|
131
|
+
### Setup checklist
|
|
132
|
+
|
|
133
|
+
| Need | Where | Notes |
|
|
134
|
+
| ------------------------- | ------------------------------ | -------------------------------------------------------------------------------------------------------------------------------------------- |
|
|
135
|
+
| A database | `kerf add` refuses without one | Holds the ledger. |
|
|
136
|
+
| Auth | `kerf add` refuses without it | A purchase belongs to `ctx.user.id`. |
|
|
137
|
+
| `STRIPE_MODE` | `.env`, server only | `test` until launch: a live key is then refused (PAY032). Set `live` with the live keys. See [Sandbox and test mode](#sandbox-and-test-mode). |
|
|
138
|
+
| `STRIPE_SECRET_KEY` | `.env`, server only | Replace the placeholder with a real test key. The placeholder is refused before anything is sent (PAY003). |
|
|
139
|
+
| `STRIPE_WEBHOOK_SECRET` | `.env`, server only | Without it every webhook is refused (PAY011). |
|
|
140
|
+
| A Stripe webhook endpoint | Stripe dashboard | URL `https://<your-app>/_kerf/x/pay/stripe`. Events: `customer.subscription.*`, `checkout.session.*`, `charge.refunded`, `charge.dispute.*`. |
|
|
141
|
+
|
|
142
|
+
Nothing calls Stripe until a user checks out.
|
|
143
|
+
|
|
144
|
+
## Quick start
|
|
145
|
+
|
|
146
|
+
The catalog names what you sell. It reaches the client, so it holds names and amounts only:
|
|
147
|
+
|
|
148
|
+
```ts
|
|
149
|
+
// src/pay/catalog.ts
|
|
150
|
+
import { product } from '@kerf-js/pay'
|
|
151
|
+
|
|
152
|
+
export const pro = product({
|
|
153
|
+
id: 'pro',
|
|
154
|
+
kind: 'subscription',
|
|
155
|
+
use: 'digital',
|
|
156
|
+
name: 'Pro',
|
|
157
|
+
plans: { month: { usd: 999 }, year: { usd: 7999, trialDays: 7 } },
|
|
158
|
+
grants: ['pro'],
|
|
159
|
+
})
|
|
160
|
+
```
|
|
161
|
+
|
|
162
|
+
The ledger is the default export of `src/pay.server.ts`:
|
|
163
|
+
|
|
164
|
+
```ts
|
|
165
|
+
// src/pay.server.ts
|
|
166
|
+
import { drizzlePayStore } from '@kerf-js/pay/drizzle'
|
|
167
|
+
import { definePay } from '@kerf-js/pay/server'
|
|
168
|
+
import { db } from '#/db/index.server'
|
|
169
|
+
import { payEvents, purchases } from '#/db/schema'
|
|
170
|
+
import * as catalog from './pay/catalog'
|
|
171
|
+
|
|
172
|
+
// Served at /_kerf/x/pay/<rail>, the webhook URL to give your
|
|
173
|
+
// provider.
|
|
174
|
+
export default definePay({
|
|
175
|
+
catalog,
|
|
176
|
+
store: drizzlePayStore(db, { purchases, payEvents }),
|
|
177
|
+
urls: { success: '/', cancel: '/' },
|
|
178
|
+
})
|
|
179
|
+
```
|
|
180
|
+
|
|
181
|
+
Server functions expose it to pages:
|
|
182
|
+
|
|
183
|
+
```ts
|
|
184
|
+
// src/server/pay.ts
|
|
185
|
+
import { entitlementTag } from '@kerf-js/pay'
|
|
186
|
+
import { mutation, query, redirect } from '@kerf-js/start'
|
|
187
|
+
import pay from '../pay.server'
|
|
188
|
+
|
|
189
|
+
export const entitlements = query({
|
|
190
|
+
auth: 'user',
|
|
191
|
+
tags: (_, ctx) => [entitlementTag(ctx.user.id)],
|
|
192
|
+
run: ({ ctx }) => ctx.entitlements.list(),
|
|
193
|
+
})
|
|
194
|
+
|
|
195
|
+
export const checkout = mutation({
|
|
196
|
+
auth: 'user',
|
|
197
|
+
input: pay.input,
|
|
198
|
+
run: async ({ input, ctx }) =>
|
|
199
|
+
redirect(await pay.checkout(ctx, input), 303),
|
|
200
|
+
})
|
|
201
|
+
|
|
202
|
+
export const portal = mutation({
|
|
203
|
+
auth: 'user',
|
|
204
|
+
run: async ({ ctx }) => redirect(await pay.portal(ctx), 303),
|
|
205
|
+
})
|
|
206
|
+
```
|
|
207
|
+
|
|
208
|
+
A page sells and reads, by product name:
|
|
209
|
+
|
|
210
|
+
```tsx
|
|
211
|
+
// src/routes/pricing.tsx
|
|
212
|
+
import { price } from '@kerf-js/pay'
|
|
213
|
+
import { pro } from '#/pay/catalog'
|
|
214
|
+
import { checkout, entitlements, portal } from '#/server/pay'
|
|
215
|
+
|
|
216
|
+
export default function Pricing() {
|
|
217
|
+
const mine = entitlements.live()
|
|
218
|
+
return (
|
|
219
|
+
<section>
|
|
220
|
+
<button
|
|
221
|
+
type="button"
|
|
222
|
+
onClick={() => checkout({ product: 'pro', plan: 'year' })}
|
|
223
|
+
>
|
|
224
|
+
Go Pro · {price(pro, 'year').display}
|
|
225
|
+
</button>
|
|
226
|
+
<button type="button" onClick={() => portal()}>
|
|
227
|
+
Manage
|
|
228
|
+
</button>
|
|
229
|
+
{mine.value?.includes('pro') && <p>You have Pro.</p>}
|
|
230
|
+
</section>
|
|
231
|
+
)
|
|
232
|
+
}
|
|
233
|
+
```
|
|
234
|
+
|
|
235
|
+
And the server enforces it:
|
|
236
|
+
|
|
237
|
+
```ts
|
|
238
|
+
// src/server/report.ts
|
|
239
|
+
import { query } from '@kerf-js/start'
|
|
240
|
+
|
|
241
|
+
export const report = query({
|
|
242
|
+
auth: 'user',
|
|
243
|
+
requires: ['pro'], // a typed 403, ENTITLEMENT_REQUIRED, without it
|
|
244
|
+
run: () => 'the numbers',
|
|
245
|
+
})
|
|
246
|
+
```
|
|
247
|
+
|
|
248
|
+
The buyer clicks, lands on Stripe Checkout, pays, and comes back to `urls.success`. Stripe posts the event to
|
|
249
|
+
`/_kerf/x/pay/stripe`, the ledger records it, and the `.live()` reader on the page shows Pro.
|
|
250
|
+
|
|
251
|
+
## Products and prices
|
|
252
|
+
|
|
253
|
+
`product(def)` checks a definition and returns it frozen. It is the only place products are defined.
|
|
254
|
+
|
|
255
|
+
| Field | Type | Default | What it does |
|
|
256
|
+
| ---------- | ---------------------------------------------- | -------- | ----------------------------------------------------------------------------------------------------------- |
|
|
257
|
+
| `id` | `string` | required | Lowercase letters, digits and dashes (PAY021 otherwise). What `checkout` and `requires` name. |
|
|
258
|
+
| `kind` | `'subscription' \| 'one-time' \| 'consumable'` | required | A subscription renews, a one-time purchase stays, a consumable is used up. |
|
|
259
|
+
| `use` | `'digital' \| 'physical' \| 'service'` | required | What the buyer gets. |
|
|
260
|
+
| `name` | `string` | the `id` | Display name at checkout. |
|
|
261
|
+
| `plans` | `Record<string, Plan>` | none | Subscriptions only, and required for them. Each plan is `Amounts` plus optional `trialDays` and `interval`. |
|
|
262
|
+
| `price` | `Amounts` | none | One-time and consumable products only. |
|
|
263
|
+
| `grants` | `string[]` | `[]` | Entitlements a live purchase gives. |
|
|
264
|
+
| `shipping` | `boolean` | `false` | Collect a shipping address at checkout. |
|
|
265
|
+
|
|
266
|
+
`Amounts` is `Record<currency, number>`: lowercase ISO codes, non-negative whole minor units. `{ usd: 999 }` is $9.99.
|
|
267
|
+
A plan's interval is its name when the name is `day`, `week`, `month` or `year`; any other name needs `interval`.
|
|
268
|
+
|
|
269
|
+
```ts
|
|
270
|
+
import { product } from '@kerf-js/pay'
|
|
271
|
+
|
|
272
|
+
export const team = product({
|
|
273
|
+
id: 'team',
|
|
274
|
+
kind: 'subscription',
|
|
275
|
+
use: 'service',
|
|
276
|
+
plans: { quarterly: { usd: 2500, eur: 2300, interval: 'month' } },
|
|
277
|
+
grants: ['pro', 'team'],
|
|
278
|
+
})
|
|
279
|
+
|
|
280
|
+
export const credits = product({
|
|
281
|
+
id: 'credits',
|
|
282
|
+
kind: 'consumable',
|
|
283
|
+
use: 'digital',
|
|
284
|
+
price: { usd: 500 },
|
|
285
|
+
grants: ['credits'],
|
|
286
|
+
})
|
|
287
|
+
```
|
|
288
|
+
|
|
289
|
+
`price(product, plan?, { currency?, locale? })` returns `{ amount, currency, display, plan?, interval?, trialDays? }`. It
|
|
290
|
+
uses the first currency listed unless you name one, and formats by the currency's own exponent (JPY has none, KWD has
|
|
291
|
+
three) for the reader's locale. Show `price(pro, 'month').display` instead of typing `$9.99` into a page (PAY005).
|
|
292
|
+
|
|
293
|
+
## The ledger: `definePay`
|
|
294
|
+
|
|
295
|
+
`definePay(options)` from `@kerf-js/pay/server` is the app's one ledger. `src/pay.server.ts` default-exports it, and the
|
|
296
|
+
plugin mounts it as a `server.extension` at `/_kerf/x/pay/...`. An app with no `src/pay.server.ts` has no route and no code
|
|
297
|
+
from any of this.
|
|
298
|
+
|
|
299
|
+
| Option | Type | Default | What it does |
|
|
300
|
+
| --------- | ---------------------------------------- | -------------------- | ------------------------------------------------------------------------------------------------------- |
|
|
301
|
+
| `catalog` | `Product[]` or `Record<string, Product>` | required | `import * as catalog from './pay/catalog'` works. |
|
|
302
|
+
| `store` | `PayStore` | required | Where purchases and seen events live. |
|
|
303
|
+
| `urls` | `{ success, cancel, portal? }` | required | Paths or URLs a buyer returns to. Never from the client. The portal returns to `portal`, else `cancel`. |
|
|
304
|
+
| `user` | `(ctx) => string \| null \| undefined` | `ctx.user?.id` | Who a request is. |
|
|
305
|
+
| `rail` | `string` | the only bound rail | Which rail takes payments when several are bound (PAY022 otherwise). |
|
|
306
|
+
| `origin` | `string` | the request's origin | Absolute origin for `urls`, behind a proxy. |
|
|
307
|
+
| `leeway` | `number` (ms) | 3 days | How long past a paid period access lasts, while a late renewal event arrives. |
|
|
308
|
+
| `slot` | `() => Promise<…>` | `kerf:slot/pay.rail` | Where rails come from. Leave it alone outside tests. |
|
|
309
|
+
|
|
310
|
+
What it returns, besides the `server.extension` members Kerf uses:
|
|
311
|
+
|
|
312
|
+
| Member | What it does |
|
|
313
|
+
| ------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
|
|
314
|
+
| `pay.input` | A Standard Schema validator for a checkout mutation's `input`: `{ product, plan?, currency?, quantity? }`, checked against the catalog. `quantity` is a whole number under 1000. |
|
|
315
|
+
| `pay.checkout(ctx, input)` | The hosted checkout URL for this buyer. Grants nothing. |
|
|
316
|
+
| `pay.portal(ctx)` | Where this buyer manages or cancels. |
|
|
317
|
+
| `pay.entitlements(userId)` | `{ has(id), list() }` for any user, as a job or webhook would read it. |
|
|
318
|
+
| `pay.forContext(ctx)` | The same, for a request: what `ctx.entitlements` is. |
|
|
319
|
+
| `pay.purchases(userId)` | The user's `Purchase` rows. |
|
|
320
|
+
| `pay.refund(purchaseId)` | Asks the purchase's rail to refund it. |
|
|
321
|
+
| `pay.webhook(rail, request, report?)` | One verified delivery: `{ response, tags }`. |
|
|
322
|
+
| `pay.ingest(rail, events, report?)` | Apply events that were already verified. Anything else goes through `webhook`. |
|
|
323
|
+
| `pay.use(rail)` / `pay.reset()` | Swap in a rail directly (what `fakePay` does), and go back to the slot. |
|
|
324
|
+
| `pay.catalog` | The products, as a list. |
|
|
325
|
+
|
|
326
|
+
## Checkout, portal and webhooks
|
|
327
|
+
|
|
328
|
+
**Checkout.** `pay.checkout(ctx, input)` needs a signed-in user (PAY010, 401), resolves the line from the catalog, and
|
|
329
|
+
asks the rail for a hosted page. A subscription the user already holds live answers PAY023 (409). The same click within a
|
|
330
|
+
minute reuses one session: the idempotency key is a hash of the user, the line and the minute. Amounts always come from the
|
|
331
|
+
catalog; the client sends names only.
|
|
332
|
+
|
|
333
|
+
**Portal.** `pay.portal(ctx)` finds the user's customer id on the current rail. A user who has bought nothing there gets
|
|
334
|
+
PAY024 (404).
|
|
335
|
+
|
|
336
|
+
**Webhooks.** The rail posts to `/_kerf/x/pay/<rail>`. For each delivery:
|
|
337
|
+
|
|
338
|
+
| Step | Result |
|
|
339
|
+
| ---------------------------------------------------- | -------------------------------------------------------------------------------- |
|
|
340
|
+
| Not a `POST` | 405 |
|
|
341
|
+
| No rail bound under that name | 404 |
|
|
342
|
+
| Body over 1 MiB | 413 |
|
|
343
|
+
| `verify` throws (bad or missing signature, a replay) | 400, and the reason goes to the server log, not the response |
|
|
344
|
+
| `ingest` fails | 500, so the rail delivers it again |
|
|
345
|
+
| Otherwise | `{"received":true}`, and the affected `entitlements:<user>` tags are invalidated |
|
|
346
|
+
|
|
347
|
+
An event applies when it is newer than the purchase's last one by the rail's clock. On a tie, a terminal state wins: a
|
|
348
|
+
refund and a renewal in the same second is a refund. The event id is recorded after the purchase is saved, so a crash in
|
|
349
|
+
between means a redelivery, not a lost event.
|
|
350
|
+
|
|
351
|
+
### Purchase states
|
|
352
|
+
|
|
353
|
+
The same on every rail:
|
|
354
|
+
|
|
355
|
+
| State | Gives access |
|
|
356
|
+
| ---------------------------------------------------------------------- | ---------------------------------- |
|
|
357
|
+
| `active`, `trial`, `grace` | Yes, until `expires` plus `leeway` |
|
|
358
|
+
| `pending`, `billing-retry`, `paused`, `expired`, `refunded`, `revoked` | No |
|
|
359
|
+
|
|
360
|
+
## Entitlements
|
|
361
|
+
|
|
362
|
+
Entitlements are the union of `grants` over a user's live purchases. On the server, in any `query`, `mutation` or `load`:
|
|
363
|
+
|
|
364
|
+
```ts
|
|
365
|
+
import { redirect } from '@kerf-js/start'
|
|
366
|
+
|
|
367
|
+
// Await it: a promise is truthy, so without `await` everyone passes
|
|
368
|
+
// (PAY015).
|
|
369
|
+
if (!(await ctx.entitlements.has('pro'))) redirect('/pricing')
|
|
370
|
+
```
|
|
371
|
+
|
|
372
|
+
| Way | Where | What happens without the entitlement |
|
|
373
|
+
| -------------------------------- | --------------------------- | ----------------------------------------------------------- |
|
|
374
|
+
| `requires: ['pro']` | any `query` or `mutation` | A 403 with code `ENTITLEMENT_REQUIRED` |
|
|
375
|
+
| `await ctx.entitlements.has(id)` | `query`, `mutation`, `load` | Whatever you do: redirect, hide, refuse |
|
|
376
|
+
| `await ctx.entitlements.list()` | same | The sorted list |
|
|
377
|
+
| `entitlementTag(userId)` | a query's `tags` | The tag a verified event invalidates: `entitlements:<user>` |
|
|
378
|
+
|
|
379
|
+
What the client shows is decoration; a check only on the client is PAY013. A query with `cache: { life }` needs
|
|
380
|
+
`scope: 'user'` to read entitlements.
|
|
381
|
+
|
|
382
|
+
## Stripe
|
|
383
|
+
|
|
384
|
+
`stripe(options?)` from `@kerf-js/pay/stripe/plugin` provides the `pay.rail` slot under the key `stripe`. It uses Stripe
|
|
385
|
+
Checkout and the billing portal over Stripe's REST API, server side only, and verifies webhooks itself with WebCrypto
|
|
386
|
+
HMAC-SHA256 on `<t>.<raw body>`, accepting any of several `v1` signatures while a secret rolls.
|
|
387
|
+
|
|
388
|
+
| Option | Type | Default | What it does |
|
|
389
|
+
| ------------------- | ------------------------ | ------------------------ | -------------------------------------------------------------------------------------------------------------------------- |
|
|
390
|
+
| `prices` | `Record<string, string>` | none | Stripe Price ids by `<product>.<plan>` or `<product>`. Without an entry the amount comes from the catalog as `price_data`. |
|
|
391
|
+
| `api` | `string` | `https://api.stripe.com` | The API origin; point it at a local mock. |
|
|
392
|
+
| `apiVersion` | `string` | `2025-09-30.clover` | Pinned, so an account's default version can't reshape the calls. |
|
|
393
|
+
| `tolerance` | `number` (s) | `300` | How old a signed delivery may be before it is refused as a replay. |
|
|
394
|
+
| `shippingCountries` | `string[]` | `['US', 'CA']` | Where a `shipping` product delivers. |
|
|
395
|
+
| `mode` | `'test' \| 'live'` | `STRIPE_MODE`, else the key | What the keys must be; one from the other mode is PAY032. See [Sandbox and test mode](#sandbox-and-test-mode). |
|
|
396
|
+
|
|
397
|
+
Keys come from the server environment, `STRIPE_SECRET_KEY` and `STRIPE_WEBHOOK_SECRET`. Don't pass a key as an option:
|
|
398
|
+
plugin options are written into `.kerf/slots/`, a generated file (PAY003).
|
|
399
|
+
|
|
400
|
+
```ts
|
|
401
|
+
// kerf.config.ts
|
|
402
|
+
import { defineConfig } from '@kerf-js/core/config'
|
|
403
|
+
import pay from '@kerf-js/pay/plugin'
|
|
404
|
+
import stripe from '@kerf-js/pay/stripe/plugin'
|
|
405
|
+
|
|
406
|
+
export default defineConfig({
|
|
407
|
+
plugins: [
|
|
408
|
+
pay(),
|
|
409
|
+
stripe({
|
|
410
|
+
prices: { 'pro.month': 'price_…', 'pro.year': 'price_…' },
|
|
411
|
+
}),
|
|
412
|
+
],
|
|
413
|
+
})
|
|
414
|
+
```
|
|
415
|
+
|
|
416
|
+
How Stripe events map to the ledger:
|
|
417
|
+
|
|
418
|
+
| Stripe event | Ledger effect |
|
|
419
|
+
| --------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
|
|
420
|
+
| `customer.subscription.*` | `active`, `trialing` → `trial`, `past_due` → `grace`, `unpaid` → `billing-retry`, `paused`, `canceled` and `incomplete_expired` → `expired`, `incomplete` → `pending`; `expires` from the period end |
|
|
421
|
+
| `checkout.session.completed`, `…async_payment_succeeded`, `…async_payment_failed` | One-time payments only: `active`, `pending` while unpaid, or `expired` on failure |
|
|
422
|
+
| `charge.refunded` | `refunded`, for a full refund only; a partial refund keeps what was bought |
|
|
423
|
+
| `charge.dispute.created` / `.closed` | `revoked`, then `active` again if the dispute is won |
|
|
424
|
+
|
|
425
|
+
Who bought what travels in metadata (`kerf_user`, `kerf_product`, `kerf_plan`) on the session, the subscription and the
|
|
426
|
+
payment intent. `pay.refund()` refunds one-time payments (`pi_…`); a subscription is cancelled in the portal.
|
|
427
|
+
|
|
428
|
+
## Square
|
|
429
|
+
|
|
430
|
+
`square(options?)` from `@kerf-js/pay/square/plugin` provides `pay.rail` under the key `square`: Square payment links for
|
|
431
|
+
one-time payments (`pay.order` and one-time products), so web orders land in the same Square account as the shop's card
|
|
432
|
+
readers. Subscriptions and `portal` are PAY022 on it; sell those with Stripe.
|
|
433
|
+
|
|
434
|
+
| Option | Type | Default | What it does |
|
|
435
|
+
| ------------- | ---------------------------- | ---------------------------------------------- | --------------------------------------------------------------- |
|
|
436
|
+
| `environment` | `'sandbox' \| 'production'` | `SQUARE_ENVIRONMENT` (or `SQUARE_ENV`), else production | Picks the API host. Any other value is PAY032, never a guess. |
|
|
437
|
+
| `api` | `string` | from `environment` | The API origin; point it at a local mock. |
|
|
438
|
+
| `apiVersion` | `string` | `2025-10-16` | Pinned `Square-Version`. |
|
|
439
|
+
|
|
440
|
+
Env, server only: `SQUARE_ACCESS_TOKEN`, `SQUARE_LOCATION_ID` (the shop the payments land in), and for the webhook at
|
|
441
|
+
`/_kerf/x/pay/square` `SQUARE_WEBHOOK_SIGNATURE_KEY` plus `SQUARE_WEBHOOK_URL`, the exact URL given to Square, which it
|
|
442
|
+
signs. Subscribe the webhook to `payment.created` and `payment.updated`. `SQUARE_APPLICATION_ID` is optional and only
|
|
443
|
+
checked against the environment.
|
|
444
|
+
|
|
445
|
+
## Sandbox and test mode
|
|
446
|
+
|
|
447
|
+
Both rails have a sandbox that takes the provider's test cards and never moves money. Build and test against it, then
|
|
448
|
+
switch the environment's variables, not code, to go live. A key from the other mode is refused before anything is sent
|
|
449
|
+
(PAY032), so a live key can't reach a dev server and a test key can't quietly run a shop.
|
|
450
|
+
|
|
451
|
+
**Stripe.** Test mode is the keys: in the dashboard turn on *Test mode* (or open a sandbox) and copy them.
|
|
452
|
+
|
|
453
|
+
```bash
|
|
454
|
+
# .env
|
|
455
|
+
STRIPE_MODE=test # `live` at launch, with sk_live_
|
|
456
|
+
STRIPE_SECRET_KEY=sk_test_… # or a restricted rk_test_ key
|
|
457
|
+
STRIPE_WEBHOOK_SECRET=whsec_… # from `stripe listen`, below
|
|
458
|
+
# STRIPE_PUBLISHABLE_KEY=pk_test_… # only for Stripe.js
|
|
459
|
+
```
|
|
460
|
+
|
|
461
|
+
`STRIPE_WEBHOOK_SECRET` is the one `stripe listen` prints locally, or the endpoint's signing secret in the dashboard once
|
|
462
|
+
deployed. `STRIPE_PUBLISHABLE_KEY` is only checked to be the same mode as the secret key; nothing here sends it.
|
|
463
|
+
|
|
464
|
+
Locally, forward webhooks with the Stripe CLI and use the `whsec_` it prints:
|
|
465
|
+
|
|
466
|
+
```bash
|
|
467
|
+
stripe listen \
|
|
468
|
+
--forward-to localhost:5173/_kerf/x/pay/stripe
|
|
469
|
+
```
|
|
470
|
+
|
|
471
|
+
Pay on the hosted Checkout page with `4242 4242 4242 4242`, any future expiry, any CVC (`4000 0000 0000 9995` declines,
|
|
472
|
+
`4000 0025 0000 3155` asks for 3-D Secure). Refund from your admin with `pay.refund(id)`; `charge.refunded` comes back
|
|
473
|
+
through the webhook. `stripe trigger checkout.session.completed` sends a signed event without a browser.
|
|
474
|
+
|
|
475
|
+
**Square.** The sandbox has its own credentials: in the Developer Console open your application, switch to the
|
|
476
|
+
*Sandbox* tab, and take the sandbox access token and application id (`sandbox-sq0idb-…`), and a location of the
|
|
477
|
+
sandbox's test seller account (*Locations* page).
|
|
478
|
+
|
|
479
|
+
```bash
|
|
480
|
+
# .env
|
|
481
|
+
SQUARE_ENVIRONMENT=sandbox # `production` at launch
|
|
482
|
+
SQUARE_ACCESS_TOKEN=… # the Sandbox tab's token
|
|
483
|
+
SQUARE_LOCATION_ID=… # a sandbox location
|
|
484
|
+
SQUARE_APPLICATION_ID=sandbox-sq0idb-… # optional, checked
|
|
485
|
+
SQUARE_WEBHOOK_SIGNATURE_KEY=… # the sandbox subscription's
|
|
486
|
+
SQUARE_WEBHOOK_URL=https://<tunnel>/_kerf/x/pay/square
|
|
487
|
+
```
|
|
488
|
+
|
|
489
|
+
At launch, swap in the production token and location with `SQUARE_ENVIRONMENT=production`; a `sandbox-` application id
|
|
490
|
+
is then refused.
|
|
491
|
+
|
|
492
|
+
`SQUARE_ENVIRONMENT=sandbox` sends every call to `connect.squareupsandbox.com`; unset or `production`, to
|
|
493
|
+
`connect.squareup.com`. A sandbox webhook needs a public URL, so run a tunnel (`cloudflared tunnel --url
|
|
494
|
+
http://localhost:5173`) and give Square that URL plus `/_kerf/x/pay/square`, the same string as `SQUARE_WEBHOOK_URL`.
|
|
495
|
+
Pay on the hosted sandbox page with `4111 1111 1111 1111`, any future expiry, CVV `111`, any ZIP. Square answers a
|
|
496
|
+
token sent to the other environment's host with a bare 401, so that PAY030 names the host it hit.
|
|
497
|
+
|
|
498
|
+
**In the app.** `rail.sandbox` is `true` for a sandbox, and `await pay.sandbox()` reads the bound rail's, for a banner:
|
|
499
|
+
|
|
500
|
+
```ts
|
|
501
|
+
export const testMode = query({ run: () => pay.sandbox() })
|
|
502
|
+
```
|
|
503
|
+
|
|
504
|
+
**Against the real sandboxes.** `test/sandbox.live.test.ts` in this package runs checkout and refund through each rail
|
|
505
|
+
against the provider's sandbox, paying with the published test instruments (`pm_card_visa`, `cnon:card-nonce-ok`). It
|
|
506
|
+
skips without credentials and refuses a live key or a production Square environment:
|
|
507
|
+
|
|
508
|
+
```bash
|
|
509
|
+
export PAY_SANDBOX=1 STRIPE_SECRET_KEY=sk_test_…
|
|
510
|
+
pnpm --filter @kerf-js/pay test sandbox.live
|
|
511
|
+
|
|
512
|
+
export PAY_SANDBOX=1 SQUARE_ENVIRONMENT=sandbox \
|
|
513
|
+
SQUARE_ACCESS_TOKEN=… SQUARE_LOCATION_ID=…
|
|
514
|
+
pnpm --filter @kerf-js/pay test sandbox.live
|
|
515
|
+
```
|
|
516
|
+
|
|
517
|
+
## Storing the ledger
|
|
518
|
+
|
|
519
|
+
A `PayStore` is five methods:
|
|
520
|
+
|
|
521
|
+
| Method | What it does |
|
|
522
|
+
| ------------------- | ------------------------------------- |
|
|
523
|
+
| `seen(eventId)` | Whether an event was already applied. |
|
|
524
|
+
| `mark(eventId, at)` | Record that it was. |
|
|
525
|
+
| `purchase(id)` | One `Purchase` by id, or `null`. |
|
|
526
|
+
| `save(purchase)` | Insert or replace by `id`. |
|
|
527
|
+
| `byUser(user)` | Every purchase of a user. |
|
|
528
|
+
|
|
529
|
+
`drizzlePayStore(db, { purchases, payEvents })` from `@kerf-js/pay/drizzle` implements it on Postgres, SQLite or MySQL, with
|
|
530
|
+
the tables `kerf add pay` writes (times are milliseconds, so they need a 64-bit integer column on Postgres and MySQL). It
|
|
531
|
+
marks both tables as written by the webhook rather than by a server function.
|
|
532
|
+
|
|
533
|
+
`memoryPayStore()` is for dev and tests. A production server refuses to start with it (PAY016).
|
|
534
|
+
|
|
535
|
+
A `Purchase` row is `{ id, rail, user, product, plan, state, at, expires, customer }`, where `id` is `<rail>:<rail's id>`
|
|
536
|
+
and `user`, `product` and `plan` stay `null` until an event names them (a dispute can arrive before its payment).
|
|
537
|
+
|
|
538
|
+
## Writing another rail
|
|
539
|
+
|
|
540
|
+
A rail is a plugin that provides the `pay.rail` slot for the `server` side and implements `PayRail` from `@kerf-js/pay`:
|
|
541
|
+
|
|
542
|
+
| Member | What it does |
|
|
543
|
+
| --------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------- |
|
|
544
|
+
| `id` | The rail's name, and its webhook path: `/_kerf/x/pay/<id>`. |
|
|
545
|
+
| `checkout(request)` | Open a hosted page for a `CheckoutRequest` (user, optional customer, the catalog line, return URLs, an idempotency key). Returns `{ url }`. |
|
|
546
|
+
| `portal({ customer, returnUrl })` | Returns `{ url }`. |
|
|
547
|
+
| `verify({ body, headers })` | Gets the exact bytes received and returns normalised `RailEvent`s, or throws `PayError('PAY011', …)` for anything it can't prove. |
|
|
548
|
+
| `refund({ purchase })` | Optional. |
|
|
549
|
+
|
|
550
|
+
Hold it to the contract with `payRailSuite` from `@kerf-js/pay/test`:
|
|
551
|
+
|
|
552
|
+
```ts
|
|
553
|
+
import { payRailSuite } from '@kerf-js/pay/test'
|
|
554
|
+
import { myRail, signedDelivery } from '../src/rail'
|
|
555
|
+
|
|
556
|
+
test('my rail passes pay.rail@1', async () => {
|
|
557
|
+
const checks = await payRailSuite({
|
|
558
|
+
rail: myRail({ fetch: mockFetch }),
|
|
559
|
+
// A delivery the rail would accept, `age` ms old
|
|
560
|
+
delivery: (age) => signedDelivery(age),
|
|
561
|
+
tolerance: 300_000, // optional: runs the replay check
|
|
562
|
+
})
|
|
563
|
+
expect(checks.filter((c) => !c.ok)).toEqual([])
|
|
564
|
+
})
|
|
565
|
+
```
|
|
566
|
+
|
|
567
|
+
It checks that a genuine delivery verifies, that events have an id, a millisecond time and a purchase, that the same
|
|
568
|
+
delivery gives the same id, that a changed byte and a missing signature are refused, that an old delivery is refused as a
|
|
569
|
+
replay (with `tolerance`), and that `checkout` and `portal` answer absolute URLs. A failed check is P119.
|
|
570
|
+
|
|
571
|
+
Swap rails by replacing `stripe()` in `plugins`. Nothing in app code changes.
|
|
572
|
+
|
|
573
|
+
## Testing with `fakePay`
|
|
574
|
+
|
|
575
|
+
`fakePay` from `@kerf-js/pay/test` is a rail with no key and no network. Its events are signed and go through your own
|
|
576
|
+
webhook and ledger, and it pokes live queries, so a test sees what a user would:
|
|
577
|
+
|
|
578
|
+
```tsx
|
|
579
|
+
import { net, render, screen, user } from '@kerf-js/core/test'
|
|
580
|
+
import { fakePay } from '@kerf-js/pay/test'
|
|
581
|
+
import pay from '#/pay.server'
|
|
582
|
+
|
|
583
|
+
test('checkout grants nothing; the verified event does', async () => {
|
|
584
|
+
// Your `definePay`, or fakePay({ catalog })
|
|
585
|
+
const fake = fakePay(pay)
|
|
586
|
+
net.context({ user: { id: 'u1' } })
|
|
587
|
+
render(Paywall)
|
|
588
|
+
await net.settle()
|
|
589
|
+
await user.click(screen.getByRole('button', { name: /Go Pro/ }))
|
|
590
|
+
await net.settle()
|
|
591
|
+
expect(screen.getByLabelText('plan').textContent).toBe('Free')
|
|
592
|
+
|
|
593
|
+
await fake.complete() // the buyer finishes the hosted page
|
|
594
|
+
expect(screen.getByLabelText('plan').textContent).toBe('Pro')
|
|
595
|
+
|
|
596
|
+
await fake.simulate('refund')
|
|
597
|
+
expect(screen.getByLabelText('plan').textContent).toBe('Free')
|
|
598
|
+
})
|
|
599
|
+
```
|
|
600
|
+
|
|
601
|
+
| Member | What it does |
|
|
602
|
+
| --------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
|
|
603
|
+
| `complete(user?)` | The buyer finishes the newest open checkout, or that user's. Returns the purchase id. |
|
|
604
|
+
| `abandon(user?)` | The buyer closes the page. Nothing is delivered. |
|
|
605
|
+
| `buy(user, product, plan?)` | A whole purchase with no page in the way. |
|
|
606
|
+
| `simulate(what, purchase?)` | `renewal`, `renewal-failed`, `grace-expired`, `recovered`, `cancel`, `pause`, `resume`, `refund`, `revoke`. Defaults to the newest purchase. `renewal` and `renewal-failed` move `clock` to the period's end when it is installed. |
|
|
607
|
+
| `redeliver()` | The last event again. |
|
|
608
|
+
| `deliver(event, { forged? })` | Any event, in any order. `forged: true` signs with the wrong key, so it answers 400. |
|
|
609
|
+
| `sessions`, `deliveries` | Every checkout opened, and every delivery with the status the app answered. |
|
|
610
|
+
| `entitlements(user)`, `purchases(user)` | Read the ledger. |
|
|
611
|
+
| `pay`, `rail` | The ledger in use and the fake rail. |
|
|
612
|
+
|
|
613
|
+
`fakePay` registers the ledger with `net.extension`, which resets it after each test. A live key in a test is PAY031.
|
|
614
|
+
|
|
615
|
+
## API reference
|
|
616
|
+
|
|
617
|
+
| Entry | Side | Exports |
|
|
618
|
+
| ---------------------------- | ----------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
|
|
619
|
+
| `@kerf-js/pay` | client and server | `product`, `price`, `entitlementTag`, `PayError`; types `Product`, `ProductDef`, `ProductKind`, `ProductUse`, `Plan`, `Amounts`, `Interval`, `Price`, `PurchaseState`, `PayRail`, `RailEvent`, `CheckoutRequest`, `CheckoutLine` |
|
|
620
|
+
| `@kerf-js/pay/server` | server | `definePay`, `memoryPayStore`, `extension`; types `Pay`, `PayOptions`, `PayStore`, `Purchase`, `Entitlements`, `CheckoutInput`, `PayContext`, `PayReport` |
|
|
621
|
+
| `@kerf-js/pay/drizzle` | server | `drizzlePayStore` |
|
|
622
|
+
| `@kerf-js/pay/test` | tests | `fakePay`, `payRailSuite`; types `FakePay`, `PayScenario`, `PayRailSuiteOptions`, `Check` |
|
|
623
|
+
| `@kerf-js/pay/plugin` | config | `pay` (default and named): the `server.extension`, the PAY checks, `kerf docs pay` and `kerf add pay` |
|
|
624
|
+
| `@kerf-js/pay/stripe` | server | `stripeRail`, `stripeKeyMode`; type `StripeOptions` |
|
|
625
|
+
| `@kerf-js/pay/stripe/plugin` | config | `stripe` (default and named): the `pay.rail` provider |
|
|
626
|
+
| `@kerf-js/pay/square` | server | `squareRail`, `squareSandbox`; type `SquareOptions` |
|
|
627
|
+
| `@kerf-js/pay/square/plugin` | config | `square` (default and named): the `pay.rail` provider |
|
|
628
|
+
|
|
629
|
+
Importing `@kerf-js/pay/server` or `@kerf-js/pay/drizzle` from client code is PAY017.
|
|
630
|
+
|
|
631
|
+
<details>
|
|
632
|
+
<summary><code>stripeRail(options)</code>: options the plugin doesn't document</summary>
|
|
633
|
+
|
|
634
|
+
`stripeRail` is what the plugin loads on the server. Besides the plugin options above, it accepts `secretKey` (default
|
|
635
|
+
`process.env.STRIPE_SECRET_KEY`), `publishableKey` (default `process.env.STRIPE_PUBLISHABLE_KEY`, only checked),
|
|
636
|
+
`webhookSecret` (default `process.env.STRIPE_WEBHOOK_SECRET`) and `fetch` (default the
|
|
637
|
+
global one). Use those in tests of the rail itself; in an app, keys stay in the environment.
|
|
638
|
+
|
|
639
|
+
</details>
|
|
640
|
+
|
|
641
|
+
<details>
|
|
642
|
+
<summary><code>PayError</code></summary>
|
|
643
|
+
|
|
644
|
+
`new PayError(code, message, status = 400)`. Every error this package throws has a stable `code`. `error.answer` is
|
|
645
|
+
`{ code, message, status }`, the shape `@kerf-js/start` sends a plugin's error to the client in.
|
|
646
|
+
|
|
647
|
+
</details>
|
|
648
|
+
|
|
649
|
+
## Recipes
|
|
650
|
+
|
|
651
|
+
**Gate a page in `load`.**
|
|
652
|
+
|
|
653
|
+
```ts
|
|
654
|
+
import { redirect } from '@kerf-js/start'
|
|
655
|
+
|
|
656
|
+
export const load = async ({ ctx }) => {
|
|
657
|
+
if (!(await ctx.entitlements.has('pro'))) redirect('/pricing')
|
|
658
|
+
}
|
|
659
|
+
```
|
|
660
|
+
|
|
661
|
+
**Sell a one-time product with shipping.**
|
|
662
|
+
|
|
663
|
+
```ts
|
|
664
|
+
import { product } from '@kerf-js/pay'
|
|
665
|
+
|
|
666
|
+
export const poster = product({
|
|
667
|
+
id: 'poster',
|
|
668
|
+
kind: 'one-time',
|
|
669
|
+
use: 'physical',
|
|
670
|
+
price: { usd: 2500 },
|
|
671
|
+
shipping: true,
|
|
672
|
+
})
|
|
673
|
+
```
|
|
674
|
+
|
|
675
|
+
Then `checkout({ product: 'poster', quantity: 2 })`. Stripe collects an address in `shippingCountries`.
|
|
676
|
+
|
|
677
|
+
**Read entitlements from a job.** Outside a request, use the ledger directly:
|
|
678
|
+
|
|
679
|
+
```ts
|
|
680
|
+
import pay from '#/pay.server'
|
|
681
|
+
|
|
682
|
+
const isPro = await pay.entitlements(userId).has('pro')
|
|
683
|
+
```
|
|
684
|
+
|
|
685
|
+
**Charge in another currency.** `checkout({ product: 'pro', plan: 'month', currency: 'eur' })` uses the plan's `eur`
|
|
686
|
+
amount; `price(pro, 'month', { currency: 'eur' }).display` shows it.
|
|
687
|
+
|
|
688
|
+
## Limits
|
|
689
|
+
|
|
690
|
+
- Stripe is the only rail that ships. Native app-store rails, store policy and `kerf pay sync` aren't built.
|
|
691
|
+
- Delivery is at-least-once and unordered by design; ordering uses the rail's clock, so an event without a newer timestamp
|
|
692
|
+
doesn't change state.
|
|
693
|
+
- A webhook body over 1 MiB is refused (413).
|
|
694
|
+
- `quantity` is a whole number from 1 to 999. A subscription is always quantity 1.
|
|
695
|
+
- Only a full Stripe refund ends access. Only one-time payments refund through `pay.refund()`.
|
|
696
|
+
- An event for a purchase nobody has seen, with no user or product on it, is stored without an owner and grants nothing
|
|
697
|
+
until a later event names them.
|
|
698
|
+
- A purchase for a product no longer in the catalog grants nothing, and the server logs PAY021 as a warning.
|
|
699
|
+
|
|
700
|
+
## Troubleshooting
|
|
701
|
+
|
|
702
|
+
`kerf check` and `kerf build` run the PAY checks. `kerf docs PAY012` prints any code's page.
|
|
703
|
+
|
|
704
|
+
| Code | When | Fix |
|
|
705
|
+
| ------ | ----------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------ |
|
|
706
|
+
| PAY003 | A Stripe key in source, a server secret read in client code, a key in plugin options, or the placeholder key still in `.env` at run time | Move it to the server env; roll any real key that was committed |
|
|
707
|
+
| PAY004 | Paid state written on the client after `checkout()` | Read `entitlements`: a grant arrives from a verified event |
|
|
708
|
+
| PAY005 | A price typed into a page that sells something (warning) | `price(product, plan).display` |
|
|
709
|
+
| PAY008 | A float or currency-less amount in `product()` | Whole minor units: `{ usd: 999 }` |
|
|
710
|
+
| PAY010 | A checkout mutation without `auth: 'user'`, or a checkout with no signed-in user (401) | Add `auth: 'user'` |
|
|
711
|
+
| PAY011 | A webhook handler with no signature check, a `verify` that ignores `headers`, no `STRIPE_WEBHOOK_SECRET`, or a delivery that fails verification (400) | Delete the handler: `/_kerf/x/pay/<rail>` verifies. Set the secret |
|
|
712
|
+
| PAY012 | A rail's price or product id in client code | Name the catalog; map ids in `stripe({ prices })` |
|
|
713
|
+
| PAY013 | An entitlement checked only on the client | `requires: [...]`, or `await ctx.entitlements.has(...)` |
|
|
714
|
+
| PAY014 | The plugin with no `src/pay.server.ts`: no webhook is mounted | Default-export `definePay({ … })` from it |
|
|
715
|
+
| PAY015 | `ctx.entitlements.has()` without `await` | Await it (`kerf fix` does, in an `async` function) |
|
|
716
|
+
| PAY016 | `memoryPayStore()` in `src/pay.server.ts` (warning); a production server refuses to start | `drizzlePayStore` or your own `PayStore` |
|
|
717
|
+
| PAY017 | `@kerf-js/pay/server` or `/drizzle` imported in client code | Import them in a server module |
|
|
718
|
+
| PAY018 | `src/pay.server.ts` with no `pay.rail` provider | `kerf add pay-stripe` |
|
|
719
|
+
| PAY031 | A live key in a test | `fakePay` |
|
|
720
|
+
|
|
721
|
+
At run time:
|
|
722
|
+
|
|
723
|
+
| Code | Status | Means |
|
|
724
|
+
| ---------------------- | --------------- | -------------------------------------------------------------------------------------------------------- |
|
|
725
|
+
| PAY021 | 404 | No such product, plan or currency in the catalog (also thrown by `product()` for a bad definition) |
|
|
726
|
+
| PAY022 | 500 / 501 / 400 | No rail chosen while several are bound, a named rail isn't bound, or the rail can't refund this purchase |
|
|
727
|
+
| PAY023 | 409 | The user already holds this subscription |
|
|
728
|
+
| PAY024 | 404 | Nothing to manage or refund |
|
|
729
|
+
| PAY030 | 502 / 503 | The rail's provider refused the call (503 when it rate-limited) |
|
|
730
|
+
| PAY032 | 500 | The keys and the chosen mode disagree (a live key with `STRIPE_MODE=test`, a sandbox app id in production), or a misspelled mode: nothing was sent |
|
|
731
|
+
| P101 | 500 | `pay.rail` has no provider in `plugins` |
|
|
732
|
+
| `ENTITLEMENT_REQUIRED` | 403 | A `requires` entitlement is missing |
|
|
733
|
+
| `E_PAY` | 500 | Applying a verified delivery failed; the rail will redeliver |
|
|
734
|
+
|
|
735
|
+
## Related packages
|
|
736
|
+
|
|
737
|
+
| Package | What it is |
|
|
738
|
+
| ---------------------------------------------------------------- | ------------------------------------------------------------------------------- |
|
|
739
|
+
| [`@kerf-js/start`](https://www.npmjs.com/package/@kerf-js/start) | Server functions, `ctx`, `server.extension` and live queries that pay builds on |
|
|
740
|
+
| [`@kerf-js/core`](https://www.npmjs.com/package/@kerf-js/core) | The plugin API (`definePlugin`, slots) and the test kit (`net`, `clock`) |
|
|
741
|
+
| [`@kerf-js/db`](https://www.npmjs.com/package/@kerf-js/db) | The database layer `drizzlePayStore` runs on |
|
|
742
|
+
| [`@kerf-js/cli`](https://www.npmjs.com/package/@kerf-js/cli) | `kerf add pay`, `kerf check`, `kerf docs pay` and `kerf docs plugins` |
|
|
743
|
+
|
|
744
|
+
## Contributing
|
|
745
|
+
|
|
746
|
+
See [CONTRIBUTING.md](https://github.com/Ravonus/kerf/blob/main/CONTRIBUTING.md). From the repository root:
|
|
747
|
+
|
|
748
|
+
```bash
|
|
749
|
+
pnpm --filter @kerf-js/pay test
|
|
750
|
+
```
|
|
751
|
+
|
|
752
|
+
The tests run the ledger end to end over `fakePay`, the Stripe rail against a mocked API, the PAY checks, and the
|
|
753
|
+
`drizzlePayStore` on SQLite. None reach a network.
|
|
754
|
+
|
|
755
|
+
## License
|
|
756
|
+
|
|
757
|
+
[MIT](https://github.com/Ravonus/kerf/blob/main/LICENSE)
|