better-auth-streampay 1.0.0 → 1.1.5

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,48 +1,40 @@
1
1
  # better-auth-streampay
2
2
 
3
- > **Community plugin — not affiliated with Stream or StreamPay.** For plugin bugs, [open an issue here](https://github.com/Genie-sa/better-auth-streampay/issues). For StreamPay bugs, contact [Stream support](https://streampay.sa).
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).
4
5
 
5
- A [Better Auth](https://better-auth.com) plugin for integrating [StreamPay](https://streampay.sa) payments and subscriptions into your authentication flow.
6
+ [Better Auth](https://better-auth.com) plugin for [StreamPay](https://streampay.sa).
6
7
 
7
8
  ## Features
8
9
 
9
- - Checkout Integration (lazy-creates a StreamPay consumer on first payment)
10
- - Consumer Portal (subscriptions, invoices, payments)
11
- - Subscription Management (cancel, freeze)
12
- - Optional eager consumer creation on signup (`createConsumerOnSignUp: true`)
13
- - Handle StreamPay Webhooks securely with HMAC-SHA256 signature verification
14
- - Consumer sync on user update/delete (when eager mode is on)
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
15
17
 
16
- ## Installation
18
+ ## Install
17
19
 
18
20
  ```bash
19
- pnpm add better-auth-streampay @streamsdk/typescript better-auth
21
+ pnpm add better-auth-streampay @streamsdk/typescript better-auth zod
20
22
  ```
21
23
 
22
- Peer dependencies: `@streamsdk/typescript`, `better-auth`, `zod` (`^3.24` or `^4.0`).
24
+ Peers: `better-auth ^1.4`, `@streamsdk/typescript ^1.0.6`, `zod ^3.24 || ^4`.
23
25
 
24
- ## Preparation
25
-
26
- Get your API credentials from the [StreamPay dashboard](https://streampay.sa). The API key is a Base64-encoded `apiKey:apiSecret` pair. Add it to your environment:
26
+ ## Env
27
27
 
28
28
  ```bash
29
- # .env
30
29
  STREAMPAY_API_KEY=...
31
- STREAMPAY_WEBHOOK_SECRET=... # Only if using webhooks()
32
- BETTER_AUTH_SECRET=... # Session signing secret (min 32 chars)
33
- BETTER_AUTH_URL=... # Your app's public URL (required in prod)
30
+ STREAMPAY_WEBHOOK_SECRET=...
31
+ BETTER_AUTH_SECRET=...
32
+ BETTER_AUTH_URL=...
34
33
  ```
35
34
 
36
- ## Server Setup
37
-
38
- The StreamPay plugin comes with a handful of sub-plugins that add functionality to your stack:
35
+ ## Server
39
36
 
40
- - **Checkout** — Enables a seamless checkout integration via payment links
41
- - **Portal** — Lets your customers view their subscriptions, invoices, and payments
42
- - **Subscriptions** — Manage subscriptions (cancel, freeze)
43
- - **Webhooks** — Listen for StreamPay webhooks with signature verification
44
-
45
- ```typescript
37
+ ```ts
46
38
  import { betterAuth } from "better-auth";
47
39
  import StreamSDK from "@streamsdk/typescript";
48
40
  import {
@@ -51,46 +43,45 @@ import {
51
43
  portal,
52
44
  subscriptions,
53
45
  webhooks,
46
+ admin,
54
47
  } from "better-auth-streampay";
55
48
 
56
- const streamPayClient = StreamSDK.init(process.env.STREAMPAY_API_KEY!);
49
+ const client = StreamSDK.init(process.env.STREAMPAY_API_KEY!);
57
50
 
58
- const auth = betterAuth({
51
+ export const auth = betterAuth({
59
52
  plugins: [
60
53
  streampay({
61
- client: streamPayClient,
62
- // createConsumerOnSignUp defaults to false: consumers are created
63
- // lazily at first checkout or subscription mutation. Set to `true`
64
- // to provision a StreamPay consumer at signup instead.
54
+ client,
65
55
  use: [
66
56
  checkout({
67
- products: [
68
- { productId: "aaaa-bbbb-cccc-dddd", slug: "pro" },
69
- ],
57
+ products: [{ productId: "aaaa-bbbb-cccc-dddd", slug: "pro" }],
70
58
  successUrl: "/dashboard?checkout=success",
71
59
  failureUrl: "/dashboard?checkout=failure",
72
60
  authenticatedUsersOnly: true,
73
61
  }),
74
62
  portal(),
75
- subscriptions(),
76
- webhooks({
77
- secret: process.env.STREAMPAY_WEBHOOK_SECRET!,
78
- onPaymentSucceeded: async (payload) => {
79
- // provision access
80
- },
81
- onSubscriptionCanceled: async (payload) => {
82
- // revoke access
83
- },
63
+ subscriptions({
64
+ plans: [
65
+ {
66
+ name: "pro",
67
+ productId: "prod_recurring_uuid",
68
+ priceHalalat: 9900,
69
+ billingInterval: "MONTH",
70
+ limits: { seats: 10 },
71
+ },
72
+ ],
84
73
  }),
74
+ webhooks({ secret: process.env.STREAMPAY_WEBHOOK_SECRET! }),
75
+ admin(),
85
76
  ],
86
77
  }),
87
78
  ],
88
79
  });
89
80
  ```
90
81
 
91
- ## Client Setup
82
+ ## Client
92
83
 
93
- ```typescript
84
+ ```ts
94
85
  import { createAuthClient } from "better-auth/react";
95
86
  import { streampayClient } from "better-auth-streampay/client";
96
87
 
@@ -99,351 +90,508 @@ export const authClient = createAuthClient({
99
90
  });
100
91
  ```
101
92
 
102
- ## Database Migration
93
+ ## Database migration
103
94
 
104
- The plugin adds a `streampayConsumerId` column to the `user` table. Run your migration after installing:
95
+ Adds a `streampayConsumerId` column on `user`, plus `subscription` and `streampayWebhookEvent` tables when `subscriptions()` is in `use`.
105
96
 
106
97
  ```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
98
+ npx @better-auth/cli migrate # Better Auth CLI
99
+ npx drizzle-kit generate && npx drizzle-kit migrate # Drizzle
100
+ npx prisma migrate dev # Prisma
110
101
  ```
111
102
 
112
- ## Configuration Options
113
-
114
- ### Required
115
-
116
- | Option | Type | Description |
117
- | -------- | ----------------- | ----------------------------- |
118
- | `client` | `StreamPayClient` | Initialized StreamPay SDK client |
119
- | `use` | `StreamPayPlugin[]` | Sub-plugins to compose |
120
-
121
- ### Optional
122
-
123
- | Option | Type | Description |
124
- | ------------------------- | ---------- | ------------------------------------------------------------------ |
125
- | `createConsumerOnSignUp` | `boolean` | Create a StreamPay consumer eagerly at signup. Default: `false` (lazy — consumer is created on first checkout / subscription mutation). |
126
- | `claimExistingConsumerBy` | `("email" \| "phone")[]` | Reclaim a duplicate linked consumer by the listed identifier(s) |
127
- | `getConsumerCreateParams` | `function` | Provide additional consumer fields (phone, language, IBAN, etc.) |
128
-
129
- ### Consumers
130
-
131
- **Lazy by default (`createConsumerOnSignUp: false`).** A StreamPay Consumer is created on demand the first time an authenticated user hits `/checkout` or a subscription mutation — not at signup. This keeps the signup hot path off StreamPay and the consumer table free of users who never pay. It matches the convention used by every other Better Auth billing plugin (Stripe, Polar, Dodo Payments).
132
-
133
- **Eager opt-in (`createConsumerOnSignUp: true`).** Set the flag to `true` to provision a StreamPay Consumer inside the signup transaction — useful when your product needs portal data (invoices, subscriptions) immediately after signup. The `before` hook aborts signup if StreamPay rejects, keeping the two systems atomic.
134
-
135
- All consumers — lazy or eager — are created with `external_id` matching the user's database ID, so no mapping table is needed. The resulting consumer ID is stored as `streampayConsumerId` on the user row.
103
+ ## `streampay()` options
136
104
 
137
- If StreamPay rejects with `DUPLICATE_CONSUMER`, the plugin normally reuses only stranded consumers whose `external_id` is empty. If you set `claimExistingConsumerBy`, the plugin can also reuse an existing consumer that matches one of the listed identifiers even if it is already linked to a different `external_id`. The `after` hook then rewrites that `external_id` to the new Better Auth user id.
138
-
139
- Claim modes:
140
- - omitted / `[]` — only reuse stranded consumers
141
- - `["email"]` — reclaim duplicates that match the same email
142
- - `["phone"]` — reclaim duplicates that match the same phone number
143
- - `["email", "phone"]` — reclaim duplicates that match either email or phone
144
-
145
- > **Breaking in 0.2.0:** `claimExistingConsumerBy` now takes an array. Replace `"email"` → `["email"]`, `"phone"` → `["phone"]`, `"both"` → `["email", "phone"]`. `null` is no longer accepted — omit the option or pass `[]` to disable.
146
-
147
- Consumer data is kept in sync for any user with a linked `streampayConsumerId` — independent of `createConsumerOnSignUp`:
148
- - **User update** — name/email changes are synced to StreamPay
149
- - **User delete** — the StreamPay consumer is deleted
150
-
151
- Users with no linked consumer (pre-first-payment in lazy mode, legacy pre-schema users) are skipped cheaply — there is no list-scan on the user-update hot path.
152
-
153
- #### Custom Consumer Fields
154
-
155
- ```typescript
105
+ ```ts
156
106
  streampay({
157
- client: streamPayClient,
158
- createConsumerOnSignUp: true, // opt into eager mode
107
+ client,
108
+ // Eagerly create a consumer at signup. Default: false (lazy).
109
+ createConsumerOnSignUp: false,
110
+ // Reclaim duplicates by matching identifier(s).
159
111
  claimExistingConsumerBy: ["email", "phone"],
160
- getConsumerCreateParams: async ({ user }, request) => ({
112
+ // Extra fields passed to `client.createConsumer`.
113
+ getConsumerCreateParams: async ({ user }) => ({
161
114
  phone_number: "+966501234567",
162
- preferred_language: "ar",
115
+ preferred_language: "AR",
163
116
  communication_methods: ["WHATSAPP", "EMAIL"],
164
117
  }),
165
- use: [...],
118
+ use: [/* sub-plugins */],
166
119
  });
167
120
  ```
168
121
 
169
- `getConsumerCreateParams` also runs during lazy provisioning at checkout, so it applies in both modes.
122
+ ### Consumer lifecycle
123
+
124
+ - **Lazy** (default) — consumer created on first `/checkout` or subscription mutation.
125
+ - **Eager** (`createConsumerOnSignUp: true`) — consumer created inside the signup transaction. Signup aborts if StreamPay rejects.
126
+ - All consumers get `external_id = user.id`. The id is stored on `user.streampayConsumerId`.
127
+ - On user update → name/email synced to StreamPay. On user delete → consumer deleted. Users with no link are skipped cheap.
170
128
 
171
- ## Checkout Plugin
129
+ ### Duplicate handling
172
130
 
173
- ```typescript
131
+ `claimExistingConsumerBy` controls reuse when StreamPay returns `DUPLICATE_CONSUMER`:
132
+
133
+ | Value | Behavior |
134
+ | -------------------- | ------------------------------------------------------------------- |
135
+ | omitted / `[]` | Reuse only stranded consumers (no `external_id`). |
136
+ | `["email"]` | Also reuse consumers matching the same email. |
137
+ | `["phone"]` | Also reuse consumers matching the same phone. |
138
+ | `["email","phone"]` | Reuse on either match. |
139
+
140
+ If reused, the plugin rewrites `external_id` to the new user id.
141
+
142
+ ## Checkout
143
+
144
+ ```ts
174
145
  checkout({
175
146
  products: [{ productId: "aaaa-bbbb-cccc-dddd", slug: "pro" }],
176
147
  successUrl: "/dashboard?checkout=success",
177
148
  failureUrl: "/dashboard?checkout=failure",
178
149
  authenticatedUsersOnly: true,
179
- contactInformationType: "EMAIL",
150
+ contactInformationType: "EMAIL", // or "PHONE"
180
151
  customFields: { source: "website" },
181
152
  });
182
153
  ```
183
154
 
184
- ### Client Usage
155
+ `products` can be a static array or a `() => Promise<StreamPayProduct[]>` factory.
156
+
157
+ ### Client
185
158
 
186
- ```typescript
187
- // By slug (maps to a productId configured on the server)
159
+ ```ts
160
+ // By slug
188
161
  const { data } = await authClient.checkout({ slug: "pro" });
189
162
  window.location.href = data.url;
190
163
 
191
- // By product UUID
192
- const { data } = await authClient.checkout({
193
- products: "aaaa-bbbb-cccc-dddd",
194
- });
164
+ // By UUID
165
+ await authClient.checkout({ products: "aaaa-bbbb-cccc-dddd" });
195
166
 
196
- // Multiple products with quantities
197
- const { data } = await authClient.checkout({
198
- products: [
199
- { productId: "aaaa-bbbb-cccc-dddd", quantity: 2 },
200
- ],
167
+ // Multiple products + quantity
168
+ await authClient.checkout({
169
+ products: [{ productId: "aaaa-bbbb-cccc-dddd", quantity: 2 }],
201
170
  });
202
171
 
203
- // With metadata and reference ID
204
- const { data } = await authClient.checkout({
172
+ // With reference id and metadata
173
+ await authClient.checkout({
205
174
  slug: "pro",
206
175
  referenceId: organizationId,
207
176
  metadata: { campaign: "spring-sale" },
208
177
  });
209
178
  ```
210
179
 
211
- ### Checkout Options
212
-
213
- | Option | Type | Description |
214
- | -------------------------- | ---------------------------------- | ------------------------------------------------------ |
215
- | `products` | `StreamPayProduct[]` or `function` | Slug-to-productId mappings |
216
- | `successUrl` | `string` | Redirect URL on successful payment |
217
- | `failureUrl` | `string` | Redirect URL on failed payment |
218
- | `authenticatedUsersOnly` | `boolean` | Reject unauthenticated/anonymous users |
219
- | `contactInformationType` | `"EMAIL" \| "PHONE"` | Contact info to collect during checkout |
220
- | `customFields` | `Record<string, unknown>` | Static fields forwarded on every payment link |
221
-
222
- ### Checkout Request Body
223
-
224
- | Field | Type | Description |
225
- | ---------------------- | ---------------------------------- | ---------------------------------------- |
226
- | `slug` | `string` | Product slug (resolved server-side) |
227
- | `products` | `string \| string[] \| object[]` | Product UUID(s) with optional quantity |
228
- | `referenceId` | `string` | Custom reference (stored in metadata) |
229
- | `consumerId` | `string` | Override consumer ID |
230
- | `name` | `string` | Payment link display name |
231
- | `description` | `string` | Payment link description |
232
- | `metadata` | `Record<string, string\|number\|boolean>` | Custom key-value metadata |
233
- | `successUrl` | `string` | Override success redirect |
234
- | `failureUrl` | `string` | Override failure redirect |
235
- | `maxNumberOfPayments` | `number` | Limit number of payments on this link |
236
- | `validUntil` | `string` | ISO 8601 expiration datetime |
237
- | `couponIds` | `string[]` | Coupon UUIDs to apply |
238
- | `redirect` | `boolean` | Whether to auto-redirect (default: true) |
239
-
240
- ## Portal Plugin
241
-
242
- ```typescript
243
- portal();
244
-
245
- // With custom lookup depth for legacy users
246
- portal({ consumerLookupMaxPages: 20 });
180
+ ### Body fields
181
+
182
+ | Field | Type | Notes |
183
+ | --------------------- | ------------------------------------------ | -------------------------------------- |
184
+ | `slug` | `string` | Resolved server-side via `products` |
185
+ | `products` | `string \| string[] \| { productId, quantity? }[]` | UUID(s) |
186
+ | `referenceId` | `string` | Stored in `custom_metadata` |
187
+ | `consumerId` | `string` (uuid) | Override the resolved consumer |
188
+ | `name` | `string` | Payment link display name |
189
+ | `description` | `string` | |
190
+ | `metadata` | `Record<string, string \| number \| boolean>` | |
191
+ | `successUrl` | `string` | Absolute or `/relative` |
192
+ | `failureUrl` | `string` | Absolute or `/relative` |
193
+ | `maxNumberOfPayments` | `number` | |
194
+ | `validUntil` | `string` (ISO 8601) | |
195
+ | `couponIds` | `string[]` (uuid) | |
196
+ | `redirect` | `boolean` | Default `true` |
197
+
198
+ ## Portal
199
+
200
+ ```ts
201
+ portal(); // default page size 100 (StreamPay's max)
202
+ portal({ pageSize: 50 });
247
203
  ```
248
204
 
249
- ### Client Usage
205
+ Reads are scoped to the session user via `organization_consumer_id`. One API call per read.
250
206
 
251
- ```typescript
252
- // Get consumer state — returns { hasConsumer, consumer }
207
+ ```ts
253
208
  const { data } = await authClient.state();
254
209
  if (!data.hasConsumer) {
255
- // User has not triggered lazy consumer creation yet — render "no billing activity" state
210
+ // user has no StreamPay consumer yet
256
211
  }
257
212
 
258
- // List subscriptions — returns { hasConsumer, data, pagination }
259
- const { data: subs } = await authClient.subscriptions({
260
- query: { page: 1, limit: 20 },
261
- });
213
+ const subs = await authClient.subscriptions(); // { hasConsumer, data }
214
+ const invoices = await authClient.invoices(); // { hasConsumer, data }
215
+ ```
262
216
 
263
- // List invoices
264
- const { data: invoices } = await authClient.invoices({
265
- query: { page: 1, limit: 20 },
266
- });
217
+ When `hasConsumer` is `false`, reads return `200 OK` with `data: []` (or `consumer: null`) instead of 404.
218
+
219
+ ## Subscriptions
220
+
221
+ ```ts
222
+ subscriptions({
223
+ plans: [
224
+ {
225
+ name: "pro",
226
+ productId: "prod_recurring_uuid",
227
+ priceHalalat: 9900, // 99.00 SAR
228
+ billingInterval: "MONTH", // WEEK | MONTH | QUARTER | YEAR
229
+ billingIntervalCount: 1, // optional
230
+ group: "tier", // optional, enforces 1 active per group
231
+ limits: { seats: 10, ai_calls: 1000 }, // typed entitlements
232
+ },
233
+ ],
234
+ // or a factory: plans: async () => fetchPlansFromCMS(),
235
+
236
+ authorizeReference: async ({ user, referenceId, action }) => {
237
+ return user.role === "admin";
238
+ },
267
239
 
268
- // List payments
269
- const { data: payments } = await authClient.payments();
240
+ // Schema knobs (defaults shown). Set to false to BYO state.
241
+ enableSubscriptionTable: true, // false → skip `subscription` schema + auto-sync
242
+ enableWebhookEventTable: true, // false → skip `streampayWebhookEvent` dedupe; you handle idempotency
243
+
244
+ onSubscriptionCreated: async (data) => {},
245
+ onSubscriptionActivated: async (data) => {},
246
+ onSubscriptionCanceled: async (data) => {},
247
+ onSubscriptionFrozen: async (data) => {},
248
+ onSubscriptionResumed: async (data) => {},
249
+ onSubscriptionRenewed: async (data) => {},
250
+ onSubscriptionPaymentFailed: async (data) => {},
251
+ });
270
252
  ```
271
253
 
272
- > **Response shape:** portal reads never eagerly create a consumer. When a user has no StreamPay consumer yet, every read returns `200 OK` with `{ hasConsumer: false, data: [], pagination: null }` (or `consumer: null` for `/state`) instead of `404`. This is additive — the `data` / `consumer` / `pagination` fields keep their shape when `hasConsumer` is true.
254
+ Each callback receives `{ subscription, user, streampaySubscription, event }`.
273
255
 
274
- ## Subscriptions Plugin
256
+ ### Endpoints
275
257
 
276
- ```typescript
277
- subscriptions();
278
- ```
258
+ | Path | Method | Notes |
259
+ | -------------------------------------- | ------ | ---------------------------------------------------------------- |
260
+ | `/subscription/upgrade` | POST | Creates payment link + `incomplete` row. Idempotent within 15min |
261
+ | `/subscription/success` | GET | Post-checkout fallback sync if webhook is slow |
262
+ | `/subscription/cancel` | POST | Immediate or `cancelAtPeriodEnd: true` |
263
+ | `/subscription/change-plan` | POST | `mode: "at_period_end"` (default) or `"immediate"` |
264
+ | `/subscription/freeze` | POST | |
265
+ | `/subscription/unfreeze` | POST | Ends the active freeze early |
266
+ | `/subscription/list` | GET | Local rows + plan config |
267
+ | `/subscription/current?group=...` | GET | Active / frozen / past_due, optional group filter |
268
+ | `/subscription/has-feature?feature=X` | GET | Boolean entitlement |
269
+ | `/subscription/check-limit?feature=X&count=N` | GET | `{ allowed, limit, remaining }` |
270
+
271
+ ### Client
279
272
 
280
- ### Client Usage
273
+ ```ts
274
+ const { data } = await authClient.upgradeSubscription({ plan: "pro" });
275
+ window.location.href = data.url;
276
+
277
+ // On success page:
278
+ await authClient.subscriptionSuccess({ subscriptionId: data.subscriptionId });
281
279
 
282
- ```typescript
283
- // Cancel a subscription
280
+ // Cancel at period end (keeps access until periodEnd)
284
281
  await authClient.cancelSubscription({
285
- subscriptionId: "sub-uuid",
286
- cancelRelatedInvoices: true,
282
+ subscriptionId,
283
+ cancelAtPeriodEnd: true,
287
284
  });
288
285
 
289
- // Freeze a subscription
286
+ // Plan change — immediate (PATCH items, no proration)
287
+ await authClient.changeSubscriptionPlan({ plan: "pro_plus", mode: "immediate" });
288
+
289
+ // Plan change — at period end (default; spawns new payment link)
290
+ const { data: change } = await authClient.changeSubscriptionPlan({ plan: "pro_plus" });
291
+ window.location.href = change.url;
292
+
293
+ // Freeze
290
294
  await authClient.freezeSubscription({
291
- subscriptionId: "sub-uuid",
292
- freezeStartDatetime: "2026-06-01T00:00:00Z",
293
- freezeEndDatetime: "2026-07-01T00:00:00Z",
294
- notes: "Customer vacation",
295
+ subscriptionId,
296
+ freezeStartDatetime: new Date().toISOString(),
297
+ freezeEndDatetime: null,
295
298
  });
299
+ await authClient.unfreezeSubscription({ subscriptionId });
300
+
301
+ // Reads
302
+ const current = await authClient.currentSubscription();
303
+ const seats = await authClient.checkSubscriptionLimit({ feature: "seats", count: 8 });
304
+ const flag = await authClient.hasSubscriptionFeature({ feature: "ai_calls" });
296
305
  ```
297
306
 
298
- ## Webhooks Plugin
307
+ ### Status values
299
308
 
300
- ```typescript
301
- webhooks({
302
- secret: process.env.STREAMPAY_WEBHOOK_SECRET!,
303
- toleranceSeconds: 300, // Replay protection window (default: 300s)
309
+ `incomplete | active | inactive | expired | canceled | frozen | past_due`
304
310
 
305
- // Catch-all handler (runs before event-specific handlers)
306
- onPayload: async (payload) => {
307
- console.log(`Received: ${payload.event_type}`);
308
- },
311
+ - `incomplete` — row pre-created at `/upgrade`, webhook not landed yet.
312
+ - `past_due` — renewal failed. StreamPay keeps `ACTIVE` during dunning; we don't.
313
+
314
+ ### Cross-account access
315
+
316
+ By default `referenceId` is the session user's id. Pass a different one and `authorizeReference` is called:
317
+
318
+ ```ts
319
+ authorizeReference: async ({ user, referenceId, action }, ctx) => {
320
+ // action: "upgrade" | "cancel" | "freeze" | "unfreeze" | "read" | "change-plan"
321
+ return user.role === "admin";
322
+ },
323
+ ```
324
+
325
+ Without `authorizeReference`, cross-account ops throw `FORBIDDEN`.
326
+
327
+ ### Webhook auto-sync
328
+
329
+ If both `subscriptions()` and `webhooks()` are in `use`, the plugin runs an idempotent sync **before** your handlers:
309
330
 
310
- // Payment events
311
- onPaymentSucceeded: async (payload) => {},
312
- onPaymentFailed: async (payload) => {},
313
- onPaymentCanceled: async (payload) => {},
314
- onPaymentRefunded: async (payload) => {},
315
- onPaymentMarkedAsPaid: async (payload) => {},
316
-
317
- // Invoice events
318
- onInvoiceCreated: async (payload) => {},
319
- onInvoiceSent: async (payload) => {},
320
- onInvoiceAccepted: async (payload) => {},
321
- onInvoiceRejected: async (payload) => {},
322
- onInvoiceCompleted: async (payload) => {},
323
- onInvoiceCanceled: async (payload) => {},
324
- onInvoiceUpdated: async (payload) => {},
325
-
326
- // Subscription events
327
- onSubscriptionCreated: async (payload) => {},
328
- onSubscriptionActivated: async (payload) => {},
329
- onSubscriptionInactivated: async (payload) => {},
330
- onSubscriptionCanceled: async (payload) => {},
331
- onSubscriptionFrozen: async (payload) => {},
332
- onSubscriptionCycleRenewalFailed: async (payload) => {},
333
- onSubscriptionCancelAtPeriodEnd: async (payload) => {},
334
- onSubscriptionFreezeNow: async (payload) => {},
335
- onSubscriptionUnfreezeNow: async (payload) => {},
336
- onSubscriptionUnfreezeFuture: async (payload) => {},
337
- onSubscriptionFreezeCancel: async (payload) => {},
338
-
339
- // Payment link events
340
- onPaymentLinkPayAttemptFailed: async (payload) => {},
331
+ - Dedupes via `streampayWebhookEvent` (`event_type:entity_id:timestamp`).
332
+ - Maps subscription events + `INVOICE_COMPLETED` (renewal) onto local rows.
333
+ - Fires your `onSubscription*` callbacks after the row is persisted.
334
+ - Transient failure → 500 (StreamPay retries). Permanent → logged + 200.
335
+
336
+ ## Admin
337
+
338
+ Back-office over the StreamPay SDK. Auth gate is `(adminRoles match user.role) || (isAdmin returns true)` — anon → 401, non-admin → 403.
339
+
340
+ ```ts
341
+ admin({
342
+ adminRoles: ["admin", "billing_ops"],
343
+ isAdmin: async (user, ctx) => user.email.endsWith("@yourco.com"),
344
+
345
+ onRefund: async ({ user, paymentId, request }) => { /* throw to block */ },
346
+ onPlanChange: async ({ user, subscriptionId, current, patch }) => { /* throw to block */ },
347
+ });
348
+ ```
349
+
350
+ - POST/PATCH/PUT bodies forward to the SDK verbatim (types from `@streamsdk/typescript`).
351
+ - DELETEs take no body / no `Content-Type`.
352
+ - List endpoints accept `?page=` / `?size=` (max 100); consumers also `?search_term=`; payments also `?invoice_id=`.
353
+ - Admin sub mutations refetch + project into the local `subscription` row using the same code path as the webhook — no drift.
354
+
355
+ ### Endpoints
356
+
357
+ | Endpoint | Method | SDK call |
358
+ | --------------------------------------------------- | ------ | ------------------------------ |
359
+ | `/admin/streampay/payments` | GET | `listPayments` |
360
+ | `/admin/streampay/payments/:id` | GET | `getPayment` |
361
+ | `/admin/streampay/payments/:id/refund` | POST | `refundPayment` |
362
+ | `/admin/streampay/subscriptions` | GET | `listSubscriptions` |
363
+ | `/admin/streampay/subscriptions` | POST | `createSubscription` |
364
+ | `/admin/streampay/subscriptions/:id` | GET | `getSubscription` |
365
+ | `/admin/streampay/subscriptions/:id` | PATCH | `updateSubscription` |
366
+ | `/admin/streampay/subscriptions/:id/cancel` | POST | `cancelSubscription` |
367
+ | `/admin/streampay/subscriptions/:id/freeze` | GET | `listSubscriptionFreezes` |
368
+ | `/admin/streampay/subscriptions/:id/freeze` | POST | `freezeSubscription` |
369
+ | `/admin/streampay/subscriptions/:id/freeze/:freezeId` | PUT | `updateSubscriptionFreeze` |
370
+ | `/admin/streampay/subscriptions/:id/freeze/:freezeId` | DELETE | `deleteSubscriptionFreeze` |
371
+ | `/admin/streampay/consumers` | GET | `listConsumers` (`search_term`) |
372
+ | `/admin/streampay/consumers/:id` | GET | `getConsumer` |
373
+ | `/admin/streampay/consumers/:id` | PATCH | `updateConsumer` |
374
+ | `/admin/streampay/consumers/:id` | DELETE | `deleteConsumer` + clears `streampayConsumerId` |
375
+ | `/admin/streampay/invoices` | GET | `listInvoices` |
376
+ | `/admin/streampay/invoices/:id` | GET | `getInvoice` |
377
+ | `/admin/streampay/products` | GET / POST | `listProducts` / `createProduct` |
378
+ | `/admin/streampay/products/:id` | GET / PUT / DELETE | `getProduct` / `updateProduct` / `deleteProduct` |
379
+ | `/admin/streampay/coupons` | GET / POST | `listCoupons` / `createCoupon` |
380
+ | `/admin/streampay/coupons/:id` | GET / PUT / DELETE | `getCoupon` / `updateCoupon` / `deleteCoupon` |
381
+ | `/admin/streampay/payment-links` | GET | `listPaymentLinks` |
382
+ | `/admin/streampay/payment-links/:id` | GET | `getPaymentLink` |
383
+
384
+ ### Calling
385
+
386
+ Method names mirror the routes: `adminListProducts`, `adminCreateProduct`, `adminCancelSubscription`, `adminRefundPayment`, etc.
387
+
388
+ Server (`auth.api.*`):
389
+ ```ts
390
+ await auth.api.adminCancelSubscription({
391
+ params: { id: streampaySubscriptionId },
392
+ body: { cancel_related_invoices: true },
393
+ headers: await headers(),
394
+ });
395
+ ```
396
+
397
+ Client (`authClient.*` — auto-generated, cookie auto-sent, gate runs on server):
398
+ ```ts
399
+ await authClient.adminListProducts({ query: { page: 1, size: 20 } });
400
+ ```
401
+
402
+ ### Examples
403
+
404
+ Create a recurring product:
405
+ ```ts
406
+ await authClient.adminCreateProduct({
407
+ body: {
408
+ name: "Pro Monthly",
409
+ price: "99.000", // SAR (string preserves halalat precision)
410
+ is_one_time: false,
411
+ type: "RECURRING", // or "ONE_OFF"
412
+ recurring_interval: "MONTH", // WEEK | MONTH | QUARTER | YEAR
413
+ recurring_interval_count: 1,
414
+ is_price_inclusive_of_vat: true,
415
+ },
341
416
  });
342
417
  ```
418
+ For ONE_OFF: drop the `recurring_*` fields, set `type: "ONE_OFF"`, `is_one_time: true`.
419
+
420
+ Refund a payment:
421
+ ```ts
422
+ await authClient.adminRefundPayment({
423
+ params: { id: paymentId },
424
+ body: {
425
+ refund_reason: "REQUESTED_BY_CUSTOMER", // REQUESTED_BY_CUSTOMER | DUPLICATE | FRAUDULENT | OTHER
426
+ refund_note: "optional",
427
+ allow_refund_multiple_related_payments: false,
428
+ },
429
+ });
430
+ ```
431
+ Refunds are always full (no `amount` field). Settled payments only — `PENDING`/`CANCELED` → 400 `PAYMENT_INVALID_STATE`.
432
+
433
+ ### Errors
343
434
 
344
- ### Webhook Configuration
435
+ 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`.
345
436
 
346
- Register `https://your-app.com/api/auth/streampay/webhooks` as the webhook URL in your [StreamPay dashboard](https://streampay.sa).
437
+ ## Webhooks
347
438
 
348
- ### Webhook Payload Shape
439
+ Register `https://your-app.com/api/auth/streampay/webhooks` in the StreamPay dashboard.
349
440
 
350
- ```typescript
351
- interface StreamPayWebhookPayload<T = Record<string, unknown>> {
352
- event_type: StreamPayEventType; // e.g. "PAYMENT_SUCCEEDED"
353
- entity_type: StreamPayEntityType; // "PAYMENT" | "INVOICE" | "SUBSCRIPTION" | "PAYMENT_LINK"
441
+ ```ts
442
+ webhooks({
443
+ secret: process.env.STREAMPAY_WEBHOOK_SECRET!,
444
+ toleranceSeconds: 300, // default 300s
445
+
446
+ onPayload: async (p) => { /* catch-all, runs first */ },
447
+
448
+ onPaymentSucceeded: async (p) => {},
449
+ onPaymentFailed: async (p) => {},
450
+ onPaymentCanceled: async (p) => {},
451
+ onPaymentRefunded: async (p) => {},
452
+ onPaymentMarkedAsPaid: async (p) => {},
453
+
454
+ onInvoiceCreated: async (p) => {},
455
+ onInvoiceSent: async (p) => {},
456
+ onInvoiceAccepted: async (p) => {},
457
+ onInvoiceRejected: async (p) => {},
458
+ onInvoiceCompleted: async (p) => {},
459
+ onInvoiceCanceled: async (p) => {},
460
+ onInvoiceUpdated: async (p) => {},
461
+
462
+ onSubscriptionCreated: async (p) => {},
463
+ onSubscriptionActivated: async (p) => {},
464
+ onSubscriptionInactivated: async (p) => {},
465
+ onSubscriptionCanceled: async (p) => {},
466
+ onSubscriptionFrozen: async (p) => {},
467
+ onSubscriptionCycleRenewalFailed: async (p) => {},
468
+ onSubscriptionCancelAtPeriodEnd: async (p) => {},
469
+ onSubscriptionFreezeNow: async (p) => {},
470
+ onSubscriptionUnfreezeNow: async (p) => {},
471
+ onSubscriptionUnfreezeFuture: async (p) => {},
472
+ onSubscriptionFreezeCancel: async (p) => {},
473
+
474
+ onPaymentLinkPayAttemptFailed: async (p) => {},
475
+ });
476
+ ```
477
+
478
+ ### Payload
479
+
480
+ ```ts
481
+ interface StreamPayWebhookPayload<T = StreamPayWebhookData> {
482
+ event_type: StreamPayEventType;
483
+ entity_type: "PAYMENT" | "INVOICE" | "SUBSCRIPTION" | "PAYMENT_LINK";
354
484
  entity_id: string;
355
485
  entity_url: string;
356
486
  status: string;
357
487
  data: T;
358
- timestamp: string; // ISO 8601
488
+ timestamp: string; // ISO 8601
359
489
  }
360
490
  ```
361
491
 
362
- ### Signature Verification
492
+ Each handler is narrowed: `onPaymentSucceeded` only sees `event_type: "PAYMENT_SUCCEEDED"`, etc.
363
493
 
364
- Webhooks are verified using HMAC-SHA256 with replay protection. The signature header format is `t=<timestamp>,v1=<hex-hmac>`.
494
+ ### Signature
365
495
 
366
- ## Endpoints
496
+ Header: `X-Webhook-Signature: t=<unix>,v1=<hex>` where hex is `HMAC_SHA256(secret, "${t}.${rawBody}")`.
367
497
 
368
- | Key | Method | Path | Auth | Plugin |
369
- | --------------------- | ------ | --------------------------------- | --------- | ----------------- |
370
- | `checkout` | POST | `/checkout` | Optional | `checkout()` |
371
- | `state` | GET | `/consumer/state` | Required | `portal()` |
372
- | `subscriptions` | GET | `/consumer/subscriptions/list` | Required | `portal()` |
373
- | `invoices` | GET | `/consumer/invoices/list` | Required | `portal()` |
374
- | `cancelSubscription` | POST | `/consumer/subscriptions/cancel` | Required | `subscriptions()` |
375
- | `freezeSubscription` | POST | `/consumer/subscriptions/freeze` | Required | `subscriptions()` |
376
- | `streampayWebhooks` | POST | `/streampay/webhooks` | Signature | `webhooks()` |
498
+ ### Rolling rotation
377
499
 
378
- ## Standalone Exports
500
+ ```ts
501
+ webhooks({
502
+ secret: [
503
+ process.env.STREAMPAY_WEBHOOK_SECRET!, // new
504
+ process.env.STREAMPAY_WEBHOOK_SECRET_OLD!, // old
505
+ ],
506
+ });
507
+ ```
508
+
509
+ Drop the old one once the dashboard is fully cut over.
510
+
511
+ ## Subscription row
512
+
513
+ ```ts
514
+ interface Subscription {
515
+ id: string;
516
+ referenceId: string;
517
+ streampaySubscriptionId: string | null;
518
+ streampayConsumerId: string | null;
519
+ plan: string;
520
+ group: string | null;
521
+ amountHalalat: number | null;
522
+ currency: string | null;
523
+ billingInterval: "WEEK" | "MONTH" | "QUARTER" | "YEAR" | null;
524
+ billingIntervalCount: number | null;
525
+ status: "incomplete" | "active" | "inactive" | "expired" | "canceled" | "frozen" | "past_due";
526
+ periodStart: Date | null;
527
+ periodEnd: Date | null;
528
+ cancelAtPeriodEnd: boolean;
529
+ endedAt: Date | null;
530
+ frozenAt: Date | null;
531
+ freezeEndAt: Date | null;
532
+ createdAt: Date;
533
+ updatedAt: Date;
534
+ }
535
+ ```
379
536
 
380
- These utilities can be used independently, outside the plugin context:
537
+ ## Error codes
381
538
 
382
- ### Webhook Verification
539
+ ```ts
540
+ import { $ERROR_CODES, type StreamPayErrorCode } from "better-auth-streampay";
541
+
542
+ if (err.code === $ERROR_CODES.SUBSCRIPTION_ALREADY_ACTIVE.code) {
543
+ // ...
544
+ }
545
+ ```
383
546
 
384
- ```typescript
547
+ 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`.
548
+
549
+ `mapToErrorCode(rawCode, status)` maps StreamPay's raw codes onto these buckets.
550
+
551
+ ## Standalone exports
552
+
553
+ ### Verify webhooks (no plugin)
554
+
555
+ ```ts
385
556
  import {
386
557
  verifyWebhook,
387
558
  verifyWebhookOrThrow,
388
559
  StreamPayWebhookError,
389
560
  } from "better-auth-streampay";
390
561
 
391
- // Result-based (no exceptions)
392
562
  const result = verifyWebhook({
393
- secret: "your-secret",
394
- rawBody: '{"event_type":"PAYMENT_SUCCEEDED",...}',
395
- signatureHeader: request.headers.get("X-Webhook-Signature"),
563
+ secret: process.env.STREAMPAY_WEBHOOK_SECRET!,
564
+ rawBody,
565
+ signatureHeader: req.headers.get("x-webhook-signature"),
396
566
  toleranceSeconds: 300,
397
567
  });
398
568
 
399
- if (result.ok) {
400
- console.log("Valid, timestamp:", result.timestamp);
401
- } else {
402
- console.log("Invalid:", result.reason);
403
- // "MISSING_HEADER" | "MALFORMED_HEADER" | "INVALID_TIMESTAMP" | "EXPIRED" | "INVALID_SIGNATURE"
404
- }
405
-
406
- // Exception-based
407
- try {
408
- const timestamp = verifyWebhookOrThrow({
409
- secret: "your-secret",
410
- rawBody,
411
- signatureHeader,
412
- });
413
- } catch (err) {
414
- if (err instanceof StreamPayWebhookError) {
415
- console.log(err.reason);
416
- }
569
+ if (!result.ok) {
570
+ // result.reason: MISSING_HEADER | MALFORMED_HEADER | INVALID_TIMESTAMP | EXPIRED | INVALID_SIGNATURE
417
571
  }
418
572
  ```
419
573
 
420
- ### Webhook Dispatch
574
+ ### Dispatch handlers manually
421
575
 
422
- ```typescript
576
+ ```ts
423
577
  import { dispatchWebhook } from "better-auth-streampay";
424
578
 
425
579
  await dispatchWebhook(payload, {
426
- onPayload: async (p) => { /* catch-all */ },
427
- onPaymentSucceeded: async (p) => { /* specific */ },
580
+ onPayload: async (p) => {},
581
+ onPaymentSucceeded: async (p) => {},
428
582
  });
429
583
  ```
430
584
 
431
- ### Consumer Lookup
585
+ ### Find consumers
432
586
 
433
- ```typescript
587
+ ```ts
434
588
  import {
435
589
  findConsumerByExternalId,
436
590
  findConsumerByIdentifiers,
437
591
  } from "better-auth-streampay";
438
592
 
439
- // By external ID (returns consumer ID or null)
440
- const consumerId = await findConsumerByExternalId(client, {
441
- externalId: "user-123",
442
- maxPages: 10,
443
- pageSize: 100,
444
- });
593
+ const id = await findConsumerByExternalId(client, { externalId: "user-123" });
445
594
 
446
- // By any identifier (returns full ConsumerResponse or null)
447
595
  const consumer = await findConsumerByIdentifiers(client, {
448
596
  email: "user@example.com",
449
597
  phone_number: "+966501234567",
@@ -452,46 +600,82 @@ const consumer = await findConsumerByIdentifiers(client, {
452
600
  });
453
601
  ```
454
602
 
455
- ### Error Formatting
603
+ ### Format / parse SDK errors
456
604
 
457
- ```typescript
458
- import { formatStreamPayError } from "better-auth-streampay";
605
+ ```ts
606
+ import { formatStreamPayError, parseStreamPayError } from "better-auth-streampay";
459
607
 
460
608
  try {
461
609
  await client.createConsumer(input);
462
610
  } catch (err) {
463
611
  console.error(formatStreamPayError(err));
612
+ const { status, code, requestId, validationErrors } = parseStreamPayError(err);
464
613
  }
465
614
  ```
466
615
 
467
- ### Constants & Types
616
+ ### Money
617
+
618
+ ```ts
619
+ import { StreamPayAmount } from "better-auth-streampay";
620
+
621
+ StreamPayAmount.toHalalat("99.00"); // 9900
622
+ StreamPayAmount.toSAR(9900); // "99.00"
623
+ ```
624
+
625
+ ### Event-type constants
468
626
 
469
- ```typescript
627
+ ```ts
470
628
  import {
471
629
  STREAMPAY_EVENT_TYPES,
630
+ STREAMPAY_PAYMENT_EVENT_TYPES,
631
+ STREAMPAY_INVOICE_EVENT_TYPES,
632
+ STREAMPAY_SUBSCRIPTION_EVENT_TYPES,
633
+ STREAMPAY_PAYMENT_LINK_EVENT_TYPES,
472
634
  type StreamPayEventType,
473
635
  type StreamPayEntityType,
474
636
  type StreamPayWebhookPayload,
475
637
  type WebhookHandler,
476
638
  type WebhookHandlers,
477
- type StreamPayOptions,
478
- type StreamPayProduct,
479
- type CheckoutOptions,
480
- type CheckoutParams,
481
- type ConsumerCreateOverrides,
482
- type VerifyWebhookInput,
483
- type VerifyWebhookResult,
484
- type VerifyFailureReason,
485
639
  } from "better-auth-streampay";
486
640
  ```
487
641
 
488
- ## Testing
642
+ ### Subscription helpers
643
+
644
+ ```ts
645
+ import { hasFeature, checkLimit, subscriptionSchema } from "better-auth-streampay";
646
+
647
+ const allowed = hasFeature(row, plan, "ai_calls");
648
+ const quota = checkLimit(row, plan, "seats", 8); // { allowed, limit, remaining }
649
+ ```
650
+
651
+ ## Endpoints summary
652
+
653
+ | Key | Method | Path | Auth | Plugin |
654
+ | ------------------------- | ------ | ---------------------------------- | --------- | ----------------- |
655
+ | `checkout` | POST | `/checkout` | Optional | `checkout()` |
656
+ | `state` | GET | `/consumer/state` | Required | `portal()` |
657
+ | `subscriptions` | GET | `/consumer/subscriptions/list` | Required | `portal()` |
658
+ | `invoices` | GET | `/consumer/invoices/list` | Required | `portal()` |
659
+ | `upgradeSubscription` | POST | `/subscription/upgrade` | Required | `subscriptions()` |
660
+ | `subscriptionSuccess` | GET | `/subscription/success` | Required | `subscriptions()` |
661
+ | `cancelSubscription` | POST | `/subscription/cancel` | Required | `subscriptions()` |
662
+ | `changeSubscriptionPlan` | POST | `/subscription/change-plan` | Required | `subscriptions()` |
663
+ | `freezeSubscription` | POST | `/subscription/freeze` | Required | `subscriptions()` |
664
+ | `unfreezeSubscription` | POST | `/subscription/unfreeze` | Required | `subscriptions()` |
665
+ | `listSubscriptions` | GET | `/subscription/list` | Required | `subscriptions()` |
666
+ | `currentSubscription` | GET | `/subscription/current` | Required | `subscriptions()` |
667
+ | `hasSubscriptionFeature` | GET | `/subscription/has-feature` | Required | `subscriptions()` |
668
+ | `checkSubscriptionLimit` | GET | `/subscription/check-limit` | Required | `subscriptions()` |
669
+ | `streampayWebhooks` | POST | `/streampay/webhooks` | Signature | `webhooks()` |
670
+ | `admin*` | varied | `/admin/streampay/...` | Role | `admin()` |
671
+
672
+ ## Scripts
489
673
 
490
674
  ```bash
491
- pnpm test # vitest run
492
- pnpm typecheck # tsc --noEmit
493
- pnpm lint # biome check
494
- pnpm build # tsup (ESM + CJS)
675
+ pnpm test # vitest
676
+ pnpm typecheck # tsc --noEmit
677
+ pnpm lint # biome check
678
+ pnpm build # tsup (ESM + CJS)
495
679
  ```
496
680
 
497
681
  ## License