better-auth-streampay 1.3.0 → 2.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -1,94 +1,112 @@
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
+ `streampayConsumerId` is unique. Before applying the generated unique index to an existing
106
+ database, resolve any duplicate non-null consumer IDs. Checkout fails closed when a consumer link
107
+ cannot be stored safely.
108
+
109
+ ## Client setup
92
110
 
93
111
  ```ts
94
112
  import { createAuthClient } from "better-auth/react";
@@ -99,130 +117,128 @@ export const authClient = createAuthClient({
99
117
  });
100
118
  ```
101
119
 
102
- ## Database migration
120
+ Use the matching Better Auth client for Vue, Svelte, or Solid.
103
121
 
104
- Adds a `streampayConsumerId` column on `user`, plus `subscription` and `streampayWebhookEvent` tables when `subscriptions()` is in `use`.
122
+ ## Consumers
105
123
 
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
- ```
124
+ By default, the plugin creates a StreamPay consumer when the user first needs one. This keeps a
125
+ StreamPay outage from blocking sign-up.
111
126
 
112
- ## `streampay()` options
127
+ To create the consumer during sign-up:
113
128
 
114
129
  ```ts
115
130
  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 */],
131
+ client: streamPayClient,
132
+ createConsumerOnSignUp: true,
133
+ use: [],
128
134
  });
129
135
  ```
130
136
 
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
139
-
140
- `claimExistingConsumerBy` controls reuse when StreamPay returns `DUPLICATE_CONSUMER`:
137
+ To reuse an existing StreamPay consumer after a verified email match:
141
138
 
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. |
139
+ ```ts
140
+ streampay({
141
+ client: streamPayClient,
142
+ createConsumerOnSignUp: true,
143
+ claimExistingConsumerBy: ["email"],
144
+ use: [],
145
+ });
146
+ ```
148
147
 
149
- If reused, the plugin rewrites `external_id` to the new user id.
148
+ Only enable reuse when your app verifies the matching email or phone number.
150
149
 
151
150
  ## Checkout
152
151
 
153
152
  ```ts
154
153
  checkout({
155
- products: [{ productId: "aaaa-bbbb-cccc-dddd", slug: "pro" }],
156
- successUrl: "/dashboard?checkout=success",
157
- failureUrl: "/dashboard?checkout=failure",
154
+ products: [
155
+ { slug: "starter", productId: "product-id" },
156
+ ],
157
+ successUrl: "/billing/success",
158
+ failureUrl: "/billing/failed",
158
159
  authenticatedUsersOnly: true,
159
- contactInformationType: "EMAIL", // or "PHONE"
160
- customFields: { source: "website" },
161
160
  });
162
161
  ```
163
162
 
164
- `products` can be a static array or a `() => Promise<StreamPayProduct[]>` factory.
165
-
166
- ### Client
163
+ Open checkout:
167
164
 
168
165
  ```ts
169
- // By slug
170
- const { data } = await authClient.checkout({ slug: "pro" });
166
+ const { data } = await authClient.checkout({
167
+ slug: "starter",
168
+ redirect: false,
169
+ });
170
+
171
171
  window.location.href = data.url;
172
+ ```
172
173
 
173
- // By UUID
174
- await authClient.checkout({ products: "aaaa-bbbb-cccc-dddd" });
174
+ You can also pass StreamPay product IDs directly with `products`.
175
175
 
176
- // Multiple products + quantity
177
- await authClient.checkout({
178
- products: [{ productId: "aaaa-bbbb-cccc-dddd", quantity: 2 }],
179
- });
176
+ ### Server-authoritative checkout
180
177
 
181
- // With reference id and metadata
182
- await authClient.checkout({
183
- slug: "pro",
184
- referenceId: organizationId,
185
- metadata: { campaign: "spring-sale" },
178
+ For a store, derive product IDs, quantities, coupons, expiry, and redirect URLs on the server:
179
+
180
+ ```ts
181
+ import { APIError } from "better-auth/api";
182
+
183
+ checkout({
184
+ authenticatedUsersOnly: true,
185
+
186
+ resolveCheckout: async ({ user, body }) => {
187
+ const order = await loadAuthorizedOrder(user?.id, body.referenceId);
188
+ if (!order) {
189
+ throw new APIError("FORBIDDEN", {
190
+ code: "ORDER_NOT_AVAILABLE",
191
+ message: "This order is not available for checkout.",
192
+ });
193
+ }
194
+
195
+ return {
196
+ products: [{ productId: order.productId, quantity: order.quantity }],
197
+ successUrl: `https://shop.example.com/orders/${order.id}?checkout=success`,
198
+ failureUrl: `https://shop.example.com/orders/${order.id}?checkout=failed`,
199
+ maxNumberOfPayments: 1,
200
+ validUntil: order.validUntil,
201
+ metadata: { flow: "store" },
202
+ };
203
+ },
204
+
205
+ onCheckoutCreated: async ({ referenceId, paymentLinkId, payload }) => {
206
+ await saveOrderPaymentLink({ referenceId, paymentLinkId, payload });
207
+ },
186
208
  });
187
209
  ```
188
210
 
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
211
+ The client then sends only app-owned reference data:
207
212
 
208
213
  ```ts
209
- portal(); // default page size 100 (StreamPay's max)
210
- portal({ pageSize: 50 });
214
+ await authClient.checkout({ referenceId: order.id, redirect: false });
211
215
  ```
212
216
 
213
- Reads are scoped to the session user via `organization_consumer_id`. One API call per read.
217
+ Configuring `resolveCheckout` automatically makes product, pricing, coupon, expiry, metadata, and
218
+ redirect URL fields server-only. Requests that include those fields are rejected; without a
219
+ resolver, the existing client-driven checkout behavior is unchanged.
214
220
 
215
- ```ts
216
- const { data } = await authClient.state();
217
- if (!data.hasConsumer) {
218
- // user has no StreamPay consumer yet
219
- }
221
+ Invalid values returned by `resolveCheckout` produce a generic 500 response. Validation details are
222
+ written to the server log without echoing the invalid values to the client.
220
223
 
221
- const subs = await authClient.subscriptions(); // { hasConsumer, data }
222
- const invoices = await authClient.invoices(); // { hasConsumer, data }
223
- ```
224
+ If `onCheckoutCreated` throws, checkout returns an error and the plugin attempts to deactivate the
225
+ new payment link. Deactivation is best effort, so webhook handling should still reconcile unexpected
226
+ links. Relative success and failure URLs resolve against the auth server; use absolute URLs when the
227
+ storefront has a different origin.
228
+
229
+ ## Billing portal
230
+
231
+ `portal()` adds three signed-in user actions:
232
+
233
+ - `state`
234
+ - `subscriptions`
235
+ - `invoices`
224
236
 
225
- When `hasConsumer` is `false`, reads return `200 OK` with `data: []` (or `consumer: null`) instead of 404.
237
+ ```ts
238
+ const state = await authClient.consumer.state();
239
+ const subscriptions = await authClient.consumer.subscriptions.list();
240
+ const invoices = await authClient.consumer.invoices.list();
241
+ ```
226
242
 
227
243
  ## Subscriptions
228
244
 
@@ -230,474 +246,280 @@ When `hasConsumer` is `false`, reads return `200 OK` with `data: []` (or `consum
230
246
  subscriptions({
231
247
  plans: [
232
248
  {
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
249
+ name: "pro-monthly",
250
+ productId: "product-id",
251
+ priceInSmallestUnit: 9900,
252
+ currency: "SAR",
253
+ billingInterval: "MONTH",
254
+ billingIntervalCount: 1,
255
+ trialPeriodDays: 7,
256
+ group: "main",
257
+ limits: { seats: 10, reports: true },
240
258
  },
241
259
  ],
242
- // or a factory: plans: async () => fetchPlansFromCMS(),
243
260
 
244
- authorizeReference: async ({ user, referenceId, action }) => {
245
- return user.role === "admin";
261
+ onSubscriptionActivated: async ({ subscription, user }) => {
262
+ // Run app-specific work here.
246
263
  },
264
+ });
265
+ ```
266
+
267
+ Plan names and product IDs must be unique. Prices use the smallest currency unit. For SAR,
268
+ `9900` means `99.00 SAR`.
247
269
 
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) => {},
270
+ The plugin gives one trial per user and plan group by default. Use `isTrialEligible` when your
271
+ app needs a stricter or more flexible rule.
272
+
273
+ ### Start checkout
274
+
275
+ ```ts
276
+ const { data } = await authClient.subscription.upgrade({
277
+ plan: "pro-monthly",
259
278
  });
279
+
280
+ window.location.href = data.url;
260
281
  ```
261
282
 
262
- Each callback receives `{ subscription, user, streampaySubscription, event }`.
283
+ On the success page:
263
284
 
264
- ### Endpoints
285
+ ```ts
286
+ await authClient.subscription.success({
287
+ query: { subscriptionId: data.subscriptionId },
288
+ });
289
+ ```
265
290
 
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 }` |
291
+ Then refresh the subscription data used by your UI.
278
292
 
279
- ### Client
293
+ ### Manage a subscription
280
294
 
281
295
  ```ts
282
- const { data } = await authClient.upgradeSubscription({ plan: "pro" });
283
- window.location.href = data.url;
296
+ await authClient.subscription.changePlan({
297
+ subscriptionId,
298
+ plan: "pro-yearly",
299
+ });
284
300
 
285
- // On success page:
286
- await authClient.subscriptionSuccess({ subscriptionId: data.subscriptionId });
301
+ await authClient.subscription.changePlan.cancel({ subscriptionId });
287
302
 
288
- // Cancel at period end (keeps access until periodEnd)
289
- await authClient.cancelSubscription({
303
+ await authClient.subscription.cancel({
290
304
  subscriptionId,
291
305
  cancelAtPeriodEnd: true,
292
306
  });
293
307
 
294
- // Plan change — immediate (PATCH items, no proration)
295
- await authClient.changeSubscriptionPlan({ plan: "pro_plus", mode: "immediate" });
308
+ await authClient.subscription.uncancel({ subscriptionId });
309
+ ```
310
+
311
+ StreamPay cancels an active subscription at the end of its current period. Trial and inactive
312
+ subscriptions are canceled at once.
296
313
 
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;
314
+ ### Freeze a subscription
300
315
 
301
- // Freeze
302
- await authClient.freezeSubscription({
316
+ ```ts
317
+ const { data: freeze } = await authClient.subscription.freeze({
303
318
  subscriptionId,
304
319
  freezeStartDatetime: new Date().toISOString(),
305
320
  freezeEndDatetime: null,
306
321
  });
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
-
315
- ### Status values
316
322
 
317
- `incomplete | active | inactive | expired | canceled | frozen | past_due`
323
+ await authClient.subscription.unfreeze({ subscriptionId });
318
324
 
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.
325
+ await authClient.subscription.freeze.cancel({
326
+ subscriptionId,
327
+ freezeId: freeze.id!,
328
+ });
329
+ ```
330
330
 
331
- - `incomplete` — row pre-created at `/upgrade`, webhook not landed yet.
332
- - `past_due` — renewal failed. StreamPay keeps `ACTIVE` during dunning; we don't.
331
+ ### Read access and limits
333
332
 
334
- ### Cross-account access
333
+ ```ts
334
+ const current = await authClient.subscription.current({
335
+ query: { group: "main" },
336
+ });
335
337
 
336
- By default `referenceId` is the session user's id. Pass a different one and `authorizeReference` is called:
338
+ const feature = await authClient.subscription.hasFeature({
339
+ query: { feature: "reports", group: "main" },
340
+ });
337
341
 
338
- ```ts
339
- authorizeReference: async ({ user, referenceId, action }, ctx) => {
340
- // action: "upgrade" | "cancel" | "freeze" | "unfreeze" | "read" | "change-plan"
341
- return user.role === "admin";
342
- },
342
+ const seats = await authClient.subscription.checkLimit({
343
+ query: { feature: "seats", count: 4, group: "main" },
344
+ });
343
345
  ```
344
346
 
345
- Without `authorizeReference`, cross-account ops throw `FORBIDDEN`.
347
+ Pass `group` for grouped plans. Leave it out only for a plan without a group.
346
348
 
347
- ### Webhook auto-sync
349
+ By default, `active`, `trialing`, `frozen`, and `past_due` subscriptions can use plan
350
+ features. Change this with `accessStatuses`.
348
351
 
349
- If both `subscriptions()` and `webhooks()` are in `use`, the plugin runs an idempotent sync **before** your handlers:
352
+ ## Server-side calls
350
353
 
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.
354
+ Every checkout, portal, subscription, and admin action is also available on `auth.api`. Types
355
+ come from Better Auth.
355
356
 
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.
357
+ Browser calls follow the route path, such as `authClient.subscription.cancel`. Server calls use
358
+ the endpoint name, such as `auth.api.cancelSubscription`.
359
359
 
360
360
  ```ts
361
- admin({
362
- adminRoles: ["admin", "billing_ops"],
363
- isAdmin: async (user, ctx) => user.email.endsWith("@yourco.com"),
361
+ import { headers } from "next/headers";
364
362
 
365
- onRefund: async ({ user, paymentId, request }) => { /* throw to block */ },
366
- onPlanChange: async ({ user, subscriptionId, current, patch }) => { /* throw to block */ },
363
+ const current = await auth.api.currentSubscription({
364
+ query: { group: "main" },
365
+ headers: await headers(),
367
366
  });
368
- ```
369
367
 
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 },
368
+ await auth.api.cancelSubscription({
369
+ body: { subscriptionId, cancelAtPeriodEnd: true },
413
370
  headers: await headers(),
414
371
  });
415
372
  ```
416
373
 
417
- Client (`authClient.*` — auto-generated, cookie auto-sent, gate runs on server):
418
- ```ts
419
- await authClient.adminListProducts({ query: { page: 1, size: 20 } });
420
- ```
374
+ Pass the request headers so Better Auth can read the session.
421
375
 
422
- ### Examples
376
+ Webhook delivery is not an `auth.api` action. It uses the raw HTTP body to verify the signature.
423
377
 
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`.
378
+ ## Cross-account access
379
+
380
+ User actions use the signed-in user's ID by default.
381
+
382
+ To manage an organization or another app-owned reference, add `authorizeReference`:
439
383
 
440
- Refund a payment:
441
384
  ```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,
385
+ subscriptions({
386
+ plans,
387
+ authorizeReference: async ({ user, referenceId, referenceType, action }) => {
388
+ return canManageBilling(user, referenceId, referenceType, action);
448
389
  },
449
390
  });
450
391
  ```
451
- Refunds are always full (no `amount` field). Settled payments only — `PENDING`/`CANCELED` → 400 `PAYMENT_INVALID_STATE`.
452
392
 
453
- ### Errors
393
+ Without this callback, cross-account actions return `FORBIDDEN`.
454
394
 
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
395
+ ## Admin
458
396
 
459
- Register `https://your-app.com/api/auth/streampay/webhooks` in the StreamPay dashboard.
397
+ `admin()` adds billing actions for payments, subscriptions, freezes, consumers, invoices,
398
+ products, coupons, payment links, and webhook retries.
460
399
 
461
400
  ```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
- ```
497
-
498
- ### Payload
401
+ import { admin } from "better-auth-streampay";
499
402
 
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
- }
403
+ admin({
404
+ adminRoles: ["admin", "billing"],
405
+ isAdmin: async (user) => user.email.endsWith("@example.com"),
406
+ });
510
407
  ```
511
408
 
512
- Each handler is narrowed: `onPaymentSucceeded` only sees `event_type: "PAYMENT_SUCCEEDED"`, etc.
513
-
514
- ### Signature
409
+ Calls use names such as:
515
410
 
516
- Header: `X-Webhook-Signature: t=<unix>,v1=<hex>` where hex is `HMAC_SHA256(secret, "${t}.${rawBody}")`.
411
+ - `auth.api.adminListPayments`
412
+ - `auth.api.adminGetSubscription`
413
+ - `auth.api.adminCreateProduct`
414
+ - `auth.api.adminReplayWebhookEvent`
517
415
 
518
- ### Rolling rotation
416
+ The IDE shows the body, query, and response types for every action.
519
417
 
520
- ```ts
521
- webhooks({
522
- secret: [
523
- process.env.STREAMPAY_WEBHOOK_SECRET!, // new
524
- process.env.STREAMPAY_WEBHOOK_SECRET_OLD!, // old
525
- ],
526
- });
527
- ```
418
+ Make sure your Better Auth route accepts `GET`, `POST`, `PATCH`, `PUT`, and `DELETE`.
528
419
 
529
- Drop the old one once the dashboard is fully cut over.
420
+ ## Webhooks
530
421
 
531
- ## Subscription row
422
+ Register this URL in the StreamPay dashboard:
532
423
 
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
- }
424
+ ```text
425
+ https://your-app.com/api/auth/streampay/webhooks
555
426
  ```
556
427
 
557
- ## Error codes
428
+ Then add the handlers you need:
558
429
 
559
430
  ```ts
560
- import { $ERROR_CODES, type StreamPayErrorCode } from "better-auth-streampay";
431
+ webhooks({
432
+ secret: process.env.STREAMPAY_WEBHOOK_SECRET!,
561
433
 
562
- if (err.code === $ERROR_CODES.SUBSCRIPTION_ALREADY_ACTIVE.code) {
563
- // ...
564
- }
434
+ onPaymentSucceeded: async (event) => {},
435
+ onPaymentFailed: async (event) => {},
436
+ onSubscriptionActivated: async (event) => {},
437
+ onSubscriptionCanceled: async (event) => {},
438
+ onPayload: async (event) => {},
439
+ });
565
440
  ```
566
441
 
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`.
442
+ The plugin:
568
443
 
569
- `mapToErrorCode(rawCode, status)` maps StreamPay's raw codes onto these buckets.
444
+ - checks the webhook signature
445
+ - rejects old signatures
446
+ - deduplicates subscription sync and lifecycle callbacks
447
+ - retries temporary failures
448
+ - stores failed subscription events for admin replay
570
449
 
571
- ## Standalone exports
450
+ The StreamPay SDK does not export webhook payload types. This package provides checked event
451
+ types based on StreamPay's documented payloads.
572
452
 
573
- ### Verify webhooks (no plugin)
453
+ To rotate a secret:
574
454
 
575
455
  ```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,
456
+ webhooks({
457
+ secret: [
458
+ process.env.STREAMPAY_WEBHOOK_SECRET!,
459
+ process.env.STREAMPAY_WEBHOOK_SECRET_OLD!,
460
+ ],
587
461
  });
588
-
589
- if (!result.ok) {
590
- // result.reason: MISSING_HEADER | MALFORMED_HEADER | INVALID_TIMESTAMP | EXPIRED | INVALID_SIGNATURE
591
- }
592
462
  ```
593
463
 
594
- ### Dispatch handlers manually
464
+ Remove the old secret after StreamPay uses the new one.
595
465
 
596
- ```ts
597
- import { dispatchWebhook } from "better-auth-streampay";
466
+ ## What owns each job
598
467
 
599
- await dispatchWebhook(payload, {
600
- onPayload: async (p) => {},
601
- onPaymentSucceeded: async (p) => {},
602
- });
603
- ```
468
+ StreamPay owns:
604
469
 
605
- ### Find consumers
470
+ - charges
471
+ - invoices
472
+ - subscription state
473
+ - trials
474
+ - renewal attempts
475
+ - cancellation timing
606
476
 
607
- ```ts
608
- import {
609
- findConsumerByExternalId,
610
- findConsumerByIdentifiers,
611
- } from "better-auth-streampay";
477
+ The plugin owns:
612
478
 
613
- const id = await findConsumerByExternalId(client, { externalId: "user-123" });
479
+ - Better Auth access checks
480
+ - local subscription rows
481
+ - plan features and limits
482
+ - webhook checks and retries
483
+ - checkout recovery
614
484
 
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
- ```
485
+ Do not edit subscription rows by hand. Let provider responses and webhooks update them.
622
486
 
623
- ### Format / parse SDK errors
487
+ ## Errors
488
+
489
+ Errors use stable codes:
624
490
 
625
491
  ```ts
626
- import { formatStreamPayError, parseStreamPayError } from "better-auth-streampay";
492
+ import { $ERROR_CODES } from "better-auth-streampay";
627
493
 
628
- try {
629
- await client.createConsumer(input);
630
- } catch (err) {
631
- console.error(formatStreamPayError(err));
632
- const { status, code, requestId, validationErrors } = parseStreamPayError(err);
494
+ if (error.code === $ERROR_CODES.SUBSCRIPTION_ALREADY_ACTIVE.code) {
495
+ // Show the current plan.
633
496
  }
634
497
  ```
635
498
 
636
- ### Money
499
+ Common codes include:
637
500
 
638
- ```ts
639
- import { StreamPayAmount } from "better-auth-streampay";
501
+ - `VALIDATION_ERROR`
502
+ - `FORBIDDEN`
503
+ - `NOT_FOUND`
504
+ - `SUBSCRIPTION_ALREADY_ACTIVE`
505
+ - `SUBSCRIPTION_INVALID_STATE`
506
+ - `SUBSCRIPTION_PLAN_CHANGE_ALREADY_SCHEDULED`
507
+ - `WEBHOOK_REPLAY_IN_PROGRESS`
640
508
 
641
- StreamPayAmount.toHalalat("99.00"); // 9900
642
- StreamPayAmount.toSAR(9900); // "99.00"
643
- ```
644
-
645
- ### Event-type constants
509
+ ## Useful exports
646
510
 
647
511
  ```ts
648
512
  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,
513
+ StreamPayAmount,
514
+ checkLimit,
515
+ findConsumerByExternalId,
516
+ formatStreamPayError,
517
+ hasFeature,
518
+ parseStreamPayError,
519
+ verifyWebhook,
659
520
  } from "better-auth-streampay";
660
521
  ```
661
522
 
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
523
  ## License
702
524
 
703
525
  MIT