better-auth-streampay 1.3.0 → 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 CHANGED
@@ -1,94 +1,108 @@
1
1
  # better-auth-streampay
2
2
 
3
- > Community plugin. Not affiliated with Stream / StreamPay.
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
- [Better Auth](https://better-auth.com) plugin for [StreamPay](https://streampay.sa).
5
+ ## Agent skill
7
6
 
8
- ## Features
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
- pnpm add better-auth-streampay @streamsdk/typescript better-auth zod
10
+ npx skills add Genie-sa/better-auth-streampay
22
11
  ```
23
12
 
24
- Peers: `better-auth ^1.4`, `@streamsdk/typescript ^1.0.6`, `zod ^3.24 || ^4`.
13
+ Then ask your coding agent to add StreamPay to your Better Auth app.
25
14
 
26
- ### Preview releases
15
+ The plugin can:
27
16
 
28
- Every push to `main` and every PR is published as an installable tarball
29
- via [pkg.pr.new](https://github.com/stackblitz-labs/pkg.pr.new):
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 https://pkg.pr.new/better-auth-streampay@<sha-or-pr-number>
27
+ pnpm add better-auth-streampay @streamsdk/typescript
33
28
  ```
34
29
 
35
- ## Env
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
- ## Server
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 client = StreamSDK.init(process.env.STREAMPAY_API_KEY!);
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: "prod_recurring_uuid",
77
- priceHalalat: 9900,
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({ secret: process.env.STREAMPAY_WEBHOOK_SECRET! }),
84
- admin(),
78
+ webhooks({
79
+ secret: process.env.STREAMPAY_WEBHOOK_SECRET!,
80
+ }),
85
81
  ],
86
82
  }),
87
83
  ],
88
84
  });
89
85
  ```
90
86
 
91
- ## Client
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,605 +113,356 @@ export const authClient = createAuthClient({
99
113
  });
100
114
  ```
101
115
 
102
- ## Database migration
116
+ Use the matching Better Auth client for Vue, Svelte, or Solid.
103
117
 
104
- Adds a `streampayConsumerId` column on `user`, plus `subscription` and `streampayWebhookEvent` tables when `subscriptions()` is in `use`.
118
+ ## Consumers
105
119
 
106
- ```bash
107
- npx @better-auth/cli migrate # Better Auth CLI
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
- ## `streampay()` options
123
+ To create the consumer during sign-up:
113
124
 
114
125
  ```ts
115
126
  streampay({
116
- client,
117
- // Eagerly create a consumer at signup. Default: false (lazy).
118
- createConsumerOnSignUp: false,
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
- ### Consumer lifecycle
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
- `claimExistingConsumerBy` controls reuse when StreamPay returns `DUPLICATE_CONSUMER`:
141
-
142
- | Value | Behavior |
143
- | -------------------- | ------------------------------------------------------------------- |
144
- | omitted / `[]` | Reuse only stranded consumers (no `external_id`). |
145
- | `["email"]` | Also reuse consumers matching the same email. |
146
- | `["phone"]` | Also reuse consumers matching the same phone. |
147
- | `["email","phone"]` | Reuse on either match. |
135
+ ```ts
136
+ streampay({
137
+ client: streamPayClient,
138
+ createConsumerOnSignUp: true,
139
+ claimExistingConsumerBy: ["email"],
140
+ use: [],
141
+ });
142
+ ```
148
143
 
149
- If reused, the plugin rewrites `external_id` to the new user id.
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: [{ productId: "aaaa-bbbb-cccc-dddd", slug: "pro" }],
156
- successUrl: "/dashboard?checkout=success",
157
- failureUrl: "/dashboard?checkout=failure",
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
- `products` can be a static array or a `() => Promise<StreamPayProduct[]>` factory.
165
-
166
- ### Client
159
+ Open checkout:
167
160
 
168
161
  ```ts
169
- // By slug
170
- const { data } = await authClient.checkout({ slug: "pro" });
171
- window.location.href = data.url;
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
- // With reference id and metadata
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
- ### Body fields
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
- | `name` | `string` | Payment link display name |
197
- | `description` | `string` | |
198
- | `metadata` | `Record<string, string \| number \| boolean>` | |
199
- | `successUrl` | `string` | Absolute or `/relative` |
200
- | `failureUrl` | `string` | Absolute or `/relative` |
201
- | `maxNumberOfPayments` | `number` | |
202
- | `validUntil` | `string` (ISO 8601) | |
203
- | `couponIds` | `string[]` (uuid) | |
204
- | `redirect` | `boolean` | Default `true` |
205
-
206
- ## Portal
170
+ You can also pass StreamPay product IDs directly with `products`.
207
171
 
208
- ```ts
209
- portal(); // default page size 100 (StreamPay's max)
210
- portal({ pageSize: 50 });
211
- ```
172
+ ## Billing portal
212
173
 
213
- Reads are scoped to the session user via `organization_consumer_id`. One API call per read.
174
+ `portal()` adds three signed-in user actions:
214
175
 
215
- ```ts
216
- const { data } = await authClient.state();
217
- if (!data.hasConsumer) {
218
- // user has no StreamPay consumer yet
219
- }
176
+ - `state`
177
+ - `subscriptions`
178
+ - `invoices`
220
179
 
221
- const subs = await authClient.subscriptions(); // { hasConsumer, data }
222
- const invoices = await authClient.invoices(); // { hasConsumer, data }
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();
223
184
  ```
224
185
 
225
- When `hasConsumer` is `false`, reads return `200 OK` with `data: []` (or `consumer: null`) instead of 404.
226
-
227
186
  ## Subscriptions
228
187
 
229
188
  ```ts
230
189
  subscriptions({
231
190
  plans: [
232
191
  {
233
- name: "pro",
234
- productId: "prod_recurring_uuid",
235
- priceHalalat: 9900, // 99.00 SAR
236
- billingInterval: "MONTH", // WEEK | MONTH | QUARTER | YEAR
237
- billingIntervalCount: 1, // optional
238
- group: "tier", // optional, enforces 1 active per group
239
- limits: { seats: 10, ai_calls: 1000 }, // typed entitlements
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 },
240
201
  },
241
202
  ],
242
- // or a factory: plans: async () => fetchPlansFromCMS(),
243
203
 
244
- authorizeReference: async ({ user, referenceId, action }) => {
245
- return user.role === "admin";
204
+ onSubscriptionActivated: async ({ subscription, user }) => {
205
+ // Run app-specific work here.
246
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.
247
215
 
248
- // Schema knobs (defaults shown). Set to false to BYO state.
249
- enableSubscriptionTable: true, // false → skip `subscription` schema + auto-sync
250
- enableWebhookEventTable: true, // false → skip `streampayWebhookEvent` dedupe; you handle idempotency
251
-
252
- onSubscriptionCreated: async (data) => {},
253
- onSubscriptionActivated: async (data) => {},
254
- onSubscriptionCanceled: async (data) => {},
255
- onSubscriptionFrozen: async (data) => {},
256
- onSubscriptionResumed: async (data) => {},
257
- onSubscriptionRenewed: async (data) => {},
258
- onSubscriptionPaymentFailed: async (data) => {},
216
+ ### Start checkout
217
+
218
+ ```ts
219
+ const { data } = await authClient.subscription.upgrade({
220
+ plan: "pro-monthly",
259
221
  });
222
+
223
+ window.location.href = data.url;
260
224
  ```
261
225
 
262
- Each callback receives `{ subscription, user, streampaySubscription, event }`.
226
+ On the success page:
263
227
 
264
- ### Endpoints
228
+ ```ts
229
+ await authClient.subscription.success({
230
+ query: { subscriptionId: data.subscriptionId },
231
+ });
232
+ ```
265
233
 
266
- | Path | Method | Notes |
267
- | -------------------------------------- | ------ | ---------------------------------------------------------------- |
268
- | `/subscription/upgrade` | POST | Creates payment link + `incomplete` row. Idempotent within 15min |
269
- | `/subscription/success` | GET | Post-checkout fallback sync if webhook is slow |
270
- | `/subscription/cancel` | POST | Immediate or `cancelAtPeriodEnd: true` |
271
- | `/subscription/change-plan` | POST | `mode: "at_period_end"` (default) or `"immediate"` |
272
- | `/subscription/freeze` | POST | |
273
- | `/subscription/unfreeze` | POST | Ends the active freeze early |
274
- | `/subscription/list` | GET | Local rows + plan config |
275
- | `/subscription/current?group=...` | GET | Returns `active`/`frozen`/`past_due` only (or `null`). See note below. |
276
- | `/subscription/has-feature?feature=X` | GET | Boolean entitlement |
277
- | `/subscription/check-limit?feature=X&count=N` | GET | `{ allowed, limit, remaining }` |
234
+ Then refresh the subscription data used by your UI.
278
235
 
279
- ### Client
236
+ ### Manage a subscription
280
237
 
281
238
  ```ts
282
- const { data } = await authClient.upgradeSubscription({ plan: "pro" });
283
- window.location.href = data.url;
239
+ await authClient.subscription.changePlan({
240
+ subscriptionId,
241
+ plan: "pro-yearly",
242
+ });
284
243
 
285
- // On success page:
286
- await authClient.subscriptionSuccess({ subscriptionId: data.subscriptionId });
244
+ await authClient.subscription.changePlan.cancel({ subscriptionId });
287
245
 
288
- // Cancel at period end (keeps access until periodEnd)
289
- await authClient.cancelSubscription({
246
+ await authClient.subscription.cancel({
290
247
  subscriptionId,
291
248
  cancelAtPeriodEnd: true,
292
249
  });
293
250
 
294
- // Plan change — immediate (PATCH items, no proration)
295
- await authClient.changeSubscriptionPlan({ plan: "pro_plus", mode: "immediate" });
251
+ await authClient.subscription.uncancel({ subscriptionId });
252
+ ```
296
253
 
297
- // Plan change — at period end (default; spawns new payment link)
298
- const { data: change } = await authClient.changeSubscriptionPlan({ plan: "pro_plus" });
299
- 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.
300
256
 
301
- // Freeze
302
- await authClient.freezeSubscription({
257
+ ### Freeze a subscription
258
+
259
+ ```ts
260
+ const { data: freeze } = await authClient.subscription.freeze({
303
261
  subscriptionId,
304
262
  freezeStartDatetime: new Date().toISOString(),
305
263
  freezeEndDatetime: null,
306
264
  });
307
- await authClient.unfreezeSubscription({ subscriptionId });
308
-
309
- // Reads
310
- const current = await authClient.currentSubscription();
311
- const seats = await authClient.checkSubscriptionLimit({ feature: "seats", count: 8 });
312
- const flag = await authClient.hasSubscriptionFeature({ feature: "ai_calls" });
313
- ```
314
265
 
315
- ### Status values
266
+ await authClient.subscription.unfreeze({ subscriptionId });
316
267
 
317
- `incomplete | active | inactive | expired | canceled | frozen | past_due`
318
-
319
- > **`/subscription/current` filter semantics**
320
- >
321
- > `/subscription/current` intentionally returns only rows whose status is
322
- > `active`, `frozen`, or `past_due` — i.e. live entitlements. **`incomplete`
323
- > rows are filtered out.**
324
- >
325
- > Practical consequence: between `/subscription/upgrade` (which creates an
326
- > `incomplete` row and a payment link) and the `SUBSCRIPTION_ACTIVATED`
327
- > webhook landing, `/subscription/current` returns `null`. If you want to
328
- > render "your subscription is being activated" during that window, call
329
- > `/subscription/list` and filter for `status === "incomplete"` in your UI.
268
+ await authClient.subscription.freeze.cancel({
269
+ subscriptionId,
270
+ freezeId: freeze.id!,
271
+ });
272
+ ```
330
273
 
331
- - `incomplete` — row pre-created at `/upgrade`, webhook not landed yet.
332
- - `past_due` — renewal failed. StreamPay keeps `ACTIVE` during dunning; we don't.
274
+ ### Read access and limits
333
275
 
334
- ### Cross-account access
276
+ ```ts
277
+ const current = await authClient.subscription.current({
278
+ query: { group: "main" },
279
+ });
335
280
 
336
- By default `referenceId` is the session user's id. Pass a different one and `authorizeReference` is called:
281
+ const feature = await authClient.subscription.hasFeature({
282
+ query: { feature: "reports", group: "main" },
283
+ });
337
284
 
338
- ```ts
339
- authorizeReference: async ({ user, referenceId, action }, ctx) => {
340
- // action: "upgrade" | "cancel" | "freeze" | "unfreeze" | "read" | "change-plan"
341
- return user.role === "admin";
342
- },
285
+ const seats = await authClient.subscription.checkLimit({
286
+ query: { feature: "seats", count: 4, group: "main" },
287
+ });
343
288
  ```
344
289
 
345
- Without `authorizeReference`, cross-account ops throw `FORBIDDEN`.
290
+ Pass `group` for grouped plans. Leave it out only for a plan without a group.
346
291
 
347
- ### Webhook auto-sync
292
+ By default, `active`, `trialing`, `frozen`, and `past_due` subscriptions can use plan
293
+ features. Change this with `accessStatuses`.
348
294
 
349
- If both `subscriptions()` and `webhooks()` are in `use`, the plugin runs an idempotent sync **before** your handlers:
295
+ ## Server-side calls
350
296
 
351
- - Dedupes via `streampayWebhookEvent` (`event_type:entity_id:timestamp`).
352
- - Maps subscription events + `INVOICE_COMPLETED` (renewal) onto local rows.
353
- - Fires your `onSubscription*` callbacks after the row is persisted.
354
- - 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.
355
299
 
356
- ## Admin
357
-
358
- 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`.
359
302
 
360
303
  ```ts
361
- admin({
362
- adminRoles: ["admin", "billing_ops"],
363
- isAdmin: async (user, ctx) => user.email.endsWith("@yourco.com"),
304
+ import { headers } from "next/headers";
364
305
 
365
- onRefund: async ({ user, paymentId, request }) => { /* throw to block */ },
366
- onPlanChange: async ({ user, subscriptionId, current, patch }) => { /* throw to block */ },
306
+ const current = await auth.api.currentSubscription({
307
+ query: { group: "main" },
308
+ headers: await headers(),
367
309
  });
368
- ```
369
310
 
370
- - POST/PATCH/PUT bodies forward to the SDK verbatim (types from `@streamsdk/typescript`).
371
- - DELETEs take no body / no `Content-Type`.
372
- - List endpoints accept `?page=` / `?size=` (max 100); consumers also `?search_term=`; payments also `?invoice_id=`.
373
- - Admin sub mutations refetch + project into the local `subscription` row using the same code path as the webhook — no drift.
374
-
375
- ### Endpoints
376
-
377
- | Endpoint | Method | SDK call |
378
- | --------------------------------------------------- | ------ | ------------------------------ |
379
- | `/admin/streampay/payments` | GET | `listPayments` |
380
- | `/admin/streampay/payments/:id` | GET | `getPayment` |
381
- | `/admin/streampay/payments/:id/refund` | POST | `refundPayment` |
382
- | `/admin/streampay/subscriptions` | GET | `listSubscriptions` |
383
- | `/admin/streampay/subscriptions` | POST | `createSubscription` |
384
- | `/admin/streampay/subscriptions/:id` | GET | `getSubscription` |
385
- | `/admin/streampay/subscriptions/:id` | PATCH | `updateSubscription` |
386
- | `/admin/streampay/subscriptions/:id/cancel` | POST | `cancelSubscription` |
387
- | `/admin/streampay/subscriptions/:id/freeze` | GET | `listSubscriptionFreezes` |
388
- | `/admin/streampay/subscriptions/:id/freeze` | POST | `freezeSubscription` |
389
- | `/admin/streampay/subscriptions/:id/freeze/:freezeId` | PUT | `updateSubscriptionFreeze` |
390
- | `/admin/streampay/subscriptions/:id/freeze/:freezeId` | DELETE | `deleteSubscriptionFreeze` |
391
- | `/admin/streampay/consumers` | GET | `listConsumers` (`search_term`) |
392
- | `/admin/streampay/consumers/:id` | GET | `getConsumer` |
393
- | `/admin/streampay/consumers/:id` | PATCH | `updateConsumer` |
394
- | `/admin/streampay/consumers/:id` | DELETE | `deleteConsumer` + clears `streampayConsumerId` |
395
- | `/admin/streampay/invoices` | GET | `listInvoices` |
396
- | `/admin/streampay/invoices/:id` | GET | `getInvoice` |
397
- | `/admin/streampay/products` | GET / POST | `listProducts` / `createProduct` |
398
- | `/admin/streampay/products/:id` | GET / PUT / DELETE | `getProduct` / `updateProduct` / `deleteProduct` |
399
- | `/admin/streampay/coupons` | GET / POST | `listCoupons` / `createCoupon` |
400
- | `/admin/streampay/coupons/:id` | GET / PUT / DELETE | `getCoupon` / `updateCoupon` / `deleteCoupon` |
401
- | `/admin/streampay/payment-links` | GET | `listPaymentLinks` |
402
- | `/admin/streampay/payment-links/:id` | GET | `getPaymentLink` |
403
-
404
- ### Calling
405
-
406
- Method names mirror the routes: `adminListProducts`, `adminCreateProduct`, `adminCancelSubscription`, `adminRefundPayment`, etc.
407
-
408
- Server (`auth.api.*`):
409
- ```ts
410
- await auth.api.adminCancelSubscription({
411
- params: { id: streampaySubscriptionId },
412
- body: { cancel_related_invoices: true },
311
+ await auth.api.cancelSubscription({
312
+ body: { subscriptionId, cancelAtPeriodEnd: true },
413
313
  headers: await headers(),
414
314
  });
415
315
  ```
416
316
 
417
- Client (`authClient.*` — auto-generated, cookie auto-sent, gate runs on server):
418
- ```ts
419
- await authClient.adminListProducts({ query: { page: 1, size: 20 } });
420
- ```
317
+ Pass the request headers so Better Auth can read the session.
421
318
 
422
- ### Examples
319
+ Webhook delivery is not an `auth.api` action. It uses the raw HTTP body to verify the signature.
423
320
 
424
- Create a recurring product:
425
- ```ts
426
- await authClient.adminCreateProduct({
427
- body: {
428
- name: "Pro Monthly",
429
- price: "99.000", // SAR (string preserves halalat precision)
430
- is_one_time: false,
431
- type: "RECURRING", // or "ONE_OFF"
432
- recurring_interval: "MONTH", // WEEK | MONTH | QUARTER | YEAR
433
- recurring_interval_count: 1,
434
- is_price_inclusive_of_vat: true,
435
- },
436
- });
437
- ```
438
- 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`:
439
326
 
440
- Refund a payment:
441
327
  ```ts
442
- await authClient.adminRefundPayment({
443
- params: { id: paymentId },
444
- body: {
445
- refund_reason: "REQUESTED_BY_CUSTOMER", // REQUESTED_BY_CUSTOMER | DUPLICATE | FRAUDULENT | OTHER
446
- refund_note: "optional",
447
- allow_refund_multiple_related_payments: false,
328
+ subscriptions({
329
+ plans,
330
+ authorizeReference: async ({ user, referenceId, referenceType, action }) => {
331
+ return canManageBilling(user, referenceId, referenceType, action);
448
332
  },
449
333
  });
450
334
  ```
451
- Refunds are always full (no `amount` field). Settled payments only — `PENDING`/`CANCELED` → 400 `PAYMENT_INVALID_STATE`.
452
335
 
453
- ### Errors
336
+ Without this callback, cross-account actions return `FORBIDDEN`.
454
337
 
455
- Upstream status propagates: 404 → 404, 422 → 422, 409 → 409, 403 → 403. Network/5xx → 500. Body is `{ code, message }` — `code` is stable (`NOT_FOUND`, `VALIDATION_ERROR`, `PRODUCT_LOCKED`, `COUPON_LOCKED`, …). Branch on `code`.
456
-
457
- ## Webhooks
338
+ ## Admin
458
339
 
459
- Register `https://your-app.com/api/auth/streampay/webhooks` in the StreamPay dashboard.
340
+ `admin()` adds billing actions for payments, subscriptions, freezes, consumers, invoices,
341
+ products, coupons, payment links, and webhook retries.
460
342
 
461
343
  ```ts
462
- webhooks({
463
- secret: process.env.STREAMPAY_WEBHOOK_SECRET!,
464
- toleranceSeconds: 300, // default 300s
465
-
466
- onPayload: async (p) => { /* catch-all, runs first */ },
467
-
468
- onPaymentSucceeded: async (p) => {},
469
- onPaymentFailed: async (p) => {},
470
- onPaymentCanceled: async (p) => {},
471
- onPaymentRefunded: async (p) => {},
472
- onPaymentMarkedAsPaid: async (p) => {},
473
-
474
- onInvoiceCreated: async (p) => {},
475
- onInvoiceSent: async (p) => {},
476
- onInvoiceAccepted: async (p) => {},
477
- onInvoiceRejected: async (p) => {},
478
- onInvoiceCompleted: async (p) => {},
479
- onInvoiceCanceled: async (p) => {},
480
- onInvoiceUpdated: async (p) => {},
481
-
482
- onSubscriptionCreated: async (p) => {},
483
- onSubscriptionActivated: async (p) => {},
484
- onSubscriptionInactivated: async (p) => {},
485
- onSubscriptionCanceled: async (p) => {},
486
- onSubscriptionFrozen: async (p) => {},
487
- onSubscriptionCycleRenewalFailed: async (p) => {},
488
- onSubscriptionCancelAtPeriodEnd: async (p) => {},
489
- onSubscriptionFreezeNow: async (p) => {},
490
- onSubscriptionUnfreezeNow: async (p) => {},
491
- onSubscriptionUnfreezeFuture: async (p) => {},
492
- onSubscriptionFreezeCancel: async (p) => {},
493
-
494
- onPaymentLinkPayAttemptFailed: async (p) => {},
495
- });
496
- ```
344
+ import { admin } from "better-auth-streampay";
497
345
 
498
- ### Payload
499
-
500
- ```ts
501
- interface StreamPayWebhookPayload<T = StreamPayWebhookData> {
502
- event_type: StreamPayEventType;
503
- entity_type: "PAYMENT" | "INVOICE" | "SUBSCRIPTION" | "PAYMENT_LINK";
504
- entity_id: string;
505
- entity_url: string;
506
- status: string;
507
- data: T;
508
- timestamp: string; // ISO 8601
509
- }
346
+ admin({
347
+ adminRoles: ["admin", "billing"],
348
+ isAdmin: async (user) => user.email.endsWith("@example.com"),
349
+ });
510
350
  ```
511
351
 
512
- Each handler is narrowed: `onPaymentSucceeded` only sees `event_type: "PAYMENT_SUCCEEDED"`, etc.
352
+ Calls use names such as:
513
353
 
514
- ### Signature
354
+ - `auth.api.adminListPayments`
355
+ - `auth.api.adminGetSubscription`
356
+ - `auth.api.adminCreateProduct`
357
+ - `auth.api.adminReplayWebhookEvent`
515
358
 
516
- Header: `X-Webhook-Signature: t=<unix>,v1=<hex>` where hex is `HMAC_SHA256(secret, "${t}.${rawBody}")`.
359
+ The IDE shows the body, query, and response types for every action.
517
360
 
518
- ### Rolling rotation
361
+ Make sure your Better Auth route accepts `GET`, `POST`, `PATCH`, `PUT`, and `DELETE`.
519
362
 
520
- ```ts
521
- webhooks({
522
- secret: [
523
- process.env.STREAMPAY_WEBHOOK_SECRET!, // new
524
- process.env.STREAMPAY_WEBHOOK_SECRET_OLD!, // old
525
- ],
526
- });
527
- ```
528
-
529
- Drop the old one once the dashboard is fully cut over.
363
+ ## Webhooks
530
364
 
531
- ## Subscription row
365
+ Register this URL in the StreamPay dashboard:
532
366
 
533
- ```ts
534
- interface Subscription {
535
- id: string;
536
- referenceId: string;
537
- streampaySubscriptionId: string | null;
538
- streampayConsumerId: string | null;
539
- plan: string;
540
- group: string | null;
541
- amountHalalat: number | null;
542
- currency: string | null;
543
- billingInterval: "WEEK" | "MONTH" | "QUARTER" | "YEAR" | null;
544
- billingIntervalCount: number | null;
545
- status: "incomplete" | "active" | "inactive" | "expired" | "canceled" | "frozen" | "past_due";
546
- periodStart: Date | null;
547
- periodEnd: Date | null;
548
- cancelAtPeriodEnd: boolean;
549
- endedAt: Date | null;
550
- frozenAt: Date | null;
551
- freezeEndAt: Date | null;
552
- createdAt: Date;
553
- updatedAt: Date;
554
- }
367
+ ```text
368
+ https://your-app.com/api/auth/streampay/webhooks
555
369
  ```
556
370
 
557
- ## Error codes
371
+ Then add the handlers you need:
558
372
 
559
373
  ```ts
560
- import { $ERROR_CODES, type StreamPayErrorCode } from "better-auth-streampay";
374
+ webhooks({
375
+ secret: process.env.STREAMPAY_WEBHOOK_SECRET!,
561
376
 
562
- if (err.code === $ERROR_CODES.SUBSCRIPTION_ALREADY_ACTIVE.code) {
563
- // ...
564
- }
377
+ onPaymentSucceeded: async (event) => {},
378
+ onPaymentFailed: async (event) => {},
379
+ onSubscriptionActivated: async (event) => {},
380
+ onSubscriptionCanceled: async (event) => {},
381
+ onPayload: async (event) => {},
382
+ });
565
383
  ```
566
384
 
567
- Buckets: `VALIDATION_ERROR`, `UNAUTHORIZED`, `FORBIDDEN`, `NOT_FOUND`, `CONSUMER_DUPLICATE`, `CONSUMER_HAS_ONGOING_ACTIVITY`, `INVOICE_INVALID_STATE`, `PAYMENT_DUPLICATE`, `PAYMENT_INVALID_STATE`, `PAYMENT_ALREADY_REFUNDED`, `PAYMENT_REFUND_FAILED`, `PAYMENT_GATEWAY_DECLINED`, `PAYMENT_GATEWAY_UNAVAILABLE`, `PAYMENT_METHOD_INVALID`, `PRODUCT_LOCKED`, `COUPON_LOCKED`, `SUBSCRIPTION_NOT_FOUND`, `SUBSCRIPTION_PLAN_NOT_FOUND`, `SUBSCRIPTION_ALREADY_ACTIVE`, `SUBSCRIPTION_INVALID_STATE`, `SUBSCRIPTION_FREEZE_NOT_ACTIVE`, `SUBSCRIPTION_REFERENCE_NOT_AUTHORIZED`, `UNKNOWN`.
385
+ The plugin:
568
386
 
569
- `mapToErrorCode(rawCode, status)` maps StreamPay's raw codes onto these buckets.
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
570
392
 
571
- ## Standalone exports
393
+ The StreamPay SDK does not export webhook payload types. This package provides checked event
394
+ types based on StreamPay's documented payloads.
572
395
 
573
- ### Verify webhooks (no plugin)
396
+ To rotate a secret:
574
397
 
575
398
  ```ts
576
- import {
577
- verifyWebhook,
578
- verifyWebhookOrThrow,
579
- StreamPayWebhookError,
580
- } from "better-auth-streampay";
581
-
582
- const result = verifyWebhook({
583
- secret: process.env.STREAMPAY_WEBHOOK_SECRET!,
584
- rawBody,
585
- signatureHeader: req.headers.get("x-webhook-signature"),
586
- toleranceSeconds: 300,
399
+ webhooks({
400
+ secret: [
401
+ process.env.STREAMPAY_WEBHOOK_SECRET!,
402
+ process.env.STREAMPAY_WEBHOOK_SECRET_OLD!,
403
+ ],
587
404
  });
588
-
589
- if (!result.ok) {
590
- // result.reason: MISSING_HEADER | MALFORMED_HEADER | INVALID_TIMESTAMP | EXPIRED | INVALID_SIGNATURE
591
- }
592
405
  ```
593
406
 
594
- ### Dispatch handlers manually
407
+ Remove the old secret after StreamPay uses the new one.
595
408
 
596
- ```ts
597
- import { dispatchWebhook } from "better-auth-streampay";
409
+ ## What owns each job
598
410
 
599
- await dispatchWebhook(payload, {
600
- onPayload: async (p) => {},
601
- onPaymentSucceeded: async (p) => {},
602
- });
603
- ```
411
+ StreamPay owns:
604
412
 
605
- ### Find consumers
413
+ - charges
414
+ - invoices
415
+ - subscription state
416
+ - trials
417
+ - renewal attempts
418
+ - cancellation timing
606
419
 
607
- ```ts
608
- import {
609
- findConsumerByExternalId,
610
- findConsumerByIdentifiers,
611
- } from "better-auth-streampay";
420
+ The plugin owns:
612
421
 
613
- const id = await findConsumerByExternalId(client, { externalId: "user-123" });
422
+ - Better Auth access checks
423
+ - local subscription rows
424
+ - plan features and limits
425
+ - webhook checks and retries
426
+ - checkout recovery
614
427
 
615
- const consumer = await findConsumerByIdentifiers(client, {
616
- email: "user@example.com",
617
- phone_number: "+966501234567",
618
- external_id: "user-123",
619
- iban: "SA...",
620
- });
621
- ```
428
+ Do not edit subscription rows by hand. Let provider responses and webhooks update them.
622
429
 
623
- ### Format / parse SDK errors
430
+ ## Errors
431
+
432
+ Errors use stable codes:
624
433
 
625
434
  ```ts
626
- import { formatStreamPayError, parseStreamPayError } from "better-auth-streampay";
435
+ import { $ERROR_CODES } from "better-auth-streampay";
627
436
 
628
- try {
629
- await client.createConsumer(input);
630
- } catch (err) {
631
- console.error(formatStreamPayError(err));
632
- const { status, code, requestId, validationErrors } = parseStreamPayError(err);
437
+ if (error.code === $ERROR_CODES.SUBSCRIPTION_ALREADY_ACTIVE.code) {
438
+ // Show the current plan.
633
439
  }
634
440
  ```
635
441
 
636
- ### Money
442
+ Common codes include:
637
443
 
638
- ```ts
639
- import { StreamPayAmount } from "better-auth-streampay";
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`
640
451
 
641
- StreamPayAmount.toHalalat("99.00"); // 9900
642
- StreamPayAmount.toSAR(9900); // "99.00"
643
- ```
644
-
645
- ### Event-type constants
452
+ ## Useful exports
646
453
 
647
454
  ```ts
648
455
  import {
649
- STREAMPAY_EVENT_TYPES,
650
- STREAMPAY_PAYMENT_EVENT_TYPES,
651
- STREAMPAY_INVOICE_EVENT_TYPES,
652
- STREAMPAY_SUBSCRIPTION_EVENT_TYPES,
653
- STREAMPAY_PAYMENT_LINK_EVENT_TYPES,
654
- type StreamPayEventType,
655
- type StreamPayEntityType,
656
- type StreamPayWebhookPayload,
657
- type WebhookHandler,
658
- type WebhookHandlers,
456
+ StreamPayAmount,
457
+ checkLimit,
458
+ findConsumerByExternalId,
459
+ formatStreamPayError,
460
+ hasFeature,
461
+ parseStreamPayError,
462
+ verifyWebhook,
659
463
  } from "better-auth-streampay";
660
464
  ```
661
465
 
662
- ### Subscription helpers
663
-
664
- ```ts
665
- import { hasFeature, checkLimit, subscriptionSchema } from "better-auth-streampay";
666
-
667
- const allowed = hasFeature(row, plan, "ai_calls");
668
- const quota = checkLimit(row, plan, "seats", 8); // { allowed, limit, remaining }
669
- ```
670
-
671
- ## Endpoints summary
672
-
673
- | Key | Method | Path | Auth | Plugin |
674
- | ------------------------- | ------ | ---------------------------------- | --------- | ----------------- |
675
- | `checkout` | POST | `/checkout` | Optional | `checkout()` |
676
- | `state` | GET | `/consumer/state` | Required | `portal()` |
677
- | `subscriptions` | GET | `/consumer/subscriptions/list` | Required | `portal()` |
678
- | `invoices` | GET | `/consumer/invoices/list` | Required | `portal()` |
679
- | `upgradeSubscription` | POST | `/subscription/upgrade` | Required | `subscriptions()` |
680
- | `subscriptionSuccess` | GET | `/subscription/success` | Required | `subscriptions()` |
681
- | `cancelSubscription` | POST | `/subscription/cancel` | Required | `subscriptions()` |
682
- | `changeSubscriptionPlan` | POST | `/subscription/change-plan` | Required | `subscriptions()` |
683
- | `freezeSubscription` | POST | `/subscription/freeze` | Required | `subscriptions()` |
684
- | `unfreezeSubscription` | POST | `/subscription/unfreeze` | Required | `subscriptions()` |
685
- | `listSubscriptions` | GET | `/subscription/list` | Required | `subscriptions()` |
686
- | `currentSubscription` | GET | `/subscription/current` | Required | `subscriptions()` |
687
- | `hasSubscriptionFeature` | GET | `/subscription/has-feature` | Required | `subscriptions()` |
688
- | `checkSubscriptionLimit` | GET | `/subscription/check-limit` | Required | `subscriptions()` |
689
- | `streampayWebhooks` | POST | `/streampay/webhooks` | Signature | `webhooks()` |
690
- | `admin*` | varied | `/admin/streampay/...` | Role | `admin()` |
691
-
692
- ## Scripts
693
-
694
- ```bash
695
- pnpm test # vitest
696
- pnpm typecheck # tsc --noEmit
697
- pnpm lint # biome check
698
- pnpm build # tsup (ESM + CJS)
699
- ```
700
-
701
466
  ## License
702
467
 
703
468
  MIT