better-auth-streampay 0.2.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 +489 -291
- 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 +3028 -523
- 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 +3013 -524
- 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 -7
- package/dist/streampay-DeyntFo9.d.cts +0 -1608
- package/dist/streampay-DeyntFo9.d.ts +0 -1608
package/README.md
CHANGED
|
@@ -1,48 +1,40 @@
|
|
|
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
|
-
##
|
|
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=...
|
|
32
|
-
BETTER_AUTH_SECRET=...
|
|
33
|
-
BETTER_AUTH_URL=...
|
|
30
|
+
STREAMPAY_WEBHOOK_SECRET=...
|
|
31
|
+
BETTER_AUTH_SECRET=...
|
|
32
|
+
BETTER_AUTH_URL=...
|
|
34
33
|
```
|
|
35
34
|
|
|
36
|
-
## Server
|
|
37
|
-
|
|
38
|
-
The StreamPay plugin comes with a handful of sub-plugins that add functionality to your stack:
|
|
35
|
+
## Server
|
|
39
36
|
|
|
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
|
-
|
|
45
|
-
```typescript
|
|
37
|
+
```ts
|
|
46
38
|
import { betterAuth } from "better-auth";
|
|
47
39
|
import StreamSDK from "@streamsdk/typescript";
|
|
48
40
|
import {
|
|
@@ -51,44 +43,45 @@ import {
|
|
|
51
43
|
portal,
|
|
52
44
|
subscriptions,
|
|
53
45
|
webhooks,
|
|
46
|
+
admin,
|
|
54
47
|
} from "better-auth-streampay";
|
|
55
48
|
|
|
56
|
-
const
|
|
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
|
|
62
|
-
createConsumerOnSignUp: true,
|
|
54
|
+
client,
|
|
63
55
|
use: [
|
|
64
56
|
checkout({
|
|
65
|
-
products: [
|
|
66
|
-
{ productId: "aaaa-bbbb-cccc-dddd", slug: "pro" },
|
|
67
|
-
],
|
|
57
|
+
products: [{ productId: "aaaa-bbbb-cccc-dddd", slug: "pro" }],
|
|
68
58
|
successUrl: "/dashboard?checkout=success",
|
|
69
59
|
failureUrl: "/dashboard?checkout=failure",
|
|
70
60
|
authenticatedUsersOnly: true,
|
|
71
61
|
}),
|
|
72
62
|
portal(),
|
|
73
|
-
subscriptions(
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
|
|
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
|
+
],
|
|
82
73
|
}),
|
|
74
|
+
webhooks({ secret: process.env.STREAMPAY_WEBHOOK_SECRET! }),
|
|
75
|
+
admin(),
|
|
83
76
|
],
|
|
84
77
|
}),
|
|
85
78
|
],
|
|
86
79
|
});
|
|
87
80
|
```
|
|
88
81
|
|
|
89
|
-
## Client
|
|
82
|
+
## Client
|
|
90
83
|
|
|
91
|
-
```
|
|
84
|
+
```ts
|
|
92
85
|
import { createAuthClient } from "better-auth/react";
|
|
93
86
|
import { streampayClient } from "better-auth-streampay/client";
|
|
94
87
|
|
|
@@ -97,339 +90,508 @@ export const authClient = createAuthClient({
|
|
|
97
90
|
});
|
|
98
91
|
```
|
|
99
92
|
|
|
100
|
-
## Database
|
|
93
|
+
## Database migration
|
|
101
94
|
|
|
102
|
-
|
|
95
|
+
Adds a `streampayConsumerId` column on `user`, plus `subscription` and `streampayWebhookEvent` tables when `subscriptions()` is in `use`.
|
|
103
96
|
|
|
104
97
|
```bash
|
|
105
|
-
npx @better-auth/cli migrate
|
|
106
|
-
npx drizzle-kit generate && npx drizzle-kit migrate
|
|
107
|
-
npx prisma migrate dev
|
|
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
|
|
108
101
|
```
|
|
109
102
|
|
|
110
|
-
##
|
|
111
|
-
|
|
112
|
-
### Required
|
|
113
|
-
|
|
114
|
-
| Option | Type | Description |
|
|
115
|
-
| -------- | ----------------- | ----------------------------- |
|
|
116
|
-
| `client` | `StreamPayClient` | Initialized StreamPay SDK client |
|
|
117
|
-
| `use` | `StreamPayPlugin[]` | Sub-plugins to compose |
|
|
118
|
-
|
|
119
|
-
### Optional
|
|
120
|
-
|
|
121
|
-
| Option | Type | Description |
|
|
122
|
-
| ------------------------- | ---------- | ------------------------------------------------------------------ |
|
|
123
|
-
| `createConsumerOnSignUp` | `boolean` | Automatically create a StreamPay consumer when a user signs up |
|
|
124
|
-
| `claimExistingConsumerBy` | `("email" \| "phone")[]` | Reclaim a duplicate linked consumer by the listed identifier(s) |
|
|
125
|
-
| `getConsumerCreateParams` | `function` | Provide additional consumer fields (phone, language, IBAN, etc.) |
|
|
126
|
-
|
|
127
|
-
### Consumers
|
|
128
|
-
|
|
129
|
-
When `createConsumerOnSignUp` is enabled, a new StreamPay Consumer is automatically created when a new user signs up. All consumers are created with an `external_id` matching the user's database ID — no mapping table needed. The resulting consumer ID is stored as `streampayConsumerId` on the user row.
|
|
130
|
-
|
|
131
|
-
If StreamPay rejects sign-up 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.
|
|
132
|
-
|
|
133
|
-
Claim modes:
|
|
134
|
-
- omitted / `[]` — only reuse stranded consumers
|
|
135
|
-
- `["email"]` — reclaim duplicates that match the same email
|
|
136
|
-
- `["phone"]` — reclaim duplicates that match the same phone number
|
|
137
|
-
- `["email", "phone"]` — reclaim duplicates that match either email or phone
|
|
103
|
+
## `streampay()` options
|
|
138
104
|
|
|
139
|
-
|
|
140
|
-
|
|
141
|
-
Consumer data is also kept in sync:
|
|
142
|
-
- **User update** — name/email changes are synced to StreamPay
|
|
143
|
-
- **User delete** — the StreamPay consumer is deleted
|
|
144
|
-
|
|
145
|
-
#### Custom Consumer Fields
|
|
146
|
-
|
|
147
|
-
```typescript
|
|
105
|
+
```ts
|
|
148
106
|
streampay({
|
|
149
|
-
client
|
|
150
|
-
|
|
107
|
+
client,
|
|
108
|
+
// Eagerly create a consumer at signup. Default: false (lazy).
|
|
109
|
+
createConsumerOnSignUp: false,
|
|
110
|
+
// Reclaim duplicates by matching identifier(s).
|
|
151
111
|
claimExistingConsumerBy: ["email", "phone"],
|
|
152
|
-
|
|
112
|
+
// Extra fields passed to `client.createConsumer`.
|
|
113
|
+
getConsumerCreateParams: async ({ user }) => ({
|
|
153
114
|
phone_number: "+966501234567",
|
|
154
|
-
preferred_language: "
|
|
115
|
+
preferred_language: "AR",
|
|
155
116
|
communication_methods: ["WHATSAPP", "EMAIL"],
|
|
156
117
|
}),
|
|
157
|
-
use: [
|
|
118
|
+
use: [/* sub-plugins */],
|
|
158
119
|
});
|
|
159
120
|
```
|
|
160
121
|
|
|
161
|
-
|
|
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.
|
|
128
|
+
|
|
129
|
+
### Duplicate handling
|
|
130
|
+
|
|
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. |
|
|
162
139
|
|
|
163
|
-
|
|
140
|
+
If reused, the plugin rewrites `external_id` to the new user id.
|
|
141
|
+
|
|
142
|
+
## Checkout
|
|
143
|
+
|
|
144
|
+
```ts
|
|
164
145
|
checkout({
|
|
165
146
|
products: [{ productId: "aaaa-bbbb-cccc-dddd", slug: "pro" }],
|
|
166
147
|
successUrl: "/dashboard?checkout=success",
|
|
167
148
|
failureUrl: "/dashboard?checkout=failure",
|
|
168
149
|
authenticatedUsersOnly: true,
|
|
169
|
-
contactInformationType: "EMAIL",
|
|
150
|
+
contactInformationType: "EMAIL", // or "PHONE"
|
|
170
151
|
customFields: { source: "website" },
|
|
171
152
|
});
|
|
172
153
|
```
|
|
173
154
|
|
|
174
|
-
|
|
155
|
+
`products` can be a static array or a `() => Promise<StreamPayProduct[]>` factory.
|
|
156
|
+
|
|
157
|
+
### Client
|
|
175
158
|
|
|
176
|
-
```
|
|
177
|
-
// By slug
|
|
159
|
+
```ts
|
|
160
|
+
// By slug
|
|
178
161
|
const { data } = await authClient.checkout({ slug: "pro" });
|
|
179
162
|
window.location.href = data.url;
|
|
180
163
|
|
|
181
|
-
// By
|
|
182
|
-
|
|
183
|
-
products: "aaaa-bbbb-cccc-dddd",
|
|
184
|
-
});
|
|
164
|
+
// By UUID
|
|
165
|
+
await authClient.checkout({ products: "aaaa-bbbb-cccc-dddd" });
|
|
185
166
|
|
|
186
|
-
// Multiple products
|
|
187
|
-
|
|
188
|
-
products: [
|
|
189
|
-
{ productId: "aaaa-bbbb-cccc-dddd", quantity: 2 },
|
|
190
|
-
],
|
|
167
|
+
// Multiple products + quantity
|
|
168
|
+
await authClient.checkout({
|
|
169
|
+
products: [{ productId: "aaaa-bbbb-cccc-dddd", quantity: 2 }],
|
|
191
170
|
});
|
|
192
171
|
|
|
193
|
-
// With
|
|
194
|
-
|
|
172
|
+
// With reference id and metadata
|
|
173
|
+
await authClient.checkout({
|
|
195
174
|
slug: "pro",
|
|
196
175
|
referenceId: organizationId,
|
|
197
176
|
metadata: { campaign: "spring-sale" },
|
|
198
177
|
});
|
|
199
178
|
```
|
|
200
179
|
|
|
201
|
-
###
|
|
202
|
-
|
|
203
|
-
|
|
|
204
|
-
|
|
|
205
|
-
| `
|
|
206
|
-
| `
|
|
207
|
-
| `
|
|
208
|
-
| `
|
|
209
|
-
| `
|
|
210
|
-
| `
|
|
211
|
-
|
|
212
|
-
|
|
213
|
-
|
|
214
|
-
|
|
|
215
|
-
|
|
|
216
|
-
| `
|
|
217
|
-
| `
|
|
218
|
-
|
|
219
|
-
|
|
220
|
-
|
|
221
|
-
|
|
222
|
-
|
|
223
|
-
|
|
224
|
-
| `failureUrl` | `string` | Override failure redirect |
|
|
225
|
-
| `maxNumberOfPayments` | `number` | Limit number of payments on this link |
|
|
226
|
-
| `validUntil` | `string` | ISO 8601 expiration datetime |
|
|
227
|
-
| `couponIds` | `string[]` | Coupon UUIDs to apply |
|
|
228
|
-
| `redirect` | `boolean` | Whether to auto-redirect (default: true) |
|
|
229
|
-
|
|
230
|
-
## Portal Plugin
|
|
231
|
-
|
|
232
|
-
```typescript
|
|
233
|
-
portal();
|
|
234
|
-
|
|
235
|
-
// With custom lookup depth for legacy users
|
|
236
|
-
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 });
|
|
237
203
|
```
|
|
238
204
|
|
|
239
|
-
|
|
205
|
+
Reads are scoped to the session user via `organization_consumer_id`. One API call per read.
|
|
240
206
|
|
|
241
|
-
```
|
|
242
|
-
|
|
243
|
-
|
|
207
|
+
```ts
|
|
208
|
+
const { data } = await authClient.state();
|
|
209
|
+
if (!data.hasConsumer) {
|
|
210
|
+
// user has no StreamPay consumer yet
|
|
211
|
+
}
|
|
244
212
|
|
|
245
|
-
|
|
246
|
-
const
|
|
247
|
-
|
|
248
|
-
});
|
|
213
|
+
const subs = await authClient.subscriptions(); // { hasConsumer, data }
|
|
214
|
+
const invoices = await authClient.invoices(); // { hasConsumer, data }
|
|
215
|
+
```
|
|
249
216
|
|
|
250
|
-
|
|
251
|
-
|
|
252
|
-
|
|
253
|
-
|
|
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(),
|
|
254
235
|
|
|
255
|
-
|
|
256
|
-
|
|
236
|
+
authorizeReference: async ({ user, referenceId, action }) => {
|
|
237
|
+
return user.role === "admin";
|
|
238
|
+
},
|
|
239
|
+
|
|
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
|
+
});
|
|
257
252
|
```
|
|
258
253
|
|
|
259
|
-
|
|
254
|
+
Each callback receives `{ subscription, user, streampaySubscription, event }`.
|
|
260
255
|
|
|
261
|
-
|
|
262
|
-
|
|
263
|
-
|
|
256
|
+
### Endpoints
|
|
257
|
+
|
|
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
|
|
264
272
|
|
|
265
|
-
|
|
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 });
|
|
266
279
|
|
|
267
|
-
|
|
268
|
-
// Cancel a subscription
|
|
280
|
+
// Cancel at period end (keeps access until periodEnd)
|
|
269
281
|
await authClient.cancelSubscription({
|
|
270
|
-
subscriptionId
|
|
271
|
-
|
|
282
|
+
subscriptionId,
|
|
283
|
+
cancelAtPeriodEnd: true,
|
|
272
284
|
});
|
|
273
285
|
|
|
274
|
-
//
|
|
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
|
|
275
294
|
await authClient.freezeSubscription({
|
|
276
|
-
subscriptionId
|
|
277
|
-
freezeStartDatetime:
|
|
278
|
-
freezeEndDatetime:
|
|
279
|
-
notes: "Customer vacation",
|
|
295
|
+
subscriptionId,
|
|
296
|
+
freezeStartDatetime: new Date().toISOString(),
|
|
297
|
+
freezeEndDatetime: null,
|
|
280
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" });
|
|
281
305
|
```
|
|
282
306
|
|
|
283
|
-
|
|
307
|
+
### Status values
|
|
284
308
|
|
|
285
|
-
|
|
286
|
-
webhooks({
|
|
287
|
-
secret: process.env.STREAMPAY_WEBHOOK_SECRET!,
|
|
288
|
-
toleranceSeconds: 300, // Replay protection window (default: 300s)
|
|
309
|
+
`incomplete | active | inactive | expired | canceled | frozen | past_due`
|
|
289
310
|
|
|
290
|
-
|
|
291
|
-
|
|
292
|
-
|
|
293
|
-
|
|
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:
|
|
294
330
|
|
|
295
|
-
|
|
296
|
-
|
|
297
|
-
|
|
298
|
-
|
|
299
|
-
|
|
300
|
-
|
|
301
|
-
|
|
302
|
-
|
|
303
|
-
|
|
304
|
-
|
|
305
|
-
|
|
306
|
-
|
|
307
|
-
|
|
308
|
-
|
|
309
|
-
|
|
310
|
-
|
|
311
|
-
|
|
312
|
-
|
|
313
|
-
|
|
314
|
-
|
|
315
|
-
|
|
316
|
-
|
|
317
|
-
|
|
318
|
-
|
|
319
|
-
|
|
320
|
-
|
|
321
|
-
|
|
322
|
-
|
|
323
|
-
|
|
324
|
-
|
|
325
|
-
|
|
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
|
+
},
|
|
326
416
|
});
|
|
327
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
|
|
328
434
|
|
|
329
|
-
|
|
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`.
|
|
330
436
|
|
|
331
|
-
|
|
437
|
+
## Webhooks
|
|
332
438
|
|
|
333
|
-
|
|
439
|
+
Register `https://your-app.com/api/auth/streampay/webhooks` in the StreamPay dashboard.
|
|
334
440
|
|
|
335
|
-
```
|
|
336
|
-
|
|
337
|
-
|
|
338
|
-
|
|
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";
|
|
339
484
|
entity_id: string;
|
|
340
485
|
entity_url: string;
|
|
341
486
|
status: string;
|
|
342
487
|
data: T;
|
|
343
|
-
timestamp: string;
|
|
488
|
+
timestamp: string; // ISO 8601
|
|
344
489
|
}
|
|
345
490
|
```
|
|
346
491
|
|
|
347
|
-
|
|
492
|
+
Each handler is narrowed: `onPaymentSucceeded` only sees `event_type: "PAYMENT_SUCCEEDED"`, etc.
|
|
348
493
|
|
|
349
|
-
|
|
494
|
+
### Signature
|
|
350
495
|
|
|
351
|
-
|
|
496
|
+
Header: `X-Webhook-Signature: t=<unix>,v1=<hex>` where hex is `HMAC_SHA256(secret, "${t}.${rawBody}")`.
|
|
352
497
|
|
|
353
|
-
|
|
354
|
-
| --------------------- | ------ | --------------------------------- | --------- | ----------------- |
|
|
355
|
-
| `checkout` | POST | `/checkout` | Optional | `checkout()` |
|
|
356
|
-
| `state` | GET | `/consumer/state` | Required | `portal()` |
|
|
357
|
-
| `subscriptions` | GET | `/consumer/subscriptions/list` | Required | `portal()` |
|
|
358
|
-
| `invoices` | GET | `/consumer/invoices/list` | Required | `portal()` |
|
|
359
|
-
| `payments` | GET | `/consumer/payments/list` | Required | `portal()` |
|
|
360
|
-
| `cancelSubscription` | POST | `/consumer/subscriptions/cancel` | Required | `subscriptions()` |
|
|
361
|
-
| `freezeSubscription` | POST | `/consumer/subscriptions/freeze` | Required | `subscriptions()` |
|
|
362
|
-
| `streampayWebhooks` | POST | `/streampay/webhooks` | Signature | `webhooks()` |
|
|
498
|
+
### Rolling rotation
|
|
363
499
|
|
|
364
|
-
|
|
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
|
+
```
|
|
365
536
|
|
|
366
|
-
|
|
537
|
+
## Error codes
|
|
367
538
|
|
|
368
|
-
|
|
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
|
+
```
|
|
369
546
|
|
|
370
|
-
|
|
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
|
|
371
556
|
import {
|
|
372
557
|
verifyWebhook,
|
|
373
558
|
verifyWebhookOrThrow,
|
|
374
559
|
StreamPayWebhookError,
|
|
375
560
|
} from "better-auth-streampay";
|
|
376
561
|
|
|
377
|
-
// Result-based (no exceptions)
|
|
378
562
|
const result = verifyWebhook({
|
|
379
|
-
secret:
|
|
380
|
-
rawBody
|
|
381
|
-
signatureHeader:
|
|
563
|
+
secret: process.env.STREAMPAY_WEBHOOK_SECRET!,
|
|
564
|
+
rawBody,
|
|
565
|
+
signatureHeader: req.headers.get("x-webhook-signature"),
|
|
382
566
|
toleranceSeconds: 300,
|
|
383
567
|
});
|
|
384
568
|
|
|
385
|
-
if (result.ok) {
|
|
386
|
-
|
|
387
|
-
} else {
|
|
388
|
-
console.log("Invalid:", result.reason);
|
|
389
|
-
// "MISSING_HEADER" | "MALFORMED_HEADER" | "INVALID_TIMESTAMP" | "EXPIRED" | "INVALID_SIGNATURE"
|
|
390
|
-
}
|
|
391
|
-
|
|
392
|
-
// Exception-based
|
|
393
|
-
try {
|
|
394
|
-
const timestamp = verifyWebhookOrThrow({
|
|
395
|
-
secret: "your-secret",
|
|
396
|
-
rawBody,
|
|
397
|
-
signatureHeader,
|
|
398
|
-
});
|
|
399
|
-
} catch (err) {
|
|
400
|
-
if (err instanceof StreamPayWebhookError) {
|
|
401
|
-
console.log(err.reason);
|
|
402
|
-
}
|
|
569
|
+
if (!result.ok) {
|
|
570
|
+
// result.reason: MISSING_HEADER | MALFORMED_HEADER | INVALID_TIMESTAMP | EXPIRED | INVALID_SIGNATURE
|
|
403
571
|
}
|
|
404
572
|
```
|
|
405
573
|
|
|
406
|
-
###
|
|
574
|
+
### Dispatch handlers manually
|
|
407
575
|
|
|
408
|
-
```
|
|
576
|
+
```ts
|
|
409
577
|
import { dispatchWebhook } from "better-auth-streampay";
|
|
410
578
|
|
|
411
579
|
await dispatchWebhook(payload, {
|
|
412
|
-
onPayload: async (p) => {
|
|
413
|
-
onPaymentSucceeded: async (p) => {
|
|
580
|
+
onPayload: async (p) => {},
|
|
581
|
+
onPaymentSucceeded: async (p) => {},
|
|
414
582
|
});
|
|
415
583
|
```
|
|
416
584
|
|
|
417
|
-
###
|
|
585
|
+
### Find consumers
|
|
418
586
|
|
|
419
|
-
```
|
|
587
|
+
```ts
|
|
420
588
|
import {
|
|
421
589
|
findConsumerByExternalId,
|
|
422
590
|
findConsumerByIdentifiers,
|
|
423
591
|
} from "better-auth-streampay";
|
|
424
592
|
|
|
425
|
-
|
|
426
|
-
const consumerId = await findConsumerByExternalId(client, {
|
|
427
|
-
externalId: "user-123",
|
|
428
|
-
maxPages: 10,
|
|
429
|
-
pageSize: 100,
|
|
430
|
-
});
|
|
593
|
+
const id = await findConsumerByExternalId(client, { externalId: "user-123" });
|
|
431
594
|
|
|
432
|
-
// By any identifier (returns full ConsumerResponse or null)
|
|
433
595
|
const consumer = await findConsumerByIdentifiers(client, {
|
|
434
596
|
email: "user@example.com",
|
|
435
597
|
phone_number: "+966501234567",
|
|
@@ -438,46 +600,82 @@ const consumer = await findConsumerByIdentifiers(client, {
|
|
|
438
600
|
});
|
|
439
601
|
```
|
|
440
602
|
|
|
441
|
-
###
|
|
603
|
+
### Format / parse SDK errors
|
|
442
604
|
|
|
443
|
-
```
|
|
444
|
-
import { formatStreamPayError } from "better-auth-streampay";
|
|
605
|
+
```ts
|
|
606
|
+
import { formatStreamPayError, parseStreamPayError } from "better-auth-streampay";
|
|
445
607
|
|
|
446
608
|
try {
|
|
447
609
|
await client.createConsumer(input);
|
|
448
610
|
} catch (err) {
|
|
449
611
|
console.error(formatStreamPayError(err));
|
|
612
|
+
const { status, code, requestId, validationErrors } = parseStreamPayError(err);
|
|
450
613
|
}
|
|
451
614
|
```
|
|
452
615
|
|
|
453
|
-
###
|
|
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
|
|
454
626
|
|
|
455
|
-
```
|
|
627
|
+
```ts
|
|
456
628
|
import {
|
|
457
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,
|
|
458
634
|
type StreamPayEventType,
|
|
459
635
|
type StreamPayEntityType,
|
|
460
636
|
type StreamPayWebhookPayload,
|
|
461
637
|
type WebhookHandler,
|
|
462
638
|
type WebhookHandlers,
|
|
463
|
-
type StreamPayOptions,
|
|
464
|
-
type StreamPayProduct,
|
|
465
|
-
type CheckoutOptions,
|
|
466
|
-
type CheckoutParams,
|
|
467
|
-
type ConsumerCreateOverrides,
|
|
468
|
-
type VerifyWebhookInput,
|
|
469
|
-
type VerifyWebhookResult,
|
|
470
|
-
type VerifyFailureReason,
|
|
471
639
|
} from "better-auth-streampay";
|
|
472
640
|
```
|
|
473
641
|
|
|
474
|
-
|
|
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
|
|
475
673
|
|
|
476
674
|
```bash
|
|
477
|
-
pnpm test
|
|
478
|
-
pnpm typecheck
|
|
479
|
-
pnpm lint
|
|
480
|
-
pnpm build
|
|
675
|
+
pnpm test # vitest
|
|
676
|
+
pnpm typecheck # tsc --noEmit
|
|
677
|
+
pnpm lint # biome check
|
|
678
|
+
pnpm build # tsup (ESM + CJS)
|
|
481
679
|
```
|
|
482
680
|
|
|
483
681
|
## License
|