better-auth-streampay 3.0.0 → 3.0.2
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 +67 -650
- package/dist/client.d.cts +3 -3
- package/dist/client.d.ts +3 -3
- package/dist/index.cjs +181 -121
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +2 -2
- package/dist/index.d.ts +2 -2
- package/dist/index.js +181 -121
- package/dist/index.js.map +1 -1
- package/dist/{streampay-Cfl70SR_.d.cts → streampay-uhs67tYl.d.cts} +28 -13
- package/dist/{streampay-Cfl70SR_.d.ts → streampay-uhs67tYl.d.ts} +28 -13
- package/docs/integration.md +716 -0
- package/docs/staging-validation.md +159 -0
- package/docs/subscriptions.md +271 -0
- package/package.json +2 -1
package/README.md
CHANGED
|
@@ -1,135 +1,72 @@
|
|
|
1
1
|
# better-auth-streampay
|
|
2
2
|
|
|
3
|
-
Add StreamPay
|
|
3
|
+
Add StreamPay checkout, billing, and signed webhooks to a Better Auth app. This is a community
|
|
4
|
+
plugin and is not affiliated with Stream.
|
|
4
5
|
|
|
5
|
-
|
|
6
|
+
The plugin supports hosted checkout, consumer records, subscription plans and access checks, a
|
|
7
|
+
consumer billing portal, admin billing actions, and webhook verification and replay.
|
|
6
8
|
|
|
7
|
-
|
|
9
|
+
For advanced checkout, consumer matching, portal, subscription lifecycle, admin, and webhook
|
|
10
|
+
examples, see the [integration guide](docs/integration.md). For subscription columns and upgrade
|
|
11
|
+
migrations, see the [subscription data model](docs/subscriptions.md).
|
|
8
12
|
|
|
9
|
-
|
|
10
|
-
npx skills add Genie-sa/better-auth-streampay
|
|
11
|
-
```
|
|
12
|
-
|
|
13
|
-
Then ask your coding agent to add StreamPay to your Better Auth app.
|
|
14
|
-
|
|
15
|
-
The plugin can:
|
|
13
|
+
## Requirements
|
|
16
14
|
|
|
17
|
-
-
|
|
18
|
-
-
|
|
19
|
-
-
|
|
20
|
-
-
|
|
21
|
-
- expose admin billing actions
|
|
22
|
-
- verify and handle signed webhooks
|
|
15
|
+
- Node.js `>=20.19.0`
|
|
16
|
+
- Better Auth `^1.6.0`
|
|
17
|
+
- Stream SDK `@streamsdk/typescript ^1.1.3`
|
|
18
|
+
- Zod `^3.24.0` or `^4.0.0`
|
|
23
19
|
|
|
24
|
-
|
|
20
|
+
Install the plugin and SDK with your package manager:
|
|
25
21
|
|
|
26
22
|
```bash
|
|
27
23
|
pnpm add better-auth-streampay @streamsdk/typescript
|
|
28
24
|
```
|
|
29
25
|
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
- `better-auth ^1.6.0`
|
|
33
|
-
- `@streamsdk/typescript ^1.1.3`
|
|
34
|
-
- `zod ^3.24.0 || ^4.0.0`
|
|
35
|
-
|
|
36
|
-
## Basic setup
|
|
37
|
-
|
|
38
|
-
Add your StreamPay API key:
|
|
26
|
+
Keep Better Auth and Zod installed in your app. Set `STREAMPAY_API_KEY` on the server. Add
|
|
27
|
+
`STREAMPAY_WEBHOOK_SECRET` when you enable webhook handling.
|
|
39
28
|
|
|
40
|
-
|
|
41
|
-
STREAMPAY_API_KEY=
|
|
42
|
-
STREAMPAY_WEBHOOK_SECRET=
|
|
43
|
-
```
|
|
29
|
+
## Server setup
|
|
44
30
|
|
|
45
|
-
Create one SDK client and
|
|
31
|
+
Create one SDK client and register the plugin with the features your app uses. This example enables
|
|
32
|
+
checkout and signed webhooks.
|
|
46
33
|
|
|
47
34
|
```ts
|
|
48
35
|
import StreamSDK from "@streamsdk/typescript";
|
|
49
36
|
import { betterAuth } from "better-auth";
|
|
50
|
-
import {
|
|
51
|
-
checkout,
|
|
52
|
-
portal,
|
|
53
|
-
streampay,
|
|
54
|
-
subscriptions,
|
|
55
|
-
webhooks,
|
|
56
|
-
} from "better-auth-streampay";
|
|
37
|
+
import { checkout, streampay, webhooks } from "better-auth-streampay";
|
|
57
38
|
|
|
58
|
-
const
|
|
39
|
+
const client = StreamSDK.init(process.env.STREAMPAY_API_KEY!);
|
|
59
40
|
|
|
60
41
|
export const auth = betterAuth({
|
|
61
42
|
plugins: [
|
|
62
43
|
streampay({
|
|
63
|
-
client
|
|
44
|
+
client,
|
|
64
45
|
use: [
|
|
65
|
-
checkout(
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
plans: [
|
|
69
|
-
{
|
|
70
|
-
name: "pro",
|
|
71
|
-
productId: "your-recurring-product-id",
|
|
72
|
-
priceInSmallestUnit: 9900,
|
|
73
|
-
billingInterval: "MONTH",
|
|
74
|
-
limits: { reports: true },
|
|
75
|
-
},
|
|
76
|
-
],
|
|
77
|
-
}),
|
|
78
|
-
webhooks({
|
|
79
|
-
secret: process.env.STREAMPAY_WEBHOOK_SECRET!,
|
|
46
|
+
checkout({
|
|
47
|
+
products: [{ slug: "starter", productId: "your-payment-product-id" }],
|
|
48
|
+
authenticatedUsersOnly: true,
|
|
80
49
|
}),
|
|
50
|
+
webhooks({ secret: process.env.STREAMPAY_WEBHOOK_SECRET! }),
|
|
81
51
|
],
|
|
82
52
|
}),
|
|
83
53
|
],
|
|
84
54
|
});
|
|
85
55
|
```
|
|
86
56
|
|
|
87
|
-
|
|
88
|
-
|
|
89
|
-
## Database
|
|
57
|
+
Register your webhook endpoint in the StreamPay dashboard. With the default Better Auth base path,
|
|
58
|
+
use:
|
|
90
59
|
|
|
91
|
-
|
|
92
|
-
|
|
93
|
-
```bash
|
|
94
|
-
npx auth@latest migrate --config path/to/auth.ts
|
|
95
|
-
```
|
|
96
|
-
|
|
97
|
-
For Drizzle or Prisma:
|
|
98
|
-
|
|
99
|
-
```bash
|
|
100
|
-
npx auth@latest generate --config path/to/auth.ts
|
|
101
|
-
```
|
|
102
|
-
|
|
103
|
-
Review the generated schema, then use your normal migration process. The plugin declares the
|
|
104
|
-
schema but never changes your database at runtime. For an existing subscription table, backfill
|
|
105
|
-
`seats` to `1` in the same migration.
|
|
106
|
-
|
|
107
|
-
Add `subscription.catalogMapped` with a default of `true` before deploying this version.
|
|
108
|
-
Better Auth 1.6's migration generator does not apply static defaults to added columns. Review
|
|
109
|
-
and backfill the column explicitly. For PostgreSQL with the default table name:
|
|
110
|
-
|
|
111
|
-
```sql
|
|
112
|
-
ALTER TABLE subscription ADD COLUMN IF NOT EXISTS "catalogMapped" boolean DEFAULT true;
|
|
113
|
-
ALTER TABLE subscription ALTER COLUMN "catalogMapped" SET DEFAULT true;
|
|
114
|
-
UPDATE subscription SET "catalogMapped" = true WHERE "catalogMapped" IS NULL;
|
|
115
|
-
ALTER TABLE subscription ADD COLUMN IF NOT EXISTS "renewalCallbackEventId" text;
|
|
60
|
+
```text
|
|
61
|
+
https://your-app.com/api/auth/streampay/webhooks
|
|
116
62
|
```
|
|
117
63
|
|
|
118
|
-
|
|
119
|
-
remains nullable for rolling migrations; legacy null values preserve existing access until
|
|
120
|
-
reconciliation provides a catalog decision. Better Auth 1.6.0 is the minimum because 1.5's built-in
|
|
121
|
-
SQL adapter handles null comparisons incorrectly, breaking ungrouped reads and released leases.
|
|
122
|
-
|
|
123
|
-
Reconciliation sets it to `false` when Stream's current products do not match a configured plan;
|
|
124
|
-
billing details remain visible, but features and limits deny access. Dynamic plan factories
|
|
125
|
-
resolve on each resolution.
|
|
126
|
-
|
|
127
|
-
`streampayConsumerId` is unique. Before applying the generated unique index to an existing
|
|
128
|
-
database, resolve any duplicate non-null consumer IDs. Checkout fails closed when a consumer link
|
|
129
|
-
cannot be stored safely.
|
|
64
|
+
Keep API keys and webhook secrets on the server. Do not put them in browser code.
|
|
130
65
|
|
|
131
66
|
## Client setup
|
|
132
67
|
|
|
68
|
+
For React, register the client plugin:
|
|
69
|
+
|
|
133
70
|
```ts
|
|
134
71
|
import { createAuthClient } from "better-auth/react";
|
|
135
72
|
import { streampayClient } from "better-auth-streampay/client";
|
|
@@ -139,583 +76,63 @@ export const authClient = createAuthClient({
|
|
|
139
76
|
});
|
|
140
77
|
```
|
|
141
78
|
|
|
142
|
-
Use the matching Better Auth client for Vue, Svelte, or Solid.
|
|
143
|
-
|
|
144
|
-
## Consumers
|
|
145
|
-
|
|
146
|
-
By default, the plugin creates a StreamPay consumer when the user first needs one. This keeps a
|
|
147
|
-
StreamPay outage from blocking sign-up.
|
|
148
|
-
|
|
149
|
-
To create the consumer during sign-up:
|
|
150
|
-
|
|
151
|
-
```ts
|
|
152
|
-
streampay({
|
|
153
|
-
client: streamPayClient,
|
|
154
|
-
createConsumerOnSignUp: true,
|
|
155
|
-
use: [],
|
|
156
|
-
});
|
|
157
|
-
```
|
|
158
|
-
|
|
159
|
-
To reuse an existing StreamPay consumer after a verified email match:
|
|
160
|
-
|
|
161
|
-
```ts
|
|
162
|
-
streampay({
|
|
163
|
-
client: streamPayClient,
|
|
164
|
-
createConsumerOnSignUp: true,
|
|
165
|
-
claimExistingConsumerBy: ["email"],
|
|
166
|
-
use: [],
|
|
167
|
-
});
|
|
168
|
-
```
|
|
169
|
-
|
|
170
|
-
Only enable reuse when your app verifies the matching email or phone number.
|
|
171
|
-
|
|
172
|
-
## Checkout
|
|
173
|
-
|
|
174
|
-
```ts
|
|
175
|
-
checkout({
|
|
176
|
-
products: [
|
|
177
|
-
{ slug: "starter", productId: "product-id" },
|
|
178
|
-
],
|
|
179
|
-
successUrl: "/billing/success",
|
|
180
|
-
failureUrl: "/billing/failed",
|
|
181
|
-
authenticatedUsersOnly: true,
|
|
182
|
-
});
|
|
183
|
-
```
|
|
184
|
-
|
|
185
|
-
Open checkout:
|
|
186
|
-
|
|
187
|
-
```ts
|
|
188
|
-
const { data } = await authClient.checkout({
|
|
189
|
-
slug: "starter",
|
|
190
|
-
redirect: false,
|
|
191
|
-
});
|
|
192
|
-
|
|
193
|
-
window.location.href = data.url;
|
|
194
|
-
```
|
|
195
|
-
|
|
196
|
-
You can also pass StreamPay product IDs directly with `products`.
|
|
197
|
-
|
|
198
|
-
### Server-authoritative checkout
|
|
199
|
-
|
|
200
|
-
For a store, derive product IDs, quantities, coupons, expiry, and redirect URLs on the server:
|
|
201
|
-
|
|
202
|
-
```ts
|
|
203
|
-
import { APIError } from "better-auth/api";
|
|
204
|
-
|
|
205
|
-
checkout({
|
|
206
|
-
authenticatedUsersOnly: true,
|
|
207
|
-
|
|
208
|
-
resolveCheckout: async ({ user, body }) => {
|
|
209
|
-
const order = await loadAuthorizedOrder(user?.id, body.referenceId);
|
|
210
|
-
if (!order) {
|
|
211
|
-
throw new APIError("FORBIDDEN", {
|
|
212
|
-
code: "ORDER_NOT_AVAILABLE",
|
|
213
|
-
message: "This order is not available for checkout.",
|
|
214
|
-
});
|
|
215
|
-
}
|
|
216
|
-
|
|
217
|
-
return {
|
|
218
|
-
products: [{ productId: order.productId, quantity: order.quantity }],
|
|
219
|
-
successUrl: `https://shop.example.com/orders/${order.id}?checkout=success`,
|
|
220
|
-
failureUrl: `https://shop.example.com/orders/${order.id}?checkout=failed`,
|
|
221
|
-
maxNumberOfPayments: 1,
|
|
222
|
-
validUntil: order.validUntil,
|
|
223
|
-
metadata: { flow: "store" },
|
|
224
|
-
};
|
|
225
|
-
},
|
|
226
|
-
|
|
227
|
-
onCheckoutCreated: async ({ referenceId, paymentLinkId, payload }) => {
|
|
228
|
-
await saveOrderPaymentLink({ referenceId, paymentLinkId, payload });
|
|
229
|
-
},
|
|
230
|
-
});
|
|
231
|
-
```
|
|
232
|
-
|
|
233
|
-
The client then sends only app-owned reference data:
|
|
79
|
+
Use the matching Better Auth client package for Vue, Svelte, or Solid. Open a hosted checkout link
|
|
80
|
+
with:
|
|
234
81
|
|
|
235
82
|
```ts
|
|
236
|
-
await authClient.checkout({
|
|
237
|
-
```
|
|
238
|
-
|
|
239
|
-
Configuring `resolveCheckout` automatically makes product, pricing, coupon, expiry, metadata, and
|
|
240
|
-
redirect URL fields server-only. Requests that include those fields are rejected; without a
|
|
241
|
-
resolver, the existing client-driven checkout behavior is unchanged.
|
|
242
|
-
|
|
243
|
-
Invalid values returned by `resolveCheckout` produce a generic 500 response. Validation details are
|
|
244
|
-
written to the server log without echoing the invalid values to the client.
|
|
245
|
-
|
|
246
|
-
If `onCheckoutCreated` throws, checkout returns an error and the plugin attempts to deactivate the
|
|
247
|
-
new payment link. Deactivation is best effort, so webhook handling should still reconcile unexpected
|
|
248
|
-
links. Relative success and failure URLs resolve against the auth server; use absolute URLs when the
|
|
249
|
-
storefront has a different origin.
|
|
250
|
-
|
|
251
|
-
## Billing portal
|
|
252
|
-
|
|
253
|
-
`portal()` adds signed-in user actions:
|
|
254
|
-
|
|
255
|
-
- `state`
|
|
256
|
-
- `subscriptions`
|
|
257
|
-
- `invoices`
|
|
258
|
-
- `portal.session` when hosted session creation is configured
|
|
259
|
-
|
|
260
|
-
```ts
|
|
261
|
-
const state = await authClient.consumer.state();
|
|
262
|
-
const subscriptions = await authClient.consumer.subscriptions.list();
|
|
263
|
-
const invoices = await authClient.consumer.invoices.list();
|
|
264
|
-
const nextInvoices = await authClient.consumer.invoices.list({ query: { page: 2, size: 10 } });
|
|
265
|
-
```
|
|
266
|
-
|
|
267
|
-
Invoice and subscription lists return Stream's `pagination` alongside `data`. The consumer filter
|
|
268
|
-
always comes from the signed-in account. `page` must be a positive safe integer; `size` is 1–100.
|
|
269
|
-
The plugin translates `size` to Stream's documented `limit` query parameter; SDK 1.1.3's
|
|
270
|
-
`size` parameter is ignored by the current API.
|
|
271
|
-
|
|
272
|
-
To open [Stream's hosted customer portal](https://docs.streampay.sa/customer-portal/), configure a
|
|
273
|
-
server-side session creator. Stream SDK 1.1.3 does not expose this endpoint yet:
|
|
274
|
-
|
|
275
|
-
```ts
|
|
276
|
-
portal({
|
|
277
|
-
createSession: async (input) => {
|
|
278
|
-
const response = await fetch(`${process.env.STREAMPAY_BASE_URL}/api/v2/consumer_portal/sessions`, {
|
|
279
|
-
method: "POST",
|
|
280
|
-
headers: {
|
|
281
|
-
"x-api-key": process.env.STREAMPAY_API_KEY!,
|
|
282
|
-
"content-type": "application/json",
|
|
283
|
-
},
|
|
284
|
-
body: JSON.stringify(input),
|
|
285
|
-
signal: AbortSignal.timeout(15_000),
|
|
286
|
-
});
|
|
287
|
-
if (!response.ok) {
|
|
288
|
-
throw Object.assign(new Error("Portal session creation failed."), { status: response.status });
|
|
289
|
-
}
|
|
290
|
-
return response.json();
|
|
291
|
-
},
|
|
292
|
-
});
|
|
293
|
-
|
|
294
|
-
// Frontend, using streampayClient():
|
|
295
|
-
const { data, error } = await authClient.consumer.portal.session();
|
|
83
|
+
const { data, error } = await authClient.checkout({ slug: "starter", redirect: false });
|
|
296
84
|
if (error) throw new Error(error.message);
|
|
297
85
|
if (data) window.location.assign(data.url);
|
|
298
86
|
```
|
|
299
87
|
|
|
300
|
-
|
|
301
|
-
in the request. Missing consumers or configuration return 404; anonymous sessions are rejected.
|
|
302
|
-
Each request creates a fresh URL, requires HTTPS, and sends `Cache-Control: no-store`. Treat the
|
|
303
|
-
single-use URL as a credential: do not log, persist, or share it. Keep API keys on the server.
|
|
304
|
-
|
|
305
|
-
Enable customer permissions and branding in Stream's dashboard. Product switches require switch
|
|
306
|
-
groups; add-ons require catalog mappings. Stream controls proration and payment confirmation.
|
|
307
|
-
Keep webhook reconciliation enabled so portal changes update local subscription access. This
|
|
308
|
-
initial integration opens the consumer's portal; subscription deep links are not exposed. The
|
|
309
|
-
current OpenAPI omits the guide's `return_url` field, so the plugin does not send it.
|
|
310
|
-
|
|
311
|
-
## Subscriptions
|
|
312
|
-
|
|
313
|
-
```ts
|
|
314
|
-
subscriptions({
|
|
315
|
-
plans: [
|
|
316
|
-
{
|
|
317
|
-
name: "pro-monthly",
|
|
318
|
-
productId: "product-id",
|
|
319
|
-
priceInSmallestUnit: 9900,
|
|
320
|
-
currency: "SAR",
|
|
321
|
-
billingInterval: "MONTH",
|
|
322
|
-
billingIntervalCount: 1,
|
|
323
|
-
trialPeriodDays: 7,
|
|
324
|
-
group: "main",
|
|
325
|
-
seatBilling: {
|
|
326
|
-
default: 3,
|
|
327
|
-
minimum: 1,
|
|
328
|
-
maximum: 100,
|
|
329
|
-
},
|
|
330
|
-
limits: { projects: 50, reports: true },
|
|
331
|
-
},
|
|
332
|
-
],
|
|
333
|
-
|
|
334
|
-
onSubscriptionActivated: async ({ subscription, user }) => {
|
|
335
|
-
// Run app-specific work here.
|
|
336
|
-
},
|
|
337
|
-
});
|
|
338
|
-
```
|
|
339
|
-
|
|
340
|
-
Plan names and product IDs must be unique. Prices use the smallest currency unit. For SAR,
|
|
341
|
-
`9900` means `99.00 SAR`.
|
|
342
|
-
|
|
343
|
-
`priceInSmallestUnit` is the price per seat. `seatBilling` controls billed quantity; `limits`
|
|
344
|
-
controls application access. Set `customerEditable: true` with explicit minimum and maximum bounds
|
|
345
|
-
to let customers change quantity in hosted checkout.
|
|
346
|
-
|
|
347
|
-
The plugin gives one trial per user and plan group by default. Use `isTrialEligible` when your
|
|
348
|
-
app needs a stricter or more flexible rule.
|
|
349
|
-
|
|
350
|
-
### Start checkout
|
|
351
|
-
|
|
352
|
-
```ts
|
|
353
|
-
const { data } = await authClient.subscription.upgrade({
|
|
354
|
-
plan: "pro-monthly",
|
|
355
|
-
seats: 5,
|
|
356
|
-
});
|
|
357
|
-
|
|
358
|
-
window.location.href = data.url;
|
|
359
|
-
```
|
|
360
|
-
|
|
361
|
-
On the success page:
|
|
88
|
+
## Database setup
|
|
362
89
|
|
|
363
|
-
|
|
364
|
-
|
|
365
|
-
query: { subscriptionId: data.subscriptionId },
|
|
366
|
-
});
|
|
367
|
-
```
|
|
368
|
-
|
|
369
|
-
Then refresh the subscription data used by your UI.
|
|
370
|
-
|
|
371
|
-
### Manage a subscription
|
|
372
|
-
|
|
373
|
-
```ts
|
|
374
|
-
await authClient.subscription.changePlan({
|
|
375
|
-
subscriptionId,
|
|
376
|
-
plan: "pro-yearly",
|
|
377
|
-
seats: 8, // optional; defaults to the current quantity
|
|
378
|
-
});
|
|
379
|
-
|
|
380
|
-
await authClient.subscription.updateSeats({
|
|
381
|
-
subscriptionId,
|
|
382
|
-
seats: 12,
|
|
383
|
-
});
|
|
384
|
-
|
|
385
|
-
await authClient.subscription.pendingChange.cancel({ subscriptionId });
|
|
386
|
-
|
|
387
|
-
await authClient.subscription.cancel({
|
|
388
|
-
subscriptionId,
|
|
389
|
-
cancelAtPeriodEnd: true,
|
|
390
|
-
});
|
|
90
|
+
The plugin declares Better Auth schema fields. It does not change your database at runtime. Generate
|
|
91
|
+
and apply a migration before deploying the plugin:
|
|
391
92
|
|
|
392
|
-
|
|
393
|
-
|
|
394
|
-
|
|
395
|
-
StreamPay applies quantity and plan changes at period end. Read the active quantity from `seats`
|
|
396
|
-
and the scheduled quantity from `pendingSeats`. The older
|
|
397
|
-
`authClient.subscription.changePlan.cancel()` action remains available.
|
|
398
|
-
|
|
399
|
-
StreamPay cancels an active subscription at the end of its current period. Trial and inactive
|
|
400
|
-
subscriptions are canceled at once.
|
|
401
|
-
|
|
402
|
-
### Freeze a subscription
|
|
403
|
-
|
|
404
|
-
```ts
|
|
405
|
-
const { data: freeze } = await authClient.subscription.freeze({
|
|
406
|
-
subscriptionId,
|
|
407
|
-
freezeStartDatetime: new Date().toISOString(),
|
|
408
|
-
freezeEndDatetime: null,
|
|
409
|
-
});
|
|
410
|
-
|
|
411
|
-
await authClient.subscription.unfreeze({ subscriptionId });
|
|
412
|
-
|
|
413
|
-
await authClient.subscription.freeze.cancel({
|
|
414
|
-
subscriptionId,
|
|
415
|
-
freezeId: freeze.id!,
|
|
416
|
-
});
|
|
417
|
-
```
|
|
418
|
-
|
|
419
|
-
SDK 1.1.3 cannot request later freeze pages. Configure `listSubscriptionFreezes` on the
|
|
420
|
-
server to enable complete freeze lookup for cancellation and unfreezing:
|
|
421
|
-
|
|
422
|
-
```ts
|
|
423
|
-
import { StreamSDKError } from "@streamsdk/typescript";
|
|
424
|
-
|
|
425
|
-
subscriptions({
|
|
426
|
-
plans,
|
|
427
|
-
listSubscriptionFreezes: async (subscriptionId, { page, limit }) => {
|
|
428
|
-
const url = new URL(
|
|
429
|
-
`/api/v2/subscriptions/${encodeURIComponent(subscriptionId)}/freeze`,
|
|
430
|
-
process.env.STREAMPAY_BASE_URL!,
|
|
431
|
-
);
|
|
432
|
-
url.search = new URLSearchParams({
|
|
433
|
-
page: String(page), limit: String(limit),
|
|
434
|
-
sort_field: "created_at", sort_direction: "asc",
|
|
435
|
-
}).toString();
|
|
436
|
-
const response = await fetch(url, {
|
|
437
|
-
headers: { "x-api-key": process.env.STREAMPAY_API_KEY! },
|
|
438
|
-
signal: AbortSignal.timeout(15000),
|
|
439
|
-
});
|
|
440
|
-
const body = await response.json();
|
|
441
|
-
if (!response.ok) {
|
|
442
|
-
throw new StreamSDKError("Freeze history request failed", {
|
|
443
|
-
status: response.status, body,
|
|
444
|
-
});
|
|
445
|
-
}
|
|
446
|
-
return body;
|
|
447
|
-
},
|
|
448
|
-
});
|
|
449
|
-
```
|
|
450
|
-
|
|
451
|
-
The callback receives only an authorized subscription ID. Return the API's complete page
|
|
452
|
-
response, including pagination. The plugin requests up to 100 entries per page and searches
|
|
453
|
-
up to 100 pages, stopping when it finds the freeze. Invalid or nonadvancing pages return 409;
|
|
454
|
-
API failures propagate without reporting cancellation. Without this callback, the plugin uses
|
|
455
|
-
the SDK's first page and retains the safe latest-freeze fallback or 409 for unresolved history.
|
|
456
|
-
|
|
457
|
-
### Read access and limits
|
|
458
|
-
|
|
459
|
-
```ts
|
|
460
|
-
const current = await authClient.subscription.current({
|
|
461
|
-
query: { group: "main" },
|
|
462
|
-
});
|
|
463
|
-
|
|
464
|
-
const feature = await authClient.subscription.hasFeature({
|
|
465
|
-
query: { feature: "reports", group: "main" },
|
|
466
|
-
});
|
|
467
|
-
|
|
468
|
-
const projects = await authClient.subscription.checkLimit({
|
|
469
|
-
query: { feature: "projects", count: 4, group: "main" },
|
|
470
|
-
});
|
|
471
|
-
```
|
|
472
|
-
|
|
473
|
-
`checkLimit` reads configured entitlements. Use `current.data?.seats` for licensed-member counts.
|
|
474
|
-
|
|
475
|
-
Pass `group` for grouped plans. Leave it out only for a plan without a group.
|
|
476
|
-
|
|
477
|
-
See [the subscription data model](docs/subscriptions.md) for columns, lifecycle, and migration
|
|
478
|
-
details.
|
|
479
|
-
|
|
480
|
-
By default, `active`, `trialing`, `frozen`, and `past_due` subscriptions can use plan
|
|
481
|
-
features. Change this with `accessStatuses`.
|
|
482
|
-
|
|
483
|
-
## Server-side calls
|
|
484
|
-
|
|
485
|
-
Every checkout, portal, subscription, and admin action is also available on `auth.api`. Types
|
|
486
|
-
come from Better Auth.
|
|
487
|
-
|
|
488
|
-
Browser calls follow the route path, such as `authClient.subscription.cancel`. Server calls use
|
|
489
|
-
the endpoint name, such as `auth.api.cancelSubscription`.
|
|
490
|
-
|
|
491
|
-
```ts
|
|
492
|
-
import { headers } from "next/headers";
|
|
493
|
-
|
|
494
|
-
const current = await auth.api.currentSubscription({
|
|
495
|
-
query: { group: "main" },
|
|
496
|
-
headers: await headers(),
|
|
497
|
-
});
|
|
498
|
-
|
|
499
|
-
await auth.api.cancelSubscription({
|
|
500
|
-
body: { subscriptionId, cancelAtPeriodEnd: true },
|
|
501
|
-
headers: await headers(),
|
|
502
|
-
});
|
|
503
|
-
```
|
|
504
|
-
|
|
505
|
-
Pass the request headers so Better Auth can read the session.
|
|
506
|
-
|
|
507
|
-
Webhook delivery is not an `auth.api` action. It uses the raw HTTP body to verify the signature.
|
|
508
|
-
|
|
509
|
-
## Cross-account access
|
|
510
|
-
|
|
511
|
-
User actions use the signed-in user's ID by default.
|
|
512
|
-
|
|
513
|
-
To manage an organization or another app-owned reference, add `authorizeReference`:
|
|
514
|
-
|
|
515
|
-
```ts
|
|
516
|
-
subscriptions({
|
|
517
|
-
plans,
|
|
518
|
-
authorizeReference: async ({ user, referenceId, referenceType, action }) => {
|
|
519
|
-
return canManageBilling(user, referenceId, referenceType, action);
|
|
520
|
-
},
|
|
521
|
-
});
|
|
522
|
-
```
|
|
523
|
-
|
|
524
|
-
Without this callback, cross-account actions return `FORBIDDEN`.
|
|
525
|
-
|
|
526
|
-
## Admin
|
|
527
|
-
|
|
528
|
-
`admin()` adds billing actions for payments, subscriptions, freezes, consumers, invoices,
|
|
529
|
-
products, coupons, payment links, and webhook retries.
|
|
530
|
-
|
|
531
|
-
```ts
|
|
532
|
-
import { admin } from "better-auth-streampay";
|
|
533
|
-
|
|
534
|
-
admin({
|
|
535
|
-
adminRoles: ["admin", "billing"],
|
|
536
|
-
isAdmin: async (user) => user.email.endsWith("@example.com"),
|
|
537
|
-
});
|
|
538
|
-
```
|
|
539
|
-
|
|
540
|
-
Calls use names such as:
|
|
541
|
-
|
|
542
|
-
- `auth.api.adminListPayments`
|
|
543
|
-
- `auth.api.adminGetSubscription`
|
|
544
|
-
- `auth.api.adminCreateProduct`
|
|
545
|
-
- `auth.api.adminReplayWebhookEvent`
|
|
546
|
-
|
|
547
|
-
The IDE shows the body, query, and response types for every action.
|
|
548
|
-
|
|
549
|
-
Make sure your Better Auth route accepts `GET`, `POST`, `PATCH`, `PUT`, and `DELETE`.
|
|
550
|
-
|
|
551
|
-
## Webhooks
|
|
552
|
-
|
|
553
|
-
Register this URL in the StreamPay dashboard:
|
|
554
|
-
|
|
555
|
-
```text
|
|
556
|
-
https://your-app.com/api/auth/streampay/webhooks
|
|
557
|
-
```
|
|
558
|
-
|
|
559
|
-
Then add the handlers you need:
|
|
560
|
-
|
|
561
|
-
```ts
|
|
562
|
-
webhooks({
|
|
563
|
-
secret: process.env.STREAMPAY_WEBHOOK_SECRET!,
|
|
564
|
-
deduplicate: true,
|
|
565
|
-
|
|
566
|
-
onPaymentSucceeded: async (event) => {},
|
|
567
|
-
onPaymentFailed: async (event) => {},
|
|
568
|
-
onSubscriptionActivated: async (event) => {},
|
|
569
|
-
onSubscriptionCanceled: async (event) => {},
|
|
570
|
-
onPayload: async (event) => {},
|
|
571
|
-
});
|
|
572
|
-
```
|
|
573
|
-
|
|
574
|
-
The plugin:
|
|
575
|
-
|
|
576
|
-
- checks the webhook signature
|
|
577
|
-
- rejects old signatures
|
|
578
|
-
- deduplicates subscription sync and lifecycle callbacks
|
|
579
|
-
- retries temporary failures
|
|
580
|
-
- stores failed subscription events for admin replay
|
|
581
|
-
|
|
582
|
-
`deduplicate: true` also persists generic handler deliveries in `streampayWebhookEvent`, including
|
|
583
|
-
unknown event envelopes. Apply the inbox table migration before enabling it. Handler receipts use
|
|
584
|
-
the `handlers:` event ID prefix and support the existing authenticated admin replay endpoint.
|
|
585
|
-
The default is `false` to preserve existing installations that have no inbox table.
|
|
586
|
-
|
|
587
|
-
Verified payloads are persisted when processing is claimed, so an interrupted delivery can be
|
|
588
|
-
recovered after its lease expires. Callbacks must still be idempotent: a crash after an external
|
|
589
|
-
side effect, or failure of a later callback, can repeat earlier work on retry. Inbox deduplication
|
|
590
|
-
does not provide exactly-once execution of external side effects.
|
|
591
|
-
|
|
592
|
-
Typed handlers include `onPaymentPartiallyRefunded` and `onSubscriptionCycleRenewedSuccessfully`.
|
|
593
|
-
Successful renewal events reconcile billing state and share renewal inference with completed
|
|
594
|
-
invoices. The cycle update records its callback owner in `renewalCallbackEventId`; an interrupted
|
|
595
|
-
owner can resume on replay, and competing events cannot take its pending callback. Apply this
|
|
596
|
-
nullable column before deploying. External callback side effects still need idempotency.
|
|
597
|
-
|
|
598
|
-
The StreamPay SDK does not export webhook payload types. This package provides checked event
|
|
599
|
-
types based on StreamPay's documented payloads.
|
|
600
|
-
|
|
601
|
-
To rotate a secret:
|
|
602
|
-
|
|
603
|
-
```ts
|
|
604
|
-
webhooks({
|
|
605
|
-
secret: [
|
|
606
|
-
process.env.STREAMPAY_WEBHOOK_SECRET!,
|
|
607
|
-
process.env.STREAMPAY_WEBHOOK_SECRET_OLD!,
|
|
608
|
-
],
|
|
609
|
-
});
|
|
610
|
-
```
|
|
611
|
-
|
|
612
|
-
Remove the old secret after StreamPay uses the new one.
|
|
613
|
-
|
|
614
|
-
## What owns each job
|
|
615
|
-
|
|
616
|
-
StreamPay owns:
|
|
617
|
-
|
|
618
|
-
- charges
|
|
619
|
-
- invoices
|
|
620
|
-
- subscription state
|
|
621
|
-
- trials
|
|
622
|
-
- renewal attempts
|
|
623
|
-
- cancellation timing
|
|
624
|
-
|
|
625
|
-
The plugin owns:
|
|
626
|
-
|
|
627
|
-
- Better Auth access checks
|
|
628
|
-
- local subscription rows
|
|
629
|
-
- plan features and limits
|
|
630
|
-
- webhook checks and retries
|
|
631
|
-
- checkout recovery
|
|
632
|
-
|
|
633
|
-
Do not edit subscription rows by hand. Let provider responses and webhooks update them.
|
|
634
|
-
|
|
635
|
-
## Errors
|
|
636
|
-
|
|
637
|
-
Errors use stable codes:
|
|
638
|
-
|
|
639
|
-
```ts
|
|
640
|
-
import { $ERROR_CODES } from "better-auth-streampay";
|
|
641
|
-
|
|
642
|
-
if (error.code === $ERROR_CODES.SUBSCRIPTION_ALREADY_ACTIVE.code) {
|
|
643
|
-
// Show the current plan.
|
|
644
|
-
}
|
|
93
|
+
```bash
|
|
94
|
+
npx auth@latest generate --config path/to/auth.ts
|
|
645
95
|
```
|
|
646
96
|
|
|
647
|
-
|
|
97
|
+
For a Better Auth managed database, use `npx auth@latest migrate --config path/to/auth.ts` instead.
|
|
98
|
+
Review generated changes and apply them with your normal database migration process.
|
|
648
99
|
|
|
649
|
-
|
|
650
|
-
|
|
651
|
-
- `
|
|
652
|
-
|
|
653
|
-
|
|
654
|
-
- `SUBSCRIPTION_PLAN_CHANGE_ALREADY_SCHEDULED`
|
|
655
|
-
- `WEBHOOK_REPLAY_IN_PROGRESS`
|
|
100
|
+
For an existing installation, review the [database upgrade instructions](docs/integration.md#database)
|
|
101
|
+
and [subscription migrations](docs/subscriptions.md#migration). Apply new columns and backfill
|
|
102
|
+
existing rows before deploying. Resolve duplicate non-null `streampayConsumerId` values before applying
|
|
103
|
+
the unique index. If you enable generic webhook deduplication, migrate the `streampayWebhookEvent`
|
|
104
|
+
table before setting `deduplicate: true`.
|
|
656
105
|
|
|
657
|
-
##
|
|
658
|
-
|
|
659
|
-
```ts
|
|
660
|
-
import {
|
|
661
|
-
StreamPayAmount,
|
|
662
|
-
checkLimit,
|
|
663
|
-
findConsumerByExternalId,
|
|
664
|
-
formatStreamPayError,
|
|
665
|
-
hasFeature,
|
|
666
|
-
parseStreamPayError,
|
|
667
|
-
verifyWebhook,
|
|
668
|
-
} from "better-auth-streampay";
|
|
669
|
-
```
|
|
670
|
-
|
|
671
|
-
## Local staging demo
|
|
106
|
+
## Billing portal
|
|
672
107
|
|
|
673
|
-
|
|
674
|
-
|
|
675
|
-
|
|
108
|
+
`portal()` adds authenticated consumer state, subscription, and invoice endpoints. Stream SDK 1.1.3
|
|
109
|
+
does not provide hosted portal session creation. To open Stream's hosted portal, configure the
|
|
110
|
+
server-side `createSession` callback with the REST endpoint. The [integration guide](docs/integration.md#billing-portal)
|
|
111
|
+
has a working bridge example and client call. The callback receives the consumer ID resolved from
|
|
112
|
+
the signed-in session.
|
|
676
113
|
|
|
677
|
-
|
|
678
|
-
and the recurring starter product ID, and generate distinct random auth and webhook secrets.
|
|
114
|
+
## Security and access
|
|
679
115
|
|
|
680
|
-
|
|
681
|
-
|
|
682
|
-
|
|
683
|
-
pnpm demo
|
|
684
|
-
# In another terminal:
|
|
685
|
-
cloudflared tunnel --url http://localhost:3100 --no-autoupdate
|
|
686
|
-
pnpm demo:setup https://YOUR-TUNNEL.trycloudflare.com
|
|
687
|
-
```
|
|
116
|
+
Checkout can require an authenticated session with `authenticatedUsersOnly`. Cross-account
|
|
117
|
+
subscription actions require an `authorizeReference` callback. Webhook signatures are checked
|
|
118
|
+
against the configured secret, and signature age is bounded by the webhook tolerance setting.
|
|
688
119
|
|
|
689
|
-
|
|
690
|
-
|
|
691
|
-
|
|
692
|
-
arrive separately through the registered webhook. Creating a subscription directly through the
|
|
693
|
-
Stream API does not include the plugin's checkout correlation metadata automatically.
|
|
120
|
+
Subscription features and limits default to access for `active`, `trialing`, `frozen`, and
|
|
121
|
+
`past_due` states. Set `accessStatuses` to use a different policy. When provider products no longer
|
|
122
|
+
match a configured plan, billing details remain readable while feature and limit checks deny access.
|
|
694
123
|
|
|
695
|
-
|
|
696
|
-
synchronizes its signing secret, including after rotation. When done,
|
|
697
|
-
run `pnpm demo:cleanup` to cancel its trial and remove its webhook, then stop the server and tunnel.
|
|
698
|
-
Cleanup also requests cancellation of a saved paid validation subscription, if present. Stream
|
|
699
|
-
cancels active subscriptions at period end; cleanup retains their state files until cancellation
|
|
700
|
-
completes. It retains the dedicated consumer and local database.
|
|
124
|
+
## Checks and coverage
|
|
701
125
|
|
|
702
|
-
|
|
703
|
-
20.19.0 and 24.21.0, and in an isolated Better Auth 1.6.0 / Zod 3.24 installation. PostgreSQL
|
|
704
|
-
17 tests run against a temporary schema and cover concurrent claims, expired-lease replay,
|
|
705
|
-
stale worker fencing, simultaneous renewal evidence, and migration/backfill of an existing row.
|
|
126
|
+
Run the repository checks with:
|
|
706
127
|
|
|
707
128
|
```bash
|
|
708
|
-
|
|
129
|
+
pnpm check
|
|
709
130
|
```
|
|
710
131
|
|
|
711
|
-
|
|
712
|
-
|
|
713
|
-
|
|
714
|
-
|
|
715
|
-
separate PostgreSQL service. Use a test database, not the application's staging or production database.
|
|
716
|
-
|
|
717
|
-
See [staging validation](docs/staging-validation.md) for the live coverage, regression evidence,
|
|
718
|
-
provider discrepancies and remaining limits.
|
|
132
|
+
`pnpm test` excludes live StreamPay tests. `pnpm test:coverage` measures local source coverage, but
|
|
133
|
+
does not prove behavior against StreamPay. `pnpm test:postgres` uses a dedicated test database for
|
|
134
|
+
database-specific behavior. Live provider coverage, test limits, and validation details are in
|
|
135
|
+
[staging validation](docs/staging-validation.md).
|
|
719
136
|
|
|
720
137
|
## License
|
|
721
138
|
|