better-auth-streampay 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Ali Aldhamen
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,473 @@
1
+ # better-auth-streampay
2
+
3
+ > **Community plugin — not affiliated with Stream or StreamPay.** For plugin bugs, [open an issue here](https://github.com/y0u-0/better-auth-streampay/issues). For StreamPay bugs, contact [Stream support](https://streampay.sa).
4
+
5
+ A [Better Auth](https://better-auth.com) plugin for integrating [StreamPay](https://streampay.sa) payments and subscriptions into your authentication flow.
6
+
7
+ ## Features
8
+
9
+ - Checkout Integration
10
+ - Consumer Portal (subscriptions, invoices, payments)
11
+ - Subscription Management (cancel, freeze)
12
+ - Automatic Consumer creation on signup
13
+ - Handle StreamPay Webhooks securely with HMAC-SHA256 signature verification
14
+ - Consumer sync on user update/delete
15
+
16
+ ## Installation
17
+
18
+ ```bash
19
+ pnpm add better-auth-streampay @streamsdk/typescript better-auth
20
+ ```
21
+
22
+ Peer dependencies: `@streamsdk/typescript`, `better-auth`, `zod` (`^3.24` or `^4.0`).
23
+
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:
27
+
28
+ ```bash
29
+ # .env
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)
34
+ ```
35
+
36
+ ## Server Setup
37
+
38
+ The StreamPay plugin comes with a handful of sub-plugins that add functionality to your stack:
39
+
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
46
+ import { betterAuth } from "better-auth";
47
+ import StreamSDK from "@streamsdk/typescript";
48
+ import {
49
+ streampay,
50
+ checkout,
51
+ portal,
52
+ subscriptions,
53
+ webhooks,
54
+ } from "better-auth-streampay";
55
+
56
+ const streamPayClient = StreamSDK.init(process.env.STREAMPAY_API_KEY!);
57
+
58
+ const auth = betterAuth({
59
+ plugins: [
60
+ streampay({
61
+ client: streamPayClient,
62
+ createConsumerOnSignUp: true,
63
+ use: [
64
+ checkout({
65
+ products: [
66
+ { productId: "aaaa-bbbb-cccc-dddd", slug: "pro" },
67
+ ],
68
+ successUrl: "/dashboard?checkout=success",
69
+ failureUrl: "/dashboard?checkout=failure",
70
+ authenticatedUsersOnly: true,
71
+ }),
72
+ portal(),
73
+ subscriptions(),
74
+ webhooks({
75
+ secret: process.env.STREAMPAY_WEBHOOK_SECRET!,
76
+ onPaymentSucceeded: async (payload) => {
77
+ // provision access
78
+ },
79
+ onSubscriptionCanceled: async (payload) => {
80
+ // revoke access
81
+ },
82
+ }),
83
+ ],
84
+ }),
85
+ ],
86
+ });
87
+ ```
88
+
89
+ ## Client Setup
90
+
91
+ ```typescript
92
+ import { createAuthClient } from "better-auth/react";
93
+ import { streampayClient } from "better-auth-streampay/client";
94
+
95
+ export const authClient = createAuthClient({
96
+ plugins: [streampayClient()],
97
+ });
98
+ ```
99
+
100
+ ## Database Migration
101
+
102
+ The plugin adds a `streampayConsumerId` column to the `user` table. Run your migration after installing:
103
+
104
+ ```bash
105
+ npx @better-auth/cli migrate # Better Auth CLI
106
+ npx drizzle-kit generate && npx drizzle-kit migrate # Drizzle
107
+ npx prisma migrate dev # Prisma
108
+ ```
109
+
110
+ ## Configuration Options
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
+ | `getConsumerCreateParams` | `function` | Provide additional consumer fields (phone, language, IBAN, etc.) |
125
+
126
+ ### Consumers
127
+
128
+ 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.
129
+
130
+ Consumer data is also kept in sync:
131
+ - **User update** — name/email changes are synced to StreamPay
132
+ - **User delete** — the StreamPay consumer is deleted
133
+
134
+ #### Custom Consumer Fields
135
+
136
+ ```typescript
137
+ streampay({
138
+ client: streamPayClient,
139
+ createConsumerOnSignUp: true,
140
+ getConsumerCreateParams: async ({ user }, request) => ({
141
+ phone_number: "+966501234567",
142
+ preferred_language: "ar",
143
+ communication_methods: ["WHATSAPP", "EMAIL"],
144
+ }),
145
+ use: [...],
146
+ });
147
+ ```
148
+
149
+ ## Checkout Plugin
150
+
151
+ ```typescript
152
+ checkout({
153
+ products: [{ productId: "aaaa-bbbb-cccc-dddd", slug: "pro" }],
154
+ successUrl: "/dashboard?checkout=success",
155
+ failureUrl: "/dashboard?checkout=failure",
156
+ authenticatedUsersOnly: true,
157
+ contactInformationType: "EMAIL",
158
+ customFields: { source: "website" },
159
+ });
160
+ ```
161
+
162
+ ### Client Usage
163
+
164
+ ```typescript
165
+ // By slug (maps to a productId configured on the server)
166
+ const { data } = await authClient.checkout({ slug: "pro" });
167
+ window.location.href = data.url;
168
+
169
+ // By product UUID
170
+ const { data } = await authClient.checkout({
171
+ products: "aaaa-bbbb-cccc-dddd",
172
+ });
173
+
174
+ // Multiple products with quantities
175
+ const { data } = await authClient.checkout({
176
+ products: [
177
+ { productId: "aaaa-bbbb-cccc-dddd", quantity: 2 },
178
+ ],
179
+ });
180
+
181
+ // With metadata and reference ID
182
+ const { data } = await authClient.checkout({
183
+ slug: "pro",
184
+ referenceId: organizationId,
185
+ metadata: { campaign: "spring-sale" },
186
+ });
187
+ ```
188
+
189
+ ### Checkout Options
190
+
191
+ | Option | Type | Description |
192
+ | -------------------------- | ---------------------------------- | ------------------------------------------------------ |
193
+ | `products` | `StreamPayProduct[]` or `function` | Slug-to-productId mappings |
194
+ | `successUrl` | `string` | Redirect URL on successful payment |
195
+ | `failureUrl` | `string` | Redirect URL on failed payment |
196
+ | `authenticatedUsersOnly` | `boolean` | Reject unauthenticated/anonymous users |
197
+ | `contactInformationType` | `"EMAIL" \| "PHONE"` | Contact info to collect during checkout |
198
+ | `customFields` | `Record<string, unknown>` | Static fields forwarded on every payment link |
199
+
200
+ ### Checkout Request Body
201
+
202
+ | Field | Type | Description |
203
+ | ---------------------- | ---------------------------------- | ---------------------------------------- |
204
+ | `slug` | `string` | Product slug (resolved server-side) |
205
+ | `products` | `string \| string[] \| object[]` | Product UUID(s) with optional quantity |
206
+ | `referenceId` | `string` | Custom reference (stored in metadata) |
207
+ | `consumerId` | `string` | Override consumer ID |
208
+ | `name` | `string` | Payment link display name |
209
+ | `description` | `string` | Payment link description |
210
+ | `metadata` | `Record<string, string\|number\|boolean>` | Custom key-value metadata |
211
+ | `successUrl` | `string` | Override success redirect |
212
+ | `failureUrl` | `string` | Override failure redirect |
213
+ | `maxNumberOfPayments` | `number` | Limit number of payments on this link |
214
+ | `validUntil` | `string` | ISO 8601 expiration datetime |
215
+ | `couponIds` | `string[]` | Coupon UUIDs to apply |
216
+ | `redirect` | `boolean` | Whether to auto-redirect (default: true) |
217
+
218
+ ## Portal Plugin
219
+
220
+ ```typescript
221
+ portal();
222
+
223
+ // With custom lookup depth for legacy users
224
+ portal({ consumerLookupMaxPages: 20 });
225
+ ```
226
+
227
+ ### Client Usage
228
+
229
+ ```typescript
230
+ // Get consumer state
231
+ const { data: consumer } = await authClient.state();
232
+
233
+ // List subscriptions (paginated)
234
+ const { data: subs } = await authClient.subscriptions({
235
+ query: { page: 1, limit: 20 },
236
+ });
237
+
238
+ // List invoices (paginated)
239
+ const { data: invoices } = await authClient.invoices({
240
+ query: { page: 1, limit: 20 },
241
+ });
242
+
243
+ // List payments
244
+ const { data: payments } = await authClient.payments();
245
+ ```
246
+
247
+ ## Subscriptions Plugin
248
+
249
+ ```typescript
250
+ subscriptions();
251
+ ```
252
+
253
+ ### Client Usage
254
+
255
+ ```typescript
256
+ // Cancel a subscription
257
+ await authClient.cancelSubscription({
258
+ subscriptionId: "sub-uuid",
259
+ cancelRelatedInvoices: true,
260
+ });
261
+
262
+ // Freeze a subscription
263
+ await authClient.freezeSubscription({
264
+ subscriptionId: "sub-uuid",
265
+ freezeStartDatetime: "2026-06-01T00:00:00Z",
266
+ freezeEndDatetime: "2026-07-01T00:00:00Z",
267
+ notes: "Customer vacation",
268
+ });
269
+ ```
270
+
271
+ ## Webhooks Plugin
272
+
273
+ ```typescript
274
+ webhooks({
275
+ secret: process.env.STREAMPAY_WEBHOOK_SECRET!,
276
+ toleranceSeconds: 300, // Replay protection window (default: 300s)
277
+
278
+ // Catch-all handler (runs before event-specific handlers)
279
+ onPayload: async (payload) => {
280
+ console.log(`Received: ${payload.event_type}`);
281
+ },
282
+
283
+ // Payment events
284
+ onPaymentSucceeded: async (payload) => {},
285
+ onPaymentFailed: async (payload) => {},
286
+ onPaymentCanceled: async (payload) => {},
287
+ onPaymentRefunded: async (payload) => {},
288
+ onPaymentMarkedAsPaid: async (payload) => {},
289
+
290
+ // Invoice events
291
+ onInvoiceCreated: async (payload) => {},
292
+ onInvoiceSent: async (payload) => {},
293
+ onInvoiceAccepted: async (payload) => {},
294
+ onInvoiceRejected: async (payload) => {},
295
+ onInvoiceCompleted: async (payload) => {},
296
+ onInvoiceCanceled: async (payload) => {},
297
+ onInvoiceUpdated: async (payload) => {},
298
+
299
+ // Subscription events
300
+ onSubscriptionCreated: async (payload) => {},
301
+ onSubscriptionActivated: async (payload) => {},
302
+ onSubscriptionInactivated: async (payload) => {},
303
+ onSubscriptionCanceled: async (payload) => {},
304
+ onSubscriptionFrozen: async (payload) => {},
305
+ onSubscriptionCycleRenewalFailed: async (payload) => {},
306
+ onSubscriptionCancelAtPeriodEnd: async (payload) => {},
307
+ onSubscriptionFreezeNow: async (payload) => {},
308
+ onSubscriptionUnfreezeNow: async (payload) => {},
309
+ onSubscriptionUnfreezeFuture: async (payload) => {},
310
+ onSubscriptionFreezeCancel: async (payload) => {},
311
+
312
+ // Payment link events
313
+ onPaymentLinkPayAttemptFailed: async (payload) => {},
314
+ });
315
+ ```
316
+
317
+ ### Webhook Configuration
318
+
319
+ Register `https://your-app.com/api/auth/streampay/webhooks` as the webhook URL in your [StreamPay dashboard](https://streampay.sa).
320
+
321
+ ### Webhook Payload Shape
322
+
323
+ ```typescript
324
+ interface StreamPayWebhookPayload<T = Record<string, unknown>> {
325
+ event_type: StreamPayEventType; // e.g. "PAYMENT_SUCCEEDED"
326
+ entity_type: StreamPayEntityType; // "PAYMENT" | "INVOICE" | "SUBSCRIPTION" | "PAYMENT_LINK"
327
+ entity_id: string;
328
+ entity_url: string;
329
+ status: string;
330
+ data: T;
331
+ timestamp: string; // ISO 8601
332
+ }
333
+ ```
334
+
335
+ ### Signature Verification
336
+
337
+ Webhooks are verified using HMAC-SHA256 with replay protection. The signature header format is `t=<timestamp>,v1=<hex-hmac>`.
338
+
339
+ ## Endpoints
340
+
341
+ | Key | Method | Path | Auth | Plugin |
342
+ | --------------------- | ------ | --------------------------------- | --------- | ----------------- |
343
+ | `checkout` | POST | `/checkout` | Optional | `checkout()` |
344
+ | `state` | GET | `/consumer/state` | Required | `portal()` |
345
+ | `subscriptions` | GET | `/consumer/subscriptions/list` | Required | `portal()` |
346
+ | `invoices` | GET | `/consumer/invoices/list` | Required | `portal()` |
347
+ | `payments` | GET | `/consumer/payments/list` | Required | `portal()` |
348
+ | `cancelSubscription` | POST | `/consumer/subscriptions/cancel` | Required | `subscriptions()` |
349
+ | `freezeSubscription` | POST | `/consumer/subscriptions/freeze` | Required | `subscriptions()` |
350
+ | `streampayWebhooks` | POST | `/streampay/webhooks` | Signature | `webhooks()` |
351
+
352
+ ## Standalone Exports
353
+
354
+ These utilities can be used independently, outside the plugin context:
355
+
356
+ ### Webhook Verification
357
+
358
+ ```typescript
359
+ import {
360
+ verifyWebhook,
361
+ verifyWebhookOrThrow,
362
+ StreamPayWebhookError,
363
+ } from "better-auth-streampay";
364
+
365
+ // Result-based (no exceptions)
366
+ const result = verifyWebhook({
367
+ secret: "your-secret",
368
+ rawBody: '{"event_type":"PAYMENT_SUCCEEDED",...}',
369
+ signatureHeader: request.headers.get("X-Webhook-Signature"),
370
+ toleranceSeconds: 300,
371
+ });
372
+
373
+ if (result.ok) {
374
+ console.log("Valid, timestamp:", result.timestamp);
375
+ } else {
376
+ console.log("Invalid:", result.reason);
377
+ // "MISSING_HEADER" | "MALFORMED_HEADER" | "INVALID_TIMESTAMP" | "EXPIRED" | "INVALID_SIGNATURE"
378
+ }
379
+
380
+ // Exception-based
381
+ try {
382
+ const timestamp = verifyWebhookOrThrow({
383
+ secret: "your-secret",
384
+ rawBody,
385
+ signatureHeader,
386
+ });
387
+ } catch (err) {
388
+ if (err instanceof StreamPayWebhookError) {
389
+ console.log(err.reason);
390
+ }
391
+ }
392
+ ```
393
+
394
+ ### Webhook Dispatch
395
+
396
+ ```typescript
397
+ import { dispatchWebhook } from "better-auth-streampay";
398
+
399
+ await dispatchWebhook(payload, {
400
+ onPayload: async (p) => { /* catch-all */ },
401
+ onPaymentSucceeded: async (p) => { /* specific */ },
402
+ });
403
+ ```
404
+
405
+ ### Consumer Lookup
406
+
407
+ ```typescript
408
+ import {
409
+ findConsumerByExternalId,
410
+ findConsumerByIdentifiers,
411
+ } from "better-auth-streampay";
412
+
413
+ // By external ID (returns consumer ID or null)
414
+ const consumerId = await findConsumerByExternalId(client, {
415
+ externalId: "user-123",
416
+ maxPages: 10,
417
+ pageSize: 100,
418
+ });
419
+
420
+ // By any identifier (returns full ConsumerResponse or null)
421
+ const consumer = await findConsumerByIdentifiers(client, {
422
+ email: "user@example.com",
423
+ phone_number: "+966501234567",
424
+ external_id: "user-123",
425
+ iban: "SA...",
426
+ });
427
+ ```
428
+
429
+ ### Error Formatting
430
+
431
+ ```typescript
432
+ import { formatStreamPayError } from "better-auth-streampay";
433
+
434
+ try {
435
+ await client.createConsumer(input);
436
+ } catch (err) {
437
+ console.error(formatStreamPayError(err));
438
+ }
439
+ ```
440
+
441
+ ### Constants & Types
442
+
443
+ ```typescript
444
+ import {
445
+ STREAMPAY_EVENT_TYPES,
446
+ type StreamPayEventType,
447
+ type StreamPayEntityType,
448
+ type StreamPayWebhookPayload,
449
+ type WebhookHandler,
450
+ type WebhookHandlers,
451
+ type StreamPayOptions,
452
+ type StreamPayProduct,
453
+ type CheckoutOptions,
454
+ type CheckoutParams,
455
+ type ConsumerCreateOverrides,
456
+ type VerifyWebhookInput,
457
+ type VerifyWebhookResult,
458
+ type VerifyFailureReason,
459
+ } from "better-auth-streampay";
460
+ ```
461
+
462
+ ## Testing
463
+
464
+ ```bash
465
+ pnpm test # vitest run
466
+ pnpm typecheck # tsc --noEmit
467
+ pnpm lint # biome check
468
+ pnpm build # tsup (ESM + CJS)
469
+ ```
470
+
471
+ ## License
472
+
473
+ MIT
@@ -0,0 +1,13 @@
1
+ 'use strict';
2
+
3
+ // src/client.ts
4
+ var streampayClient = () => {
5
+ return {
6
+ id: "streampay-client",
7
+ $InferServerPlugin: {}
8
+ };
9
+ };
10
+
11
+ exports.streampayClient = streampayClient;
12
+ //# sourceMappingURL=client.cjs.map
13
+ //# sourceMappingURL=client.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/client.ts"],"names":[],"mappings":";;;AAGO,IAAM,kBAAkB,MAAM;AACpC,EAAA,OAAO;AAAA,IACN,EAAA,EAAI,kBAAA;AAAA,IACJ,oBAAoB;AAAC,GACtB;AACD","file":"client.cjs","sourcesContent":["import type { BetterAuthClientPlugin } from \"better-auth\";\nimport type { streampay } from \"./streampay\";\n\nexport const streampayClient = () => {\n\treturn {\n\t\tid: \"streampay-client\",\n\t\t$InferServerPlugin: {} as ReturnType<typeof streampay>,\n\t} satisfies BetterAuthClientPlugin;\n};\n"]}
@@ -0,0 +1,12 @@
1
+ import { s as streampay } from './streampay-DFc4fN8R.cjs';
2
+ import 'better-auth';
3
+ import 'zod/v4/core';
4
+ import 'zod';
5
+ import '@streamsdk/typescript';
6
+
7
+ declare const streampayClient: () => {
8
+ id: "streampay-client";
9
+ $InferServerPlugin: ReturnType<typeof streampay>;
10
+ };
11
+
12
+ export { streampayClient };
@@ -0,0 +1,12 @@
1
+ import { s as streampay } from './streampay-DFc4fN8R.js';
2
+ import 'better-auth';
3
+ import 'zod/v4/core';
4
+ import 'zod';
5
+ import '@streamsdk/typescript';
6
+
7
+ declare const streampayClient: () => {
8
+ id: "streampay-client";
9
+ $InferServerPlugin: ReturnType<typeof streampay>;
10
+ };
11
+
12
+ export { streampayClient };
package/dist/client.js ADDED
@@ -0,0 +1,11 @@
1
+ // src/client.ts
2
+ var streampayClient = () => {
3
+ return {
4
+ id: "streampay-client",
5
+ $InferServerPlugin: {}
6
+ };
7
+ };
8
+
9
+ export { streampayClient };
10
+ //# sourceMappingURL=client.js.map
11
+ //# sourceMappingURL=client.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/client.ts"],"names":[],"mappings":";AAGO,IAAM,kBAAkB,MAAM;AACpC,EAAA,OAAO;AAAA,IACN,EAAA,EAAI,kBAAA;AAAA,IACJ,oBAAoB;AAAC,GACtB;AACD","file":"client.js","sourcesContent":["import type { BetterAuthClientPlugin } from \"better-auth\";\nimport type { streampay } from \"./streampay\";\n\nexport const streampayClient = () => {\n\treturn {\n\t\tid: \"streampay-client\",\n\t\t$InferServerPlugin: {} as ReturnType<typeof streampay>,\n\t} satisfies BetterAuthClientPlugin;\n};\n"]}