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