better-auth-streampay 1.2.1 → 2.0.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +265 -501
- package/dist/client.cjs +11 -4
- package/dist/client.cjs.map +1 -1
- package/dist/client.d.cts +14 -3
- package/dist/client.d.ts +14 -3
- package/dist/client.js +11 -4
- package/dist/client.js.map +1 -1
- package/dist/index.cjs +1910 -906
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +142 -83
- package/dist/index.d.ts +142 -83
- package/dist/index.js +1905 -908
- package/dist/index.js.map +1 -1
- package/dist/{streampay-DMlTwJUB.d.cts → streampay-CYAHE6Qj.d.cts} +5494 -1903
- package/dist/{streampay-DMlTwJUB.d.ts → streampay-CYAHE6Qj.d.ts} +5494 -1903
- package/package.json +24 -12
package/README.md
CHANGED
|
@@ -1,94 +1,108 @@
|
|
|
1
1
|
# better-auth-streampay
|
|
2
2
|
|
|
3
|
-
|
|
4
|
-
> Plugin bugs → [GitHub issues](https://github.com/Genie-sa/better-auth-streampay/issues). StreamPay bugs → [Stream support](https://streampay.sa).
|
|
3
|
+
Add StreamPay payments and subscriptions to a Better Auth app.
|
|
5
4
|
|
|
6
|
-
|
|
5
|
+
## Agent skill
|
|
7
6
|
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
- Checkout via payment links
|
|
11
|
-
- Customer portal (subscriptions, invoices, consumer state)
|
|
12
|
-
- Subscriptions: upgrade, change plan, cancel, freeze/unfreeze, entitlements
|
|
13
|
-
- Webhook receiver with HMAC-SHA256 verification + replay protection
|
|
14
|
-
- Auto DB sync from webhooks (idempotent)
|
|
15
|
-
- Admin back-office (consumers, products, coupons, refunds, freezes, …)
|
|
16
|
-
- Lazy or eager StreamPay consumer creation, with duplicate-claim modes
|
|
17
|
-
|
|
18
|
-
## Install
|
|
7
|
+
Install the included integration skill:
|
|
19
8
|
|
|
20
9
|
```bash
|
|
21
|
-
|
|
10
|
+
npx skills add Genie-sa/better-auth-streampay
|
|
22
11
|
```
|
|
23
12
|
|
|
24
|
-
|
|
13
|
+
Then ask your coding agent to add StreamPay to your Better Auth app.
|
|
25
14
|
|
|
26
|
-
|
|
15
|
+
The plugin can:
|
|
27
16
|
|
|
28
|
-
|
|
29
|
-
|
|
17
|
+
- create StreamPay consumers
|
|
18
|
+
- open hosted checkout
|
|
19
|
+
- show a billing portal
|
|
20
|
+
- manage subscriptions
|
|
21
|
+
- expose admin billing actions
|
|
22
|
+
- verify and handle signed webhooks
|
|
23
|
+
|
|
24
|
+
## Install
|
|
30
25
|
|
|
31
26
|
```bash
|
|
32
|
-
pnpm add
|
|
27
|
+
pnpm add better-auth-streampay @streamsdk/typescript
|
|
33
28
|
```
|
|
34
29
|
|
|
35
|
-
|
|
30
|
+
Required versions:
|
|
31
|
+
|
|
32
|
+
- `better-auth ^1.5.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:
|
|
36
39
|
|
|
37
40
|
```bash
|
|
38
|
-
STREAMPAY_API_KEY
|
|
39
|
-
STREAMPAY_WEBHOOK_SECRET
|
|
40
|
-
BETTER_AUTH_SECRET=...
|
|
41
|
-
BETTER_AUTH_URL=...
|
|
41
|
+
STREAMPAY_API_KEY=
|
|
42
|
+
STREAMPAY_WEBHOOK_SECRET=
|
|
42
43
|
```
|
|
43
44
|
|
|
44
|
-
|
|
45
|
+
Create one SDK client and pass it to the plugin:
|
|
45
46
|
|
|
46
47
|
```ts
|
|
47
|
-
import { betterAuth } from "better-auth";
|
|
48
48
|
import StreamSDK from "@streamsdk/typescript";
|
|
49
|
+
import { betterAuth } from "better-auth";
|
|
49
50
|
import {
|
|
50
|
-
streampay,
|
|
51
51
|
checkout,
|
|
52
52
|
portal,
|
|
53
|
+
streampay,
|
|
53
54
|
subscriptions,
|
|
54
55
|
webhooks,
|
|
55
|
-
admin,
|
|
56
56
|
} from "better-auth-streampay";
|
|
57
57
|
|
|
58
|
-
const
|
|
58
|
+
const streamPayClient = StreamSDK.init(process.env.STREAMPAY_API_KEY!);
|
|
59
59
|
|
|
60
60
|
export const auth = betterAuth({
|
|
61
61
|
plugins: [
|
|
62
62
|
streampay({
|
|
63
|
-
client,
|
|
63
|
+
client: streamPayClient,
|
|
64
64
|
use: [
|
|
65
|
-
checkout(
|
|
66
|
-
products: [{ productId: "aaaa-bbbb-cccc-dddd", slug: "pro" }],
|
|
67
|
-
successUrl: "/dashboard?checkout=success",
|
|
68
|
-
failureUrl: "/dashboard?checkout=failure",
|
|
69
|
-
authenticatedUsersOnly: true,
|
|
70
|
-
}),
|
|
65
|
+
checkout(),
|
|
71
66
|
portal(),
|
|
72
67
|
subscriptions({
|
|
73
68
|
plans: [
|
|
74
69
|
{
|
|
75
70
|
name: "pro",
|
|
76
|
-
productId: "
|
|
77
|
-
|
|
71
|
+
productId: "your-recurring-product-id",
|
|
72
|
+
priceInSmallestUnit: 9900,
|
|
78
73
|
billingInterval: "MONTH",
|
|
79
74
|
limits: { seats: 10 },
|
|
80
75
|
},
|
|
81
76
|
],
|
|
82
77
|
}),
|
|
83
|
-
webhooks({
|
|
84
|
-
|
|
78
|
+
webhooks({
|
|
79
|
+
secret: process.env.STREAMPAY_WEBHOOK_SECRET!,
|
|
80
|
+
}),
|
|
85
81
|
],
|
|
86
82
|
}),
|
|
87
83
|
],
|
|
88
84
|
});
|
|
89
85
|
```
|
|
90
86
|
|
|
91
|
-
|
|
87
|
+
Only add the parts you use.
|
|
88
|
+
|
|
89
|
+
## Database
|
|
90
|
+
|
|
91
|
+
For a new Better Auth managed database:
|
|
92
|
+
|
|
93
|
+
```bash
|
|
94
|
+
npx @better-auth/cli migrate --config path/to/auth.ts
|
|
95
|
+
```
|
|
96
|
+
|
|
97
|
+
For Drizzle or Prisma:
|
|
98
|
+
|
|
99
|
+
```bash
|
|
100
|
+
npx @better-auth/cli generate --config path/to/auth.ts
|
|
101
|
+
```
|
|
102
|
+
|
|
103
|
+
Then create and run your normal database migration.
|
|
104
|
+
|
|
105
|
+
## Client setup
|
|
92
106
|
|
|
93
107
|
```ts
|
|
94
108
|
import { createAuthClient } from "better-auth/react";
|
|
@@ -99,606 +113,356 @@ export const authClient = createAuthClient({
|
|
|
99
113
|
});
|
|
100
114
|
```
|
|
101
115
|
|
|
102
|
-
|
|
116
|
+
Use the matching Better Auth client for Vue, Svelte, or Solid.
|
|
103
117
|
|
|
104
|
-
|
|
118
|
+
## Consumers
|
|
105
119
|
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
npx drizzle-kit generate && npx drizzle-kit migrate # Drizzle
|
|
109
|
-
npx prisma migrate dev # Prisma
|
|
110
|
-
```
|
|
120
|
+
By default, the plugin creates a StreamPay consumer when the user first needs one. This keeps a
|
|
121
|
+
StreamPay outage from blocking sign-up.
|
|
111
122
|
|
|
112
|
-
|
|
123
|
+
To create the consumer during sign-up:
|
|
113
124
|
|
|
114
125
|
```ts
|
|
115
126
|
streampay({
|
|
116
|
-
client,
|
|
117
|
-
|
|
118
|
-
|
|
119
|
-
// Reclaim duplicates by matching identifier(s).
|
|
120
|
-
claimExistingConsumerBy: ["email", "phone"],
|
|
121
|
-
// Extra fields passed to `client.createConsumer`.
|
|
122
|
-
getConsumerCreateParams: async ({ user }) => ({
|
|
123
|
-
phone_number: "+966501234567",
|
|
124
|
-
preferred_language: "AR",
|
|
125
|
-
communication_methods: ["WHATSAPP", "EMAIL"],
|
|
126
|
-
}),
|
|
127
|
-
use: [/* sub-plugins */],
|
|
127
|
+
client: streamPayClient,
|
|
128
|
+
createConsumerOnSignUp: true,
|
|
129
|
+
use: [],
|
|
128
130
|
});
|
|
129
131
|
```
|
|
130
132
|
|
|
131
|
-
|
|
132
|
-
|
|
133
|
-
- **Lazy** (default) — consumer created on first `/checkout` or subscription mutation.
|
|
134
|
-
- **Eager** (`createConsumerOnSignUp: true`) — consumer created inside the signup transaction. Signup aborts if StreamPay rejects.
|
|
135
|
-
- All consumers get `external_id = user.id`. The id is stored on `user.streampayConsumerId`.
|
|
136
|
-
- On user update → name/email synced to StreamPay. On user delete → consumer deleted. Users with no link are skipped cheap.
|
|
137
|
-
|
|
138
|
-
### Duplicate handling
|
|
133
|
+
To reuse an existing StreamPay consumer after a verified email match:
|
|
139
134
|
|
|
140
|
-
|
|
141
|
-
|
|
142
|
-
|
|
143
|
-
|
|
144
|
-
|
|
145
|
-
|
|
146
|
-
|
|
147
|
-
|
|
135
|
+
```ts
|
|
136
|
+
streampay({
|
|
137
|
+
client: streamPayClient,
|
|
138
|
+
createConsumerOnSignUp: true,
|
|
139
|
+
claimExistingConsumerBy: ["email"],
|
|
140
|
+
use: [],
|
|
141
|
+
});
|
|
142
|
+
```
|
|
148
143
|
|
|
149
|
-
|
|
144
|
+
Only enable reuse when your app verifies the matching email or phone number.
|
|
150
145
|
|
|
151
146
|
## Checkout
|
|
152
147
|
|
|
153
148
|
```ts
|
|
154
149
|
checkout({
|
|
155
|
-
products: [
|
|
156
|
-
|
|
157
|
-
|
|
150
|
+
products: [
|
|
151
|
+
{ slug: "starter", productId: "product-id" },
|
|
152
|
+
],
|
|
153
|
+
successUrl: "/billing/success",
|
|
154
|
+
failureUrl: "/billing/failed",
|
|
158
155
|
authenticatedUsersOnly: true,
|
|
159
|
-
contactInformationType: "EMAIL", // or "PHONE"
|
|
160
|
-
customFields: { source: "website" },
|
|
161
156
|
});
|
|
162
157
|
```
|
|
163
158
|
|
|
164
|
-
|
|
165
|
-
|
|
166
|
-
### Client
|
|
159
|
+
Open checkout:
|
|
167
160
|
|
|
168
161
|
```ts
|
|
169
|
-
|
|
170
|
-
|
|
171
|
-
|
|
172
|
-
|
|
173
|
-
// By UUID
|
|
174
|
-
await authClient.checkout({ products: "aaaa-bbbb-cccc-dddd" });
|
|
175
|
-
|
|
176
|
-
// Multiple products + quantity
|
|
177
|
-
await authClient.checkout({
|
|
178
|
-
products: [{ productId: "aaaa-bbbb-cccc-dddd", quantity: 2 }],
|
|
162
|
+
const { data } = await authClient.checkout({
|
|
163
|
+
slug: "starter",
|
|
164
|
+
redirect: false,
|
|
179
165
|
});
|
|
180
166
|
|
|
181
|
-
|
|
182
|
-
await authClient.checkout({
|
|
183
|
-
slug: "pro",
|
|
184
|
-
referenceId: organizationId,
|
|
185
|
-
metadata: { campaign: "spring-sale" },
|
|
186
|
-
});
|
|
167
|
+
window.location.href = data.url;
|
|
187
168
|
```
|
|
188
169
|
|
|
189
|
-
|
|
190
|
-
|
|
191
|
-
| Field | Type | Notes |
|
|
192
|
-
| --------------------- | ------------------------------------------ | -------------------------------------- |
|
|
193
|
-
| `slug` | `string` | Resolved server-side via `products` |
|
|
194
|
-
| `products` | `string \| string[] \| { productId, quantity? }[]` | UUID(s) |
|
|
195
|
-
| `referenceId` | `string` | Stored in `custom_metadata` |
|
|
196
|
-
| `consumerId` | `string` (uuid) | Override the resolved consumer |
|
|
197
|
-
| `name` | `string` | Payment link display name |
|
|
198
|
-
| `description` | `string` | |
|
|
199
|
-
| `metadata` | `Record<string, string \| number \| boolean>` | |
|
|
200
|
-
| `successUrl` | `string` | Absolute or `/relative` |
|
|
201
|
-
| `failureUrl` | `string` | Absolute or `/relative` |
|
|
202
|
-
| `maxNumberOfPayments` | `number` | |
|
|
203
|
-
| `validUntil` | `string` (ISO 8601) | |
|
|
204
|
-
| `couponIds` | `string[]` (uuid) | |
|
|
205
|
-
| `redirect` | `boolean` | Default `true` |
|
|
206
|
-
|
|
207
|
-
## Portal
|
|
170
|
+
You can also pass StreamPay product IDs directly with `products`.
|
|
208
171
|
|
|
209
|
-
|
|
210
|
-
portal(); // default page size 100 (StreamPay's max)
|
|
211
|
-
portal({ pageSize: 50 });
|
|
212
|
-
```
|
|
172
|
+
## Billing portal
|
|
213
173
|
|
|
214
|
-
|
|
174
|
+
`portal()` adds three signed-in user actions:
|
|
215
175
|
|
|
216
|
-
|
|
217
|
-
|
|
218
|
-
|
|
219
|
-
// user has no StreamPay consumer yet
|
|
220
|
-
}
|
|
176
|
+
- `state`
|
|
177
|
+
- `subscriptions`
|
|
178
|
+
- `invoices`
|
|
221
179
|
|
|
222
|
-
|
|
223
|
-
const
|
|
180
|
+
```ts
|
|
181
|
+
const state = await authClient.consumer.state();
|
|
182
|
+
const subscriptions = await authClient.consumer.subscriptions.list();
|
|
183
|
+
const invoices = await authClient.consumer.invoices.list();
|
|
224
184
|
```
|
|
225
185
|
|
|
226
|
-
When `hasConsumer` is `false`, reads return `200 OK` with `data: []` (or `consumer: null`) instead of 404.
|
|
227
|
-
|
|
228
186
|
## Subscriptions
|
|
229
187
|
|
|
230
188
|
```ts
|
|
231
189
|
subscriptions({
|
|
232
190
|
plans: [
|
|
233
191
|
{
|
|
234
|
-
name: "pro",
|
|
235
|
-
productId: "
|
|
236
|
-
|
|
237
|
-
|
|
238
|
-
|
|
239
|
-
|
|
240
|
-
|
|
192
|
+
name: "pro-monthly",
|
|
193
|
+
productId: "product-id",
|
|
194
|
+
priceInSmallestUnit: 9900,
|
|
195
|
+
currency: "SAR",
|
|
196
|
+
billingInterval: "MONTH",
|
|
197
|
+
billingIntervalCount: 1,
|
|
198
|
+
trialPeriodDays: 7,
|
|
199
|
+
group: "main",
|
|
200
|
+
limits: { seats: 10, reports: true },
|
|
241
201
|
},
|
|
242
202
|
],
|
|
243
|
-
// or a factory: plans: async () => fetchPlansFromCMS(),
|
|
244
203
|
|
|
245
|
-
|
|
246
|
-
|
|
204
|
+
onSubscriptionActivated: async ({ subscription, user }) => {
|
|
205
|
+
// Run app-specific work here.
|
|
247
206
|
},
|
|
207
|
+
});
|
|
208
|
+
```
|
|
209
|
+
|
|
210
|
+
Plan names and product IDs must be unique. Prices use the smallest currency unit. For SAR,
|
|
211
|
+
`9900` means `99.00 SAR`.
|
|
212
|
+
|
|
213
|
+
The plugin gives one trial per user and plan group by default. Use `isTrialEligible` when your
|
|
214
|
+
app needs a stricter or more flexible rule.
|
|
248
215
|
|
|
249
|
-
|
|
250
|
-
|
|
251
|
-
|
|
252
|
-
|
|
253
|
-
|
|
254
|
-
onSubscriptionActivated: async (data) => {},
|
|
255
|
-
onSubscriptionCanceled: async (data) => {},
|
|
256
|
-
onSubscriptionFrozen: async (data) => {},
|
|
257
|
-
onSubscriptionResumed: async (data) => {},
|
|
258
|
-
onSubscriptionRenewed: async (data) => {},
|
|
259
|
-
onSubscriptionPaymentFailed: async (data) => {},
|
|
216
|
+
### Start checkout
|
|
217
|
+
|
|
218
|
+
```ts
|
|
219
|
+
const { data } = await authClient.subscription.upgrade({
|
|
220
|
+
plan: "pro-monthly",
|
|
260
221
|
});
|
|
222
|
+
|
|
223
|
+
window.location.href = data.url;
|
|
261
224
|
```
|
|
262
225
|
|
|
263
|
-
|
|
226
|
+
On the success page:
|
|
264
227
|
|
|
265
|
-
|
|
228
|
+
```ts
|
|
229
|
+
await authClient.subscription.success({
|
|
230
|
+
query: { subscriptionId: data.subscriptionId },
|
|
231
|
+
});
|
|
232
|
+
```
|
|
266
233
|
|
|
267
|
-
|
|
268
|
-
| -------------------------------------- | ------ | ---------------------------------------------------------------- |
|
|
269
|
-
| `/subscription/upgrade` | POST | Creates payment link + `incomplete` row. Idempotent within 15min |
|
|
270
|
-
| `/subscription/success` | GET | Post-checkout fallback sync if webhook is slow |
|
|
271
|
-
| `/subscription/cancel` | POST | Immediate or `cancelAtPeriodEnd: true` |
|
|
272
|
-
| `/subscription/change-plan` | POST | `mode: "at_period_end"` (default) or `"immediate"` |
|
|
273
|
-
| `/subscription/freeze` | POST | |
|
|
274
|
-
| `/subscription/unfreeze` | POST | Ends the active freeze early |
|
|
275
|
-
| `/subscription/list` | GET | Local rows + plan config |
|
|
276
|
-
| `/subscription/current?group=...` | GET | Returns `active`/`frozen`/`past_due` only (or `null`). See note below. |
|
|
277
|
-
| `/subscription/has-feature?feature=X` | GET | Boolean entitlement |
|
|
278
|
-
| `/subscription/check-limit?feature=X&count=N` | GET | `{ allowed, limit, remaining }` |
|
|
234
|
+
Then refresh the subscription data used by your UI.
|
|
279
235
|
|
|
280
|
-
###
|
|
236
|
+
### Manage a subscription
|
|
281
237
|
|
|
282
238
|
```ts
|
|
283
|
-
|
|
284
|
-
|
|
239
|
+
await authClient.subscription.changePlan({
|
|
240
|
+
subscriptionId,
|
|
241
|
+
plan: "pro-yearly",
|
|
242
|
+
});
|
|
285
243
|
|
|
286
|
-
|
|
287
|
-
await authClient.subscriptionSuccess({ subscriptionId: data.subscriptionId });
|
|
244
|
+
await authClient.subscription.changePlan.cancel({ subscriptionId });
|
|
288
245
|
|
|
289
|
-
|
|
290
|
-
await authClient.cancelSubscription({
|
|
246
|
+
await authClient.subscription.cancel({
|
|
291
247
|
subscriptionId,
|
|
292
248
|
cancelAtPeriodEnd: true,
|
|
293
249
|
});
|
|
294
250
|
|
|
295
|
-
|
|
296
|
-
|
|
251
|
+
await authClient.subscription.uncancel({ subscriptionId });
|
|
252
|
+
```
|
|
297
253
|
|
|
298
|
-
|
|
299
|
-
|
|
300
|
-
window.location.href = change.url;
|
|
254
|
+
StreamPay cancels an active subscription at the end of its current period. Trial and inactive
|
|
255
|
+
subscriptions are canceled at once.
|
|
301
256
|
|
|
302
|
-
|
|
303
|
-
|
|
257
|
+
### Freeze a subscription
|
|
258
|
+
|
|
259
|
+
```ts
|
|
260
|
+
const { data: freeze } = await authClient.subscription.freeze({
|
|
304
261
|
subscriptionId,
|
|
305
262
|
freezeStartDatetime: new Date().toISOString(),
|
|
306
263
|
freezeEndDatetime: null,
|
|
307
264
|
});
|
|
308
|
-
await authClient.unfreezeSubscription({ subscriptionId });
|
|
309
|
-
|
|
310
|
-
// Reads
|
|
311
|
-
const current = await authClient.currentSubscription();
|
|
312
|
-
const seats = await authClient.checkSubscriptionLimit({ feature: "seats", count: 8 });
|
|
313
|
-
const flag = await authClient.hasSubscriptionFeature({ feature: "ai_calls" });
|
|
314
|
-
```
|
|
315
265
|
|
|
316
|
-
|
|
266
|
+
await authClient.subscription.unfreeze({ subscriptionId });
|
|
317
267
|
|
|
318
|
-
|
|
319
|
-
|
|
320
|
-
|
|
321
|
-
|
|
322
|
-
|
|
323
|
-
> `active`, `frozen`, or `past_due` — i.e. live entitlements. **`incomplete`
|
|
324
|
-
> rows are filtered out.**
|
|
325
|
-
>
|
|
326
|
-
> Practical consequence: between `/subscription/upgrade` (which creates an
|
|
327
|
-
> `incomplete` row and a payment link) and the `SUBSCRIPTION_ACTIVATED`
|
|
328
|
-
> webhook landing, `/subscription/current` returns `null`. If you want to
|
|
329
|
-
> render "your subscription is being activated" during that window, call
|
|
330
|
-
> `/subscription/list` and filter for `status === "incomplete"` in your UI.
|
|
268
|
+
await authClient.subscription.freeze.cancel({
|
|
269
|
+
subscriptionId,
|
|
270
|
+
freezeId: freeze.id!,
|
|
271
|
+
});
|
|
272
|
+
```
|
|
331
273
|
|
|
332
|
-
|
|
333
|
-
- `past_due` — renewal failed. StreamPay keeps `ACTIVE` during dunning; we don't.
|
|
274
|
+
### Read access and limits
|
|
334
275
|
|
|
335
|
-
|
|
276
|
+
```ts
|
|
277
|
+
const current = await authClient.subscription.current({
|
|
278
|
+
query: { group: "main" },
|
|
279
|
+
});
|
|
336
280
|
|
|
337
|
-
|
|
281
|
+
const feature = await authClient.subscription.hasFeature({
|
|
282
|
+
query: { feature: "reports", group: "main" },
|
|
283
|
+
});
|
|
338
284
|
|
|
339
|
-
|
|
340
|
-
|
|
341
|
-
|
|
342
|
-
return user.role === "admin";
|
|
343
|
-
},
|
|
285
|
+
const seats = await authClient.subscription.checkLimit({
|
|
286
|
+
query: { feature: "seats", count: 4, group: "main" },
|
|
287
|
+
});
|
|
344
288
|
```
|
|
345
289
|
|
|
346
|
-
|
|
290
|
+
Pass `group` for grouped plans. Leave it out only for a plan without a group.
|
|
347
291
|
|
|
348
|
-
|
|
292
|
+
By default, `active`, `trialing`, `frozen`, and `past_due` subscriptions can use plan
|
|
293
|
+
features. Change this with `accessStatuses`.
|
|
349
294
|
|
|
350
|
-
|
|
295
|
+
## Server-side calls
|
|
351
296
|
|
|
352
|
-
|
|
353
|
-
|
|
354
|
-
- Fires your `onSubscription*` callbacks after the row is persisted.
|
|
355
|
-
- Transient failure → 500 (StreamPay retries). Permanent → logged + 200.
|
|
297
|
+
Every checkout, portal, subscription, and admin action is also available on `auth.api`. Types
|
|
298
|
+
come from Better Auth.
|
|
356
299
|
|
|
357
|
-
|
|
358
|
-
|
|
359
|
-
Back-office over the StreamPay SDK. Auth gate is `(adminRoles match user.role) || (isAdmin returns true)` — anon → 401, non-admin → 403.
|
|
300
|
+
Browser calls follow the route path, such as `authClient.subscription.cancel`. Server calls use
|
|
301
|
+
the endpoint name, such as `auth.api.cancelSubscription`.
|
|
360
302
|
|
|
361
303
|
```ts
|
|
362
|
-
|
|
363
|
-
adminRoles: ["admin", "billing_ops"],
|
|
364
|
-
isAdmin: async (user, ctx) => user.email.endsWith("@yourco.com"),
|
|
304
|
+
import { headers } from "next/headers";
|
|
365
305
|
|
|
366
|
-
|
|
367
|
-
|
|
306
|
+
const current = await auth.api.currentSubscription({
|
|
307
|
+
query: { group: "main" },
|
|
308
|
+
headers: await headers(),
|
|
368
309
|
});
|
|
369
|
-
```
|
|
370
310
|
|
|
371
|
-
|
|
372
|
-
|
|
373
|
-
- List endpoints accept `?page=` / `?size=` (max 100); consumers also `?search_term=`; payments also `?invoice_id=`.
|
|
374
|
-
- Admin sub mutations refetch + project into the local `subscription` row using the same code path as the webhook — no drift.
|
|
375
|
-
|
|
376
|
-
### Endpoints
|
|
377
|
-
|
|
378
|
-
| Endpoint | Method | SDK call |
|
|
379
|
-
| --------------------------------------------------- | ------ | ------------------------------ |
|
|
380
|
-
| `/admin/streampay/payments` | GET | `listPayments` |
|
|
381
|
-
| `/admin/streampay/payments/:id` | GET | `getPayment` |
|
|
382
|
-
| `/admin/streampay/payments/:id/refund` | POST | `refundPayment` |
|
|
383
|
-
| `/admin/streampay/subscriptions` | GET | `listSubscriptions` |
|
|
384
|
-
| `/admin/streampay/subscriptions` | POST | `createSubscription` |
|
|
385
|
-
| `/admin/streampay/subscriptions/:id` | GET | `getSubscription` |
|
|
386
|
-
| `/admin/streampay/subscriptions/:id` | PATCH | `updateSubscription` |
|
|
387
|
-
| `/admin/streampay/subscriptions/:id/cancel` | POST | `cancelSubscription` |
|
|
388
|
-
| `/admin/streampay/subscriptions/:id/freeze` | GET | `listSubscriptionFreezes` |
|
|
389
|
-
| `/admin/streampay/subscriptions/:id/freeze` | POST | `freezeSubscription` |
|
|
390
|
-
| `/admin/streampay/subscriptions/:id/freeze/:freezeId` | PUT | `updateSubscriptionFreeze` |
|
|
391
|
-
| `/admin/streampay/subscriptions/:id/freeze/:freezeId` | DELETE | `deleteSubscriptionFreeze` |
|
|
392
|
-
| `/admin/streampay/consumers` | GET | `listConsumers` (`search_term`) |
|
|
393
|
-
| `/admin/streampay/consumers/:id` | GET | `getConsumer` |
|
|
394
|
-
| `/admin/streampay/consumers/:id` | PATCH | `updateConsumer` |
|
|
395
|
-
| `/admin/streampay/consumers/:id` | DELETE | `deleteConsumer` + clears `streampayConsumerId` |
|
|
396
|
-
| `/admin/streampay/invoices` | GET | `listInvoices` |
|
|
397
|
-
| `/admin/streampay/invoices/:id` | GET | `getInvoice` |
|
|
398
|
-
| `/admin/streampay/products` | GET / POST | `listProducts` / `createProduct` |
|
|
399
|
-
| `/admin/streampay/products/:id` | GET / PUT / DELETE | `getProduct` / `updateProduct` / `deleteProduct` |
|
|
400
|
-
| `/admin/streampay/coupons` | GET / POST | `listCoupons` / `createCoupon` |
|
|
401
|
-
| `/admin/streampay/coupons/:id` | GET / PUT / DELETE | `getCoupon` / `updateCoupon` / `deleteCoupon` |
|
|
402
|
-
| `/admin/streampay/payment-links` | GET | `listPaymentLinks` |
|
|
403
|
-
| `/admin/streampay/payment-links/:id` | GET | `getPaymentLink` |
|
|
404
|
-
|
|
405
|
-
### Calling
|
|
406
|
-
|
|
407
|
-
Method names mirror the routes: `adminListProducts`, `adminCreateProduct`, `adminCancelSubscription`, `adminRefundPayment`, etc.
|
|
408
|
-
|
|
409
|
-
Server (`auth.api.*`):
|
|
410
|
-
```ts
|
|
411
|
-
await auth.api.adminCancelSubscription({
|
|
412
|
-
params: { id: streampaySubscriptionId },
|
|
413
|
-
body: { cancel_related_invoices: true },
|
|
311
|
+
await auth.api.cancelSubscription({
|
|
312
|
+
body: { subscriptionId, cancelAtPeriodEnd: true },
|
|
414
313
|
headers: await headers(),
|
|
415
314
|
});
|
|
416
315
|
```
|
|
417
316
|
|
|
418
|
-
|
|
419
|
-
```ts
|
|
420
|
-
await authClient.adminListProducts({ query: { page: 1, size: 20 } });
|
|
421
|
-
```
|
|
317
|
+
Pass the request headers so Better Auth can read the session.
|
|
422
318
|
|
|
423
|
-
|
|
319
|
+
Webhook delivery is not an `auth.api` action. It uses the raw HTTP body to verify the signature.
|
|
424
320
|
|
|
425
|
-
|
|
426
|
-
|
|
427
|
-
|
|
428
|
-
|
|
429
|
-
|
|
430
|
-
price: "99.000", // SAR (string preserves halalat precision)
|
|
431
|
-
is_one_time: false,
|
|
432
|
-
type: "RECURRING", // or "ONE_OFF"
|
|
433
|
-
recurring_interval: "MONTH", // WEEK | MONTH | QUARTER | YEAR
|
|
434
|
-
recurring_interval_count: 1,
|
|
435
|
-
is_price_inclusive_of_vat: true,
|
|
436
|
-
},
|
|
437
|
-
});
|
|
438
|
-
```
|
|
439
|
-
For ONE_OFF: drop the `recurring_*` fields, set `type: "ONE_OFF"`, `is_one_time: true`.
|
|
321
|
+
## Cross-account access
|
|
322
|
+
|
|
323
|
+
User actions use the signed-in user's ID by default.
|
|
324
|
+
|
|
325
|
+
To manage an organization or another app-owned reference, add `authorizeReference`:
|
|
440
326
|
|
|
441
|
-
Refund a payment:
|
|
442
327
|
```ts
|
|
443
|
-
|
|
444
|
-
|
|
445
|
-
|
|
446
|
-
|
|
447
|
-
refund_note: "optional",
|
|
448
|
-
allow_refund_multiple_related_payments: false,
|
|
328
|
+
subscriptions({
|
|
329
|
+
plans,
|
|
330
|
+
authorizeReference: async ({ user, referenceId, referenceType, action }) => {
|
|
331
|
+
return canManageBilling(user, referenceId, referenceType, action);
|
|
449
332
|
},
|
|
450
333
|
});
|
|
451
334
|
```
|
|
452
|
-
Refunds are always full (no `amount` field). Settled payments only — `PENDING`/`CANCELED` → 400 `PAYMENT_INVALID_STATE`.
|
|
453
335
|
|
|
454
|
-
|
|
336
|
+
Without this callback, cross-account actions return `FORBIDDEN`.
|
|
455
337
|
|
|
456
|
-
|
|
457
|
-
|
|
458
|
-
## Webhooks
|
|
338
|
+
## Admin
|
|
459
339
|
|
|
460
|
-
|
|
340
|
+
`admin()` adds billing actions for payments, subscriptions, freezes, consumers, invoices,
|
|
341
|
+
products, coupons, payment links, and webhook retries.
|
|
461
342
|
|
|
462
343
|
```ts
|
|
463
|
-
|
|
464
|
-
secret: process.env.STREAMPAY_WEBHOOK_SECRET!,
|
|
465
|
-
toleranceSeconds: 300, // default 300s
|
|
466
|
-
|
|
467
|
-
onPayload: async (p) => { /* catch-all, runs first */ },
|
|
468
|
-
|
|
469
|
-
onPaymentSucceeded: async (p) => {},
|
|
470
|
-
onPaymentFailed: async (p) => {},
|
|
471
|
-
onPaymentCanceled: async (p) => {},
|
|
472
|
-
onPaymentRefunded: async (p) => {},
|
|
473
|
-
onPaymentMarkedAsPaid: async (p) => {},
|
|
474
|
-
|
|
475
|
-
onInvoiceCreated: async (p) => {},
|
|
476
|
-
onInvoiceSent: async (p) => {},
|
|
477
|
-
onInvoiceAccepted: async (p) => {},
|
|
478
|
-
onInvoiceRejected: async (p) => {},
|
|
479
|
-
onInvoiceCompleted: async (p) => {},
|
|
480
|
-
onInvoiceCanceled: async (p) => {},
|
|
481
|
-
onInvoiceUpdated: async (p) => {},
|
|
482
|
-
|
|
483
|
-
onSubscriptionCreated: async (p) => {},
|
|
484
|
-
onSubscriptionActivated: async (p) => {},
|
|
485
|
-
onSubscriptionInactivated: async (p) => {},
|
|
486
|
-
onSubscriptionCanceled: async (p) => {},
|
|
487
|
-
onSubscriptionFrozen: async (p) => {},
|
|
488
|
-
onSubscriptionCycleRenewalFailed: async (p) => {},
|
|
489
|
-
onSubscriptionCancelAtPeriodEnd: async (p) => {},
|
|
490
|
-
onSubscriptionFreezeNow: async (p) => {},
|
|
491
|
-
onSubscriptionUnfreezeNow: async (p) => {},
|
|
492
|
-
onSubscriptionUnfreezeFuture: async (p) => {},
|
|
493
|
-
onSubscriptionFreezeCancel: async (p) => {},
|
|
494
|
-
|
|
495
|
-
onPaymentLinkPayAttemptFailed: async (p) => {},
|
|
496
|
-
});
|
|
497
|
-
```
|
|
344
|
+
import { admin } from "better-auth-streampay";
|
|
498
345
|
|
|
499
|
-
|
|
500
|
-
|
|
501
|
-
|
|
502
|
-
|
|
503
|
-
event_type: StreamPayEventType;
|
|
504
|
-
entity_type: "PAYMENT" | "INVOICE" | "SUBSCRIPTION" | "PAYMENT_LINK";
|
|
505
|
-
entity_id: string;
|
|
506
|
-
entity_url: string;
|
|
507
|
-
status: string;
|
|
508
|
-
data: T;
|
|
509
|
-
timestamp: string; // ISO 8601
|
|
510
|
-
}
|
|
346
|
+
admin({
|
|
347
|
+
adminRoles: ["admin", "billing"],
|
|
348
|
+
isAdmin: async (user) => user.email.endsWith("@example.com"),
|
|
349
|
+
});
|
|
511
350
|
```
|
|
512
351
|
|
|
513
|
-
|
|
352
|
+
Calls use names such as:
|
|
514
353
|
|
|
515
|
-
|
|
354
|
+
- `auth.api.adminListPayments`
|
|
355
|
+
- `auth.api.adminGetSubscription`
|
|
356
|
+
- `auth.api.adminCreateProduct`
|
|
357
|
+
- `auth.api.adminReplayWebhookEvent`
|
|
516
358
|
|
|
517
|
-
|
|
359
|
+
The IDE shows the body, query, and response types for every action.
|
|
518
360
|
|
|
519
|
-
|
|
361
|
+
Make sure your Better Auth route accepts `GET`, `POST`, `PATCH`, `PUT`, and `DELETE`.
|
|
520
362
|
|
|
521
|
-
|
|
522
|
-
webhooks({
|
|
523
|
-
secret: [
|
|
524
|
-
process.env.STREAMPAY_WEBHOOK_SECRET!, // new
|
|
525
|
-
process.env.STREAMPAY_WEBHOOK_SECRET_OLD!, // old
|
|
526
|
-
],
|
|
527
|
-
});
|
|
528
|
-
```
|
|
529
|
-
|
|
530
|
-
Drop the old one once the dashboard is fully cut over.
|
|
363
|
+
## Webhooks
|
|
531
364
|
|
|
532
|
-
|
|
365
|
+
Register this URL in the StreamPay dashboard:
|
|
533
366
|
|
|
534
|
-
```
|
|
535
|
-
|
|
536
|
-
id: string;
|
|
537
|
-
referenceId: string;
|
|
538
|
-
streampaySubscriptionId: string | null;
|
|
539
|
-
streampayConsumerId: string | null;
|
|
540
|
-
plan: string;
|
|
541
|
-
group: string | null;
|
|
542
|
-
amountHalalat: number | null;
|
|
543
|
-
currency: string | null;
|
|
544
|
-
billingInterval: "WEEK" | "MONTH" | "QUARTER" | "YEAR" | null;
|
|
545
|
-
billingIntervalCount: number | null;
|
|
546
|
-
status: "incomplete" | "active" | "inactive" | "expired" | "canceled" | "frozen" | "past_due";
|
|
547
|
-
periodStart: Date | null;
|
|
548
|
-
periodEnd: Date | null;
|
|
549
|
-
cancelAtPeriodEnd: boolean;
|
|
550
|
-
endedAt: Date | null;
|
|
551
|
-
frozenAt: Date | null;
|
|
552
|
-
freezeEndAt: Date | null;
|
|
553
|
-
createdAt: Date;
|
|
554
|
-
updatedAt: Date;
|
|
555
|
-
}
|
|
367
|
+
```text
|
|
368
|
+
https://your-app.com/api/auth/streampay/webhooks
|
|
556
369
|
```
|
|
557
370
|
|
|
558
|
-
|
|
371
|
+
Then add the handlers you need:
|
|
559
372
|
|
|
560
373
|
```ts
|
|
561
|
-
|
|
374
|
+
webhooks({
|
|
375
|
+
secret: process.env.STREAMPAY_WEBHOOK_SECRET!,
|
|
562
376
|
|
|
563
|
-
|
|
564
|
-
|
|
565
|
-
}
|
|
377
|
+
onPaymentSucceeded: async (event) => {},
|
|
378
|
+
onPaymentFailed: async (event) => {},
|
|
379
|
+
onSubscriptionActivated: async (event) => {},
|
|
380
|
+
onSubscriptionCanceled: async (event) => {},
|
|
381
|
+
onPayload: async (event) => {},
|
|
382
|
+
});
|
|
566
383
|
```
|
|
567
384
|
|
|
568
|
-
|
|
385
|
+
The plugin:
|
|
569
386
|
|
|
570
|
-
|
|
387
|
+
- checks the webhook signature
|
|
388
|
+
- rejects old signatures
|
|
389
|
+
- deduplicates subscription sync and lifecycle callbacks
|
|
390
|
+
- retries temporary failures
|
|
391
|
+
- stores failed subscription events for admin replay
|
|
571
392
|
|
|
572
|
-
|
|
393
|
+
The StreamPay SDK does not export webhook payload types. This package provides checked event
|
|
394
|
+
types based on StreamPay's documented payloads.
|
|
573
395
|
|
|
574
|
-
|
|
396
|
+
To rotate a secret:
|
|
575
397
|
|
|
576
398
|
```ts
|
|
577
|
-
|
|
578
|
-
|
|
579
|
-
|
|
580
|
-
|
|
581
|
-
|
|
582
|
-
|
|
583
|
-
const result = verifyWebhook({
|
|
584
|
-
secret: process.env.STREAMPAY_WEBHOOK_SECRET!,
|
|
585
|
-
rawBody,
|
|
586
|
-
signatureHeader: req.headers.get("x-webhook-signature"),
|
|
587
|
-
toleranceSeconds: 300,
|
|
399
|
+
webhooks({
|
|
400
|
+
secret: [
|
|
401
|
+
process.env.STREAMPAY_WEBHOOK_SECRET!,
|
|
402
|
+
process.env.STREAMPAY_WEBHOOK_SECRET_OLD!,
|
|
403
|
+
],
|
|
588
404
|
});
|
|
589
|
-
|
|
590
|
-
if (!result.ok) {
|
|
591
|
-
// result.reason: MISSING_HEADER | MALFORMED_HEADER | INVALID_TIMESTAMP | EXPIRED | INVALID_SIGNATURE
|
|
592
|
-
}
|
|
593
405
|
```
|
|
594
406
|
|
|
595
|
-
|
|
407
|
+
Remove the old secret after StreamPay uses the new one.
|
|
596
408
|
|
|
597
|
-
|
|
598
|
-
import { dispatchWebhook } from "better-auth-streampay";
|
|
409
|
+
## What owns each job
|
|
599
410
|
|
|
600
|
-
|
|
601
|
-
onPayload: async (p) => {},
|
|
602
|
-
onPaymentSucceeded: async (p) => {},
|
|
603
|
-
});
|
|
604
|
-
```
|
|
411
|
+
StreamPay owns:
|
|
605
412
|
|
|
606
|
-
|
|
413
|
+
- charges
|
|
414
|
+
- invoices
|
|
415
|
+
- subscription state
|
|
416
|
+
- trials
|
|
417
|
+
- renewal attempts
|
|
418
|
+
- cancellation timing
|
|
607
419
|
|
|
608
|
-
|
|
609
|
-
import {
|
|
610
|
-
findConsumerByExternalId,
|
|
611
|
-
findConsumerByIdentifiers,
|
|
612
|
-
} from "better-auth-streampay";
|
|
420
|
+
The plugin owns:
|
|
613
421
|
|
|
614
|
-
|
|
422
|
+
- Better Auth access checks
|
|
423
|
+
- local subscription rows
|
|
424
|
+
- plan features and limits
|
|
425
|
+
- webhook checks and retries
|
|
426
|
+
- checkout recovery
|
|
615
427
|
|
|
616
|
-
|
|
617
|
-
email: "user@example.com",
|
|
618
|
-
phone_number: "+966501234567",
|
|
619
|
-
external_id: "user-123",
|
|
620
|
-
iban: "SA...",
|
|
621
|
-
});
|
|
622
|
-
```
|
|
428
|
+
Do not edit subscription rows by hand. Let provider responses and webhooks update them.
|
|
623
429
|
|
|
624
|
-
|
|
430
|
+
## Errors
|
|
431
|
+
|
|
432
|
+
Errors use stable codes:
|
|
625
433
|
|
|
626
434
|
```ts
|
|
627
|
-
import {
|
|
435
|
+
import { $ERROR_CODES } from "better-auth-streampay";
|
|
628
436
|
|
|
629
|
-
|
|
630
|
-
|
|
631
|
-
} catch (err) {
|
|
632
|
-
console.error(formatStreamPayError(err));
|
|
633
|
-
const { status, code, requestId, validationErrors } = parseStreamPayError(err);
|
|
437
|
+
if (error.code === $ERROR_CODES.SUBSCRIPTION_ALREADY_ACTIVE.code) {
|
|
438
|
+
// Show the current plan.
|
|
634
439
|
}
|
|
635
440
|
```
|
|
636
441
|
|
|
637
|
-
|
|
442
|
+
Common codes include:
|
|
638
443
|
|
|
639
|
-
|
|
640
|
-
|
|
444
|
+
- `VALIDATION_ERROR`
|
|
445
|
+
- `FORBIDDEN`
|
|
446
|
+
- `NOT_FOUND`
|
|
447
|
+
- `SUBSCRIPTION_ALREADY_ACTIVE`
|
|
448
|
+
- `SUBSCRIPTION_INVALID_STATE`
|
|
449
|
+
- `SUBSCRIPTION_PLAN_CHANGE_ALREADY_SCHEDULED`
|
|
450
|
+
- `WEBHOOK_REPLAY_IN_PROGRESS`
|
|
641
451
|
|
|
642
|
-
|
|
643
|
-
StreamPayAmount.toSAR(9900); // "99.00"
|
|
644
|
-
```
|
|
645
|
-
|
|
646
|
-
### Event-type constants
|
|
452
|
+
## Useful exports
|
|
647
453
|
|
|
648
454
|
```ts
|
|
649
455
|
import {
|
|
650
|
-
|
|
651
|
-
|
|
652
|
-
|
|
653
|
-
|
|
654
|
-
|
|
655
|
-
|
|
656
|
-
|
|
657
|
-
type StreamPayWebhookPayload,
|
|
658
|
-
type WebhookHandler,
|
|
659
|
-
type WebhookHandlers,
|
|
456
|
+
StreamPayAmount,
|
|
457
|
+
checkLimit,
|
|
458
|
+
findConsumerByExternalId,
|
|
459
|
+
formatStreamPayError,
|
|
460
|
+
hasFeature,
|
|
461
|
+
parseStreamPayError,
|
|
462
|
+
verifyWebhook,
|
|
660
463
|
} from "better-auth-streampay";
|
|
661
464
|
```
|
|
662
465
|
|
|
663
|
-
### Subscription helpers
|
|
664
|
-
|
|
665
|
-
```ts
|
|
666
|
-
import { hasFeature, checkLimit, subscriptionSchema } from "better-auth-streampay";
|
|
667
|
-
|
|
668
|
-
const allowed = hasFeature(row, plan, "ai_calls");
|
|
669
|
-
const quota = checkLimit(row, plan, "seats", 8); // { allowed, limit, remaining }
|
|
670
|
-
```
|
|
671
|
-
|
|
672
|
-
## Endpoints summary
|
|
673
|
-
|
|
674
|
-
| Key | Method | Path | Auth | Plugin |
|
|
675
|
-
| ------------------------- | ------ | ---------------------------------- | --------- | ----------------- |
|
|
676
|
-
| `checkout` | POST | `/checkout` | Optional | `checkout()` |
|
|
677
|
-
| `state` | GET | `/consumer/state` | Required | `portal()` |
|
|
678
|
-
| `subscriptions` | GET | `/consumer/subscriptions/list` | Required | `portal()` |
|
|
679
|
-
| `invoices` | GET | `/consumer/invoices/list` | Required | `portal()` |
|
|
680
|
-
| `upgradeSubscription` | POST | `/subscription/upgrade` | Required | `subscriptions()` |
|
|
681
|
-
| `subscriptionSuccess` | GET | `/subscription/success` | Required | `subscriptions()` |
|
|
682
|
-
| `cancelSubscription` | POST | `/subscription/cancel` | Required | `subscriptions()` |
|
|
683
|
-
| `changeSubscriptionPlan` | POST | `/subscription/change-plan` | Required | `subscriptions()` |
|
|
684
|
-
| `freezeSubscription` | POST | `/subscription/freeze` | Required | `subscriptions()` |
|
|
685
|
-
| `unfreezeSubscription` | POST | `/subscription/unfreeze` | Required | `subscriptions()` |
|
|
686
|
-
| `listSubscriptions` | GET | `/subscription/list` | Required | `subscriptions()` |
|
|
687
|
-
| `currentSubscription` | GET | `/subscription/current` | Required | `subscriptions()` |
|
|
688
|
-
| `hasSubscriptionFeature` | GET | `/subscription/has-feature` | Required | `subscriptions()` |
|
|
689
|
-
| `checkSubscriptionLimit` | GET | `/subscription/check-limit` | Required | `subscriptions()` |
|
|
690
|
-
| `streampayWebhooks` | POST | `/streampay/webhooks` | Signature | `webhooks()` |
|
|
691
|
-
| `admin*` | varied | `/admin/streampay/...` | Role | `admin()` |
|
|
692
|
-
|
|
693
|
-
## Scripts
|
|
694
|
-
|
|
695
|
-
```bash
|
|
696
|
-
pnpm test # vitest
|
|
697
|
-
pnpm typecheck # tsc --noEmit
|
|
698
|
-
pnpm lint # biome check
|
|
699
|
-
pnpm build # tsup (ESM + CJS)
|
|
700
|
-
```
|
|
701
|
-
|
|
702
466
|
## License
|
|
703
467
|
|
|
704
468
|
MIT
|