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