better-auth-paystack 0.0.0 → 3.2.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.
Files changed (35) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +919 -0
  3. package/dist/client.d.mts +151 -0
  4. package/dist/client.d.mts.map +1 -0
  5. package/dist/client.mjs +129 -0
  6. package/dist/client.mjs.map +1 -0
  7. package/dist/index-CXuHlFoy.d.mts +858 -0
  8. package/dist/index-CXuHlFoy.d.mts.map +1 -0
  9. package/dist/index.d.mts +2 -0
  10. package/dist/index.mjs +3288 -0
  11. package/dist/index.mjs.map +1 -0
  12. package/dist/version-BYbIySEf.mjs +73 -0
  13. package/dist/version-BYbIySEf.mjs.map +1 -0
  14. package/package.json +118 -8
  15. package/skills/better-auth-paystack-setup/SKILL.md +144 -0
  16. package/skills/better-auth-paystack-setup/agents/openai.yaml +6 -0
  17. package/skills/paystack-billing-flows/SKILL.md +154 -0
  18. package/skills/paystack-billing-flows/agents/openai.yaml +6 -0
  19. package/skills/paystack-catalog-limits/SKILL.md +183 -0
  20. package/skills/paystack-catalog-limits/agents/openai.yaml +6 -0
  21. package/skills/paystack-client-api/SKILL.md +120 -0
  22. package/skills/paystack-client-api/agents/openai.yaml +6 -0
  23. package/skills/paystack-local-subscriptions/SKILL.md +97 -0
  24. package/skills/paystack-local-subscriptions/agents/openai.yaml +6 -0
  25. package/skills/paystack-organization-billing/SKILL.md +159 -0
  26. package/skills/paystack-organization-billing/agents/openai.yaml +6 -0
  27. package/skills/paystack-schema-migrations/SKILL.md +94 -0
  28. package/skills/paystack-schema-migrations/agents/openai.yaml +6 -0
  29. package/skills/paystack-tanstack-start/SKILL.md +170 -0
  30. package/skills/paystack-tanstack-start/agents/openai.yaml +6 -0
  31. package/skills/paystack-testing-fixtures/SKILL.md +97 -0
  32. package/skills/paystack-testing-fixtures/agents/openai.yaml +6 -0
  33. package/skills/paystack-webhooks-events/SKILL.md +106 -0
  34. package/skills/paystack-webhooks-events/agents/openai.yaml +6 -0
  35. package/index.js +0 -1
package/README.md ADDED
@@ -0,0 +1,919 @@
1
+ # Better Auth Paystack Plugin
2
+
3
+ A TypeScript-first plugin that integrates Paystack into [Better Auth](https://www.better-auth.com), providing a production-ready billing system with support for subscriptions (native & local), one-time payments, trials, organization billing, and secure webhooks.
4
+
5
+ <div align="center">
6
+
7
+ ![npm downloads](https://img.shields.io/npm/dm/better-auth-paystack.svg)
8
+ [![GitHub stars](https://img.shields.io/github/stars/alexasomba/better-auth-paystack.svg?style=social&label=Star)](https://github.com/alexasomba/better-auth-paystack/stargazers)
9
+ [![GitHub release](https://img.shields.io/github/v/release/alexasomba/better-auth-paystack)](https://github.com/alexasomba/better-auth-paystack/releases)
10
+ [![bundlephobia](https://img.shields.io/bundlephobia/minzip/better-auth-paystack)](https://bundlephobia.com/result?p=better-auth-paystack)
11
+ [![Follow on Twitter](https://img.shields.io/twitter/follow/alexasomba?style=social)](https://twitter.com/alexasomba)
12
+ ![GitHub License](https://img.shields.io/github/license/alexasomba/better-auth-paystack)
13
+
14
+ </div>
15
+
16
+ [**Live Demo (Tanstack Start)**](https://better-auth-paystack.gittech.workers.dev) | [**Source Code**](https://github.com/alexasomba/better-auth-paystack/tree/main/examples/tanstack)
17
+
18
+ ## AI Agent Skills
19
+
20
+ This package publishes agent skills so AI coding agents can load package-specific guidance for setup, subscriptions, organization billing, TanStack Start integration, client APIs, webhooks, local subscription lifecycle, schema changes, and testing.
21
+
22
+ Use [TanStack Intent](https://www.npmjs.com/package/@tanstack/intent) when you want to explicitly list or load individual skills:
23
+
24
+ ```bash
25
+ npx @tanstack/intent@latest list
26
+ npx @tanstack/intent@latest load better-auth-paystack#better-auth-paystack-setup
27
+ npx @tanstack/intent@latest load better-auth-paystack#paystack-testing-fixtures
28
+ ```
29
+
30
+ If you use an AI agent, run `npx @tanstack/intent@latest install` in your project so the agent knows how to discover package skills.
31
+
32
+ This package also ships skills in the npm package under `skills/*/SKILL.md`, so projects can use [skills-npm](https://www.npmjs.com/package/skills-npm) to symlink installed package skills for compatible agents:
33
+
34
+ ```bash
35
+ npm install better-auth-paystack
36
+ npx skills-npm --yes
37
+ ```
38
+
39
+ For this repository, maintainers can run `pnpm run skills:dry-run` to preview discovery through the TanStack example fixture or `pnpm run skills:install` to create local agent skill symlinks from that fixture.
40
+
41
+ ## Features
42
+
43
+ - [x] **Billing Patterns**: Support for Paystack-native plans, local-managed subscriptions, and one-time payments (products/amounts).
44
+ - [x] **Auto Customer Creation**: Optional Paystack customer creation on user sign up or organization creation.
45
+ - [x] **Trial Management**: Configurable trial periods with built-in abuse prevention logic.
46
+ - [x] **Organization Billing**: Associate subscriptions with organizations and authorize access via roles.
47
+ - [x] **Subscription Channel Controls**: Restrict subscription checkout to specific Paystack payment channels such as card-only.
48
+ - [x] **Enforced Limits & Seats**: Automatic enforcement of member seat upgrades and resource limits (teams).
49
+ - [x] **Scheduled Changes**: Defer subscription updates or cancellations to the end of the billing cycle.
50
+ - [x] **Proration**: Immediate mid-cycle prorated upgrades for local plans, using saved-card charges when possible and checkout fallback when interactive payment is required.
51
+ - [x] **Popup Modal Flow**: Optional support for Paystack's inline checkout experience via `@alexasomba/paystack-inline`.
52
+ - [x] **Webhook Security**: Pre-configured signature verification (HMAC-SHA512) and optional IP whitelisting.
53
+ - [x] **Transaction History**: Built-in support for listing and viewing local transaction records.
54
+
55
+ ---
56
+
57
+ ## Quick Start
58
+
59
+ ### Prerequisites
60
+
61
+ - **Node.js**: `v22.0.0` or higher.
62
+ - **Better Auth**: `v1.6.9` or higher.
63
+
64
+ ### 1. Install Plugin & SDKs
65
+
66
+ ```bash
67
+ npm install better-auth better-auth-paystack @alexasomba/paystack-node
68
+ ```
69
+
70
+ #### Migrating from the scoped package
71
+
72
+ Replace the scoped dependency with the unscoped package:
73
+
74
+ ```bash
75
+ npm uninstall @alexasomba/better-auth-paystack
76
+ npm install better-auth-paystack
77
+ ```
78
+
79
+ Then update imports from `@alexasomba/better-auth-paystack` to `better-auth-paystack` and from
80
+ `@alexasomba/better-auth-paystack/client` to `better-auth-paystack/client`.
81
+
82
+ This is a package-name migration. The v4 release also moves Paystack billing data into
83
+ provider-owned tables. Existing client route names remain compatible, but a database migration
84
+ and the trusted migration operation described below are required.
85
+
86
+ #### Optional: Browser SDK (for Popup Modals)
87
+
88
+ ```bash
89
+ npm install @alexasomba/paystack-inline
90
+ ```
91
+
92
+ ### 2. Configure Environment Variables
93
+
94
+ ```env
95
+ PAYSTACK_SECRET_KEY=sk_test_...
96
+ BETTER_AUTH_SECRET=...
97
+ BETTER_AUTH_URL=http://localhost:8787
98
+ ```
99
+
100
+ ### 3. Setup Server Plugin
101
+
102
+ ```ts title="auth.ts"
103
+ import { betterAuth } from "better-auth";
104
+ import { paystack } from "better-auth-paystack";
105
+ import { createPaystack } from "@alexasomba/paystack-node";
106
+ import { admin } from "better-auth/plugins";
107
+
108
+ const paystackClient = createPaystack({
109
+ secretKey: process.env.PAYSTACK_SECRET_KEY!,
110
+ });
111
+
112
+ export const auth = betterAuth({
113
+ plugins: [
114
+ admin(),
115
+ paystack({
116
+ paystackClient,
117
+ secretKey: process.env.PAYSTACK_SECRET_KEY!,
118
+ createCustomerOnSignUp: true,
119
+ subscription: {
120
+ enabled: true,
121
+ allowedPaymentChannels: ["card"], // Optional: enforce card-only subscriptions
122
+ plans: [
123
+ {
124
+ name: "pro",
125
+ group: "workspace", // Optional: one active/trialing subscription per group
126
+ planCode: "PLN_pro_123", // Native: Managed by Paystack
127
+ freeTrial: { days: 14 },
128
+ limits: { teams: 5, seats: 10 }, // Custom resource & member limits
129
+ },
130
+ {
131
+ name: "starter",
132
+ amount: 50000, // Local: Managed by your app (500 NGN)
133
+ currency: "NGN",
134
+ interval: "monthly",
135
+ },
136
+ ],
137
+ },
138
+ products: {
139
+ products: [{ name: "credits_50", amount: 200000, currency: "NGN" }],
140
+ },
141
+ }),
142
+ ],
143
+ });
144
+ ```
145
+
146
+ Paystack signs webhook payloads with the same `PAYSTACK_SECRET_KEY` used for API authentication;
147
+ there is no separate webhook secret. Legacy `webhook.secret` and `paystackWebhookSecret` options
148
+ are accepted for source compatibility but ignored.
149
+
150
+ ### 4. Configure Client Plugin
151
+
152
+ ```ts title="client.ts"
153
+ import { createAuthClient } from "better-auth/client";
154
+ import { paystackClient } from "better-auth-paystack/client";
155
+ import { adminClient } from "better-auth/client/plugins";
156
+
157
+ export const client = createAuthClient({
158
+ plugins: [adminClient(), paystackClient({ subscription: true })],
159
+ });
160
+ ```
161
+
162
+ ### 5. Migrate Database Schema
163
+
164
+ ```bash
165
+ npx better-auth migrate
166
+ ```
167
+
168
+ ---
169
+
170
+ ## Migration Guide
171
+
172
+ Version `2.0.0` contains a security-focused breaking change.
173
+
174
+ - Removed public/client operator actions:
175
+ - `authClient.paystack.syncProducts()`
176
+ - `authClient.paystack.syncPlans()`
177
+ - `authClient.paystack.chargeRecurringSubscription(...)`
178
+ - Removed public Better Auth endpoints for:
179
+ - `/paystack/sync-products`
180
+ - `/paystack/sync-plans`
181
+ - `/paystack/charge-recurring`
182
+ - Added trusted server operations:
183
+ - `chargeSubscriptionRenewal`
184
+ - `syncPaystackProducts`
185
+ - `syncPaystackPlans`
186
+
187
+ ### Old
188
+
189
+ ```ts
190
+ await authClient.paystack.syncProducts();
191
+ await authClient.paystack.syncPlans();
192
+ await authClient.paystack.chargeRecurringSubscription({
193
+ subscriptionId: "sub_123",
194
+ });
195
+ ```
196
+
197
+ ### New
198
+
199
+ ```ts
200
+ import {
201
+ chargeSubscriptionRenewal,
202
+ syncPaystackPlans,
203
+ syncPaystackProducts,
204
+ type ChargeRecurringSubscriptionResult,
205
+ type PaystackSyncResult,
206
+ } from "better-auth-paystack";
207
+
208
+ const ctx = { context: await auth.$context } as any;
209
+ const paystackOptions = {
210
+ secretKey: process.env.PAYSTACK_SECRET_KEY!,
211
+ paystackClient,
212
+ };
213
+
214
+ await syncPaystackProducts(ctx, paystackOptions);
215
+ await syncPaystackPlans(ctx, paystackOptions);
216
+ await chargeSubscriptionRenewal(ctx, paystackOptions, {
217
+ subscriptionId: "sub_123",
218
+ });
219
+ ```
220
+
221
+ These operations are intentionally server-only. Do not expose them through browser-triggered auth client calls.
222
+
223
+ ---
224
+
225
+ ## Billing Patterns
226
+
227
+ ### 1. Subscriptions
228
+
229
+ #### Native (Recommended)
230
+
231
+ Use `planCode` from your Paystack Dashboard. Paystack handles the recurring logic and emails.
232
+
233
+ ```ts
234
+ { name: "pro", planCode: "PLN_xxx" }
235
+ ```
236
+
237
+ #### Local
238
+
239
+ Use `amount` and `interval`. The plugin stores the status locally, allowing you to manage custom recurring logic or one-off "access periods".
240
+
241
+ ```ts
242
+ { name: "starter", amount: 50000, interval: "monthly" }
243
+ ```
244
+
245
+ ### 2. One-Time Payments
246
+
247
+ #### Fixed Products
248
+
249
+ Define pre-configured products in your server settings and purchase them by name.
250
+
251
+ ```ts
252
+ await authClient.paystack.transaction.initialize({
253
+ product: "credits_50",
254
+ });
255
+ ```
256
+
257
+ #### Ad-hoc Amounts
258
+
259
+ Charge dynamic amounts for top-ups, tips, or custom invoices.
260
+
261
+ ```ts
262
+ await authClient.paystack.transaction.initialize({
263
+ amount: 100000, // 1000 NGN
264
+ currency: "NGN",
265
+ metadata: { type: "donation" },
266
+ });
267
+ ```
268
+
269
+ ---
270
+
271
+ ## Limits & Seat Management
272
+
273
+ The plugin automatically enforces limits across active and trialing subscriptions. When multiple
274
+ subscription groups define the same numeric limit, the highest value wins; plan features are
275
+ combined.
276
+
277
+ ### Member Seat Limits
278
+
279
+ Purchased seats are stored in the `subscription.seats` field. The plugin hooks into `member.create` and `invitation.create` to block additions once the limit is reached.
280
+
281
+ ### Resource Limits (e.g., Teams)
282
+
283
+ Define limits in your plan config, and they will be checked during resource creation:
284
+
285
+ ```ts
286
+ plans: [{ name: "pro", limits: { teams: 5, seats: 10 } }];
287
+ ```
288
+
289
+ The plugin natively checks the `teams` limit if using the Better Auth Organization plugin.
290
+
291
+ ### Subscription Groups
292
+
293
+ Set `group` on related plans when a user or organization may own independent subscriptions:
294
+
295
+ ```ts
296
+ plans: [
297
+ { name: "pro", group: "workspace", planCode: "PLN_pro" },
298
+ { name: "priority-support", group: "support", planCode: "PLN_support" },
299
+ ];
300
+ ```
301
+
302
+ Group names are trimmed and lowercased. A reference can have one active or trialing subscription
303
+ per group. Plans without `group` remain in the legacy default group, represented by a nullable
304
+ `subscription.groupId`, so existing configurations keep their previous single-subscription
305
+ behavior.
306
+
307
+ ---
308
+
309
+ ## Currency Support
310
+
311
+ The plugin supports the following currencies with automatic minimum transaction amount validation:
312
+
313
+ | Currency | Name | Minimum Amount |
314
+ | -------- | ---------------------- | -------------- |
315
+ | **NGN** | Nigerian Naira | ₦50.00 |
316
+ | **GHS** | Ghanaian Cedi | ₵0.10 |
317
+ | **ZAR** | South African Rand | R1.00 |
318
+ | **KES** | Kenyan Shilling | KSh 3.00 |
319
+ | **USD** | United States Dollar | $2.00 |
320
+ | **XOF** | West African CFA Franc | CFA 100 |
321
+
322
+ Transactions below these thresholds will be rejected with a `BAD_REQUEST` error.
323
+
324
+ ## Advanced Usage
325
+
326
+ ### Organization Billing
327
+
328
+ Enable `organization.enabled` to bill organizations instead of users.
329
+
330
+ - **Auto Customer**: Organizations get their own provider-owned `paystackCustomer` record.
331
+ - **Authorization**: Organization owners and admins can manage billing by default. Use `organization.billingRoles` to extend the trusted role list, or `subscription.authorizeReference` when you need fully custom authorization.
332
+
333
+ ```ts
334
+ paystack({
335
+ subscription: {
336
+ enabled: true,
337
+ plans: [],
338
+ },
339
+ organization: {
340
+ enabled: true,
341
+ billingRoles: ["owner", "admin", "billing"],
342
+ },
343
+ });
344
+ ```
345
+
346
+ ### Inline Popup Modal
347
+
348
+ Use `@alexasomba/paystack-inline` for a seamless UI.
349
+
350
+ ```ts
351
+ const { data } = await authClient.subscription.upgrade({ plan: "pro" });
352
+ if (data?.kind === "checkout") {
353
+ const paystack = createPaystack({ publicKey: "pk_test_..." });
354
+ paystack.checkout({
355
+ accessCode: data.accessCode,
356
+ onSuccess: (res) => authClient.paystack.transaction.verify({ reference: res.reference }),
357
+ });
358
+ }
359
+ ```
360
+
361
+ ### Scheduled Changes & Cancellation
362
+
363
+ Defer changes to the end of the current billing cycle:
364
+
365
+ - **Upgrades**: Pass `scheduleAtPeriodEnd: true` in `initializeTransaction()`.
366
+ - **Cancellations**: Use `authClient.subscription.cancel({ subscriptionCode, atPeriodEnd: true })` to keep the subscription active until the period ends.
367
+
368
+ ### Mid-Cycle Proration (`prorateAndCharge`)
369
+
370
+ The plugin can dynamically calculate the cost difference for immediate mid-cycle upgrades (like adding more seats).
371
+ For locally managed plans:
372
+
373
+ - If the subscription already has a reusable Paystack authorization code, the plugin charges the prorated delta off-session, records a local `paystackTransaction`, and immediately updates the subscription.
374
+ - If there is no reusable authorization code available (for example, transfer-based payments), the plugin initializes a new checkout for the prorated delta instead of silently upgrading without payment.
375
+ - If the prorated amount is below Paystack's minimum charge for the currency, the request is rejected so you can schedule the change for period end instead of undercharging.
376
+
377
+ ```ts
378
+ const { data } = await authClient.paystack.transaction.initialize({
379
+ plan: "pro",
380
+ quantity: 5, // Upgrading seats
381
+ prorateAndCharge: true, // Charges saved authorization or returns a checkout redirect for the delta
382
+ });
383
+
384
+ if (data?.kind === "checkout") {
385
+ window.location.href = data.url;
386
+ }
387
+
388
+ if (data?.kind === "prorated") {
389
+ console.log(data.message);
390
+ }
391
+ ```
392
+
393
+ When the flow falls back to checkout, verify the returned transaction reference after payment. The plugin uses the stored proration metadata to apply the pending plan/seat change only after successful verification.
394
+
395
+ ### Restricting Subscription Payment Channels
396
+
397
+ Use `subscription.allowedPaymentChannels` to constrain which Paystack checkout channels can be used for subscription flows.
398
+ This applies to standard subscription checkout, trial authorization flows, and interactive proration checkout fallbacks.
399
+
400
+ ```ts
401
+ paystack({
402
+ subscription: {
403
+ enabled: true,
404
+ allowedPaymentChannels: ["card"],
405
+ plans: [{ name: "starter", amount: 50000, currency: "NGN", interval: "monthly" }],
406
+ },
407
+ });
408
+ ```
409
+
410
+ If a subscription payment is later verified with a disallowed channel, the plugin rejects activation instead of silently creating the subscription.
411
+
412
+ ### Webhook Security
413
+
414
+ Webhook deliveries are persisted in the provider-specific `paystackWebhookEvent` table using a
415
+ stable hash of the verified raw payload. Duplicate deliveries that were already processed are
416
+ acknowledged without running billing side effects again. Failed or interrupted deliveries remain
417
+ pending for later reconciliation or replay handling.
418
+
419
+ The plugin automatically verifies the `x-paystack-signature` header to ensure events are authentic. For an extra layer of security, you can enable **IP Whitelisting** to restrict processing to Paystack's official servers.
420
+
421
+ ```ts
422
+ paystack({
423
+ secretKey: process.env.PAYSTACK_SECRET_KEY!,
424
+ webhook: {
425
+ verifyIP: true, // Enable IP whitelisting (defaults to false for flexible proxy support)
426
+ trustedIPs: ["52.31.139.75", "52.49.173.169", "52.214.14.220"], // Optional: override trusted IPs
427
+ },
428
+ });
429
+ ```
430
+
431
+ Webhook signatures are always verified with `secretKey`, as required by Paystack. Do not create or
432
+ configure a separate `PAYSTACK_WEBHOOK_SECRET`.
433
+
434
+ ### Trial Abuse Prevention
435
+
436
+ The plugin checks the `referenceId` history. If a trial was ever used (active, expired, or trialing), it will not be granted again, preventing resubscribe-abuse.
437
+
438
+ ### Lifecycle Hooks
439
+
440
+ React to billing events on the server by providing callbacks in your configuration:
441
+
442
+ #### Subscription Hooks (`subscription.*`)
443
+
444
+ - `onSubscriptionComplete`: Called after successful transaction verification (Native or Local).
445
+ - `onSubscriptionCreated`: Called when a subscription record is first initialized in the DB.
446
+ - `onSubscriptionUpdate`: Called after a persisted lifecycle change.
447
+ - `onSubscriptionCancel`: Called when a user or organization cancels their subscription.
448
+
449
+ #### Customer Hooks (`top-level` or `organization.*`)
450
+
451
+ - `onCustomerCreate`: Called after the plugin successfully creates a Paystack customer.
452
+ - `getCustomerCreateParams`: Return a custom object to override/extend the data sent to Paystack during customer creation.
453
+
454
+ #### Trial Hooks (`subscription.plans[].freeTrial.*`)
455
+
456
+ - `onTrialStart`: Called when a new trial period begins.
457
+ - `onTrialEnd`: Called when a trial converts to an active subscription.
458
+ - `onTrialExpired`: Called when a trial ends without conversion.
459
+
460
+ Application callback failures are logged after billing state is persisted and do not cause an
461
+ otherwise valid Paystack webhook to be replayed.
462
+
463
+ #### Global Hook
464
+
465
+ - `onEvent`: Receives every webhook event payload sent from Paystack for custom processing.
466
+
467
+ ### Trusted Server Operations
468
+
469
+ Recurring renewals and Paystack catalog sync are intentionally not exposed through the browser auth client.
470
+ Invoke them from trusted backend code only:
471
+
472
+ ```ts
473
+ import {
474
+ chargeSubscriptionRenewal,
475
+ reconcilePaystackTransaction,
476
+ syncPaystackPlans,
477
+ syncPaystackProducts,
478
+ } from "better-auth-paystack";
479
+
480
+ const ctx = { context: await auth.$context } as any;
481
+
482
+ await chargeSubscriptionRenewal(ctx, paystackOptions, {
483
+ subscriptionId: "sub_123",
484
+ });
485
+
486
+ const settlement = await reconcilePaystackTransaction(ctx, paystackOptions, {
487
+ reference: "PAYSTACK_REFERENCE",
488
+ source: "queue",
489
+ referenceId: "user_or_org_id",
490
+ });
491
+
492
+ if (settlement.ok) {
493
+ console.log(settlement.transaction.status, settlement.subscription.updated);
494
+ }
495
+
496
+ await syncPaystackProducts(ctx, paystackOptions);
497
+ await syncPaystackPlans(ctx, paystackOptions);
498
+ ```
499
+
500
+ Use `reconcilePaystackTransaction` from webhook handlers, queue retries, cron jobs, or admin actions when trusted server code needs the same verification and local transaction/subscription side effects as the browser verify endpoint.
501
+
502
+ ### Authorization & Security
503
+
504
+ #### `authorizeReference`
505
+
506
+ Control who can manage billing for specific references (Users or Organizations).
507
+
508
+ ```ts
509
+ paystack({
510
+ subscription: {
511
+ authorizeReference: async ({ user, referenceId, action }) => {
512
+ // Example: Only allow Org Admins to initialize transactions
513
+ if (referenceId.startsWith("org_")) {
514
+ const member = await db.findOne({
515
+ model: "member",
516
+ where: [
517
+ { field: "organizationId", value: referenceId },
518
+ { field: "userId", value: user.id },
519
+ ],
520
+ });
521
+ return member?.role === "admin";
522
+ }
523
+ return user.id === referenceId;
524
+ },
525
+ },
526
+ });
527
+ ```
528
+
529
+ ---
530
+
531
+ ## Client SDK Reference
532
+
533
+ The client plugin exposes fully typed canonical methods under `authClient.paystack`, `authClient.transaction`, and `authClient.subscription`.
534
+
535
+ - `authClient.transaction.initialize`, `verify`, `list`
536
+ - `authClient.subscription.create`, `upgrade`, `cancel`, `restore`, `list`, `billingPortal`
537
+ - `authClient.paystack.config`, `listProducts`, `listPlans`, plus the transaction/subscription helpers above
538
+
539
+ Legacy compatibility aliases remain available for migration, but new code should use the canonical methods:
540
+
541
+ - `authClient.subscription.disable(...)` -> use `authClient.subscription.cancel(...)`
542
+ - `authClient.subscription.enable(...)` -> use `authClient.subscription.restore(...)`
543
+
544
+ ### `authClient.subscription.upgrade` / `create`
545
+
546
+ Initializes a transaction to create or upgrade a subscription.
547
+
548
+ ```ts
549
+ type upgradeSubscription = {
550
+ /**
551
+ * The name of the plan to subscribe to.
552
+ */
553
+ plan: string;
554
+ /**
555
+ * The email of the subscriber. Defaults to the current user's email.
556
+ */
557
+ email?: string;
558
+ /**
559
+ * Amount to charge (if not using a Paystack Plan Code).
560
+ */
561
+ amount?: number;
562
+ /**
563
+ * Currency code (e.g., "NGN").
564
+ */
565
+ currency?: string;
566
+ /**
567
+ * The callback URL to redirect to after payment.
568
+ */
569
+ callbackURL?: string;
570
+ /**
571
+ * Additional metadata to store with the transaction.
572
+ */
573
+ metadata?: Record<string, unknown>;
574
+ /**
575
+ * Reference ID for the subscription owner (User ID or Org ID).
576
+ * Defaults to the current user's ID.
577
+ */
578
+ referenceId?: string;
579
+ /**
580
+ * Number of seats to purchase (for team plans).
581
+ */
582
+ quantity?: number;
583
+ };
584
+ ```
585
+
586
+ ### `authClient.paystack.transaction.initialize`
587
+
588
+ Same as `upgrade`, but can also be used for one-time payments by omitting `plan` and providing `amount` or `product`.
589
+
590
+ ```ts
591
+ type initializeTransaction = {
592
+ /**
593
+ * Plan name (for subscriptions).
594
+ */
595
+ plan?: string;
596
+ /**
597
+ * Product name (for one-time purchases).
598
+ */
599
+ product?: string;
600
+ /**
601
+ * Amount to charge (if sending raw amount).
602
+ */
603
+ amount?: number;
604
+ /**
605
+ * For existing locally managed subscriptions, calculate a mid-cycle delta and either
606
+ * charge the saved authorization or return a checkout redirect for interactive payment.
607
+ */
608
+ prorateAndCharge?: boolean;
609
+ // ... same as upgradeSubscription
610
+ };
611
+
612
+ type initializeTransactionResult =
613
+ | {
614
+ kind: "checkout";
615
+ url: string;
616
+ reference: string;
617
+ accessCode: string;
618
+ redirect: true;
619
+ }
620
+ | { kind: "scheduled"; status: "success"; message: string; scheduled: true }
621
+ | { kind: "prorated"; status: "success"; message: string; prorated: true };
622
+ ```
623
+
624
+ ### `authClient.subscription.list`
625
+
626
+ List subscriptions for a user or organization. Organization-scoped billing actions require an owner/admin membership by default. To allow roles such as `billing`, configure `organization.billingRoles`. For custom resources or deeper policy checks, configure `subscription.authorizeReference`.
627
+
628
+ ```ts
629
+ type listSubscriptions = {
630
+ query?: {
631
+ /**
632
+ * Filter by reference ID (User ID or Org ID).
633
+ */
634
+ referenceId?: string;
635
+ };
636
+ };
637
+ ```
638
+
639
+ ### `authClient.subscription.cancel` / `restore`
640
+
641
+ Cancel or restore a subscription.
642
+
643
+ - **Cancel**: Sets `cancelAtPeriodEnd: true`. The subscription remains `active` until the end of the current billing period, after which it moves to `canceled`.
644
+ - **Restore**: Reactivates a subscription that is scheduled to cancel.
645
+
646
+ ```ts
647
+ type cancelSubscription = {
648
+ /**
649
+ * Optional reference owner (user ID or org ID) when managing another billing entity.
650
+ */
651
+ referenceId?: string;
652
+ /**
653
+ * The Paystack subscription code (e.g. SUB_...)
654
+ */
655
+ subscriptionCode: string;
656
+ /**
657
+ * The email token required by Paystack to manage the subscription.
658
+ * Optional: The server will try to fetch it if omitted.
659
+ */
660
+ emailToken?: string;
661
+ /**
662
+ * When true, keep the subscription active until the current period ends.
663
+ */
664
+ atPeriodEnd?: boolean;
665
+ };
666
+ ```
667
+
668
+ ## Schema Reference
669
+
670
+ The plugin extends your database with the following fields and tables.
671
+
672
+ ### `user` and `organization`
673
+
674
+ Paystack customer codes are no longer added to Better Auth auth tables. Organization `email`
675
+ remains available for billing fallback.
676
+
677
+ | Field | Type | Required | Description |
678
+ | :------ | :------- | :------- | :--------------------------------------------------------------------------------- |
679
+ | `email` | `string` | No | The billing email for the organization. Falls back to the owner's email if absent. |
680
+
681
+ ### `paystackCustomer`
682
+
683
+ | Field | Type | Required | Description |
684
+ | :-------------- | :------- | :------- | :----------------------------------- |
685
+ | `referenceType` | `string` | Yes | `user` or `organization`. |
686
+ | `referenceId` | `string` | Yes | Owning Better Auth identifier. |
687
+ | `referenceKey` | `string` | Yes | Unique provider-owned reference key. |
688
+ | `customerCode` | `string` | Yes | Paystack customer code. |
689
+ | `email` | `string` | No | Billing email. |
690
+
691
+ ### `paystackPaymentCredential`
692
+
693
+ Payment credentials are stored separately as AES-256-GCM ciphertext. Plaintext values are not
694
+ returned by subscription APIs, callbacks, logs, or client actions. Set `credentialEncryptionKey`
695
+ to a dedicated production secret; the plugin falls back to `secretKey` for compatibility.
696
+
697
+ | Field | Type | Required | Description |
698
+ | :--------------------------- | :------- | :------- | :---------------------------------------- |
699
+ | `subscriptionId` | `string` | Yes | Unique Paystack subscription ID. |
700
+ | `authorizationCodeEncrypted` | `string` | No | Encrypted recurring-charge authorization. |
701
+ | `emailTokenEncrypted` | `string` | No | Encrypted subscription-management token. |
702
+
703
+ ### `paystackSubscription`
704
+
705
+ | Field | Type | Required | Description |
706
+ | :--------------------- | :-------- | :------- | :------------------------------------------------------------------- |
707
+ | `plan` | `string` | Yes | Lowercased name of the active plan. |
708
+ | `referenceId` | `string` | Yes | Associated User ID or Organization ID. |
709
+ | `userId` | `string` | Yes | User who initiated the subscription checkout. |
710
+ | `customerCode` | `string` | No | The Paystack customer code for this subscription. |
711
+ | `subscriptionCode` | `string` | No | The unique code for the subscription (e.g., `SUB_...` or `LOC_...`). |
712
+ | `transactionReference` | `string` | No | The reference of the transaction that started the subscription. |
713
+ | `planCode` | `string` | No | The Paystack plan code, when Paystack manages the subscription. |
714
+ | `status` | `string` | Yes | `active`, `trialing`, `canceled`, `incomplete`. |
715
+ | `periodStart` | `Date` | No | Start date of the current billing period. |
716
+ | `periodEnd` | `Date` | No | End date of the current billing period. |
717
+ | `trialStart` | `Date` | No | Start date of the trial period. |
718
+ | `trialEnd` | `Date` | No | End date of the trial period. |
719
+ | `cancelAtPeriodEnd` | `boolean` | No | Whether to cancel at the end of the current period. |
720
+ | `cancelAt` | `Date` | No | Scheduled cancellation timestamp. |
721
+ | `canceledAt` | `Date` | No | Cancellation timestamp. |
722
+ | `endedAt` | `Date` | No | Subscription end timestamp. |
723
+ | `billingInterval` | `string` | No | Billing interval used by the plan. |
724
+ | `groupId` | `string` | No | Optional subscription group. |
725
+ | `pendingPlan` | `string` | No | Plan pending a future lifecycle change. |
726
+ | `seats` | `number` | No | Purchased seat count for team billing. |
727
+ | `createdAt` | `Date` | Yes | Record creation timestamp. |
728
+ | `updatedAt` | `Date` | Yes | Record update timestamp. |
729
+
730
+ ### `paystackTransaction`
731
+
732
+ | Field | Type | Required | Description |
733
+ | :------------ | :------- | :------- | :--------------------------------------------------- |
734
+ | `reference` | `string` | Yes | Unique transaction reference. |
735
+ | `referenceId` | `string` | Yes | Associated User ID or Organization ID. |
736
+ | `userId` | `string` | Yes | The ID of the user who initiated the transaction. |
737
+ | `amount` | `number` | Yes | Transaction amount in smallest currency unit. |
738
+ | `currency` | `string` | Yes | Currency code (e.g., "NGN"). |
739
+ | `status` | `string` | Yes | `success`, `pending`, `failed`, `abandoned`. |
740
+ | `plan` | `string` | No | Name of the plan associated with the transaction. |
741
+ | `product` | `string` | No | Name of the product associated with the transaction. |
742
+ | `metadata` | `string` | No | JSON string of extra transaction metadata. |
743
+ | `paystackId` | `string` | No | The internal Paystack ID for the transaction. |
744
+ | `createdAt` | `Date` | Yes | Transaction creation timestamp. |
745
+ | `updatedAt` | `Date` | Yes | Transaction last update timestamp. |
746
+
747
+ ### `paystackProduct`
748
+
749
+ | Field | Type | Required | Description |
750
+ | :------------ | :-------- | :------- | :--------------------------------------- |
751
+ | `name` | `string` | Yes | Product name. |
752
+ | `description` | `string` | No | Product description. |
753
+ | `price` | `number` | Yes | Price in smallest currency unit. |
754
+ | `currency` | `string` | Yes | Currency code (e.g., "NGN"). |
755
+ | `quantity` | `number` | No | Available stock quantity. |
756
+ | `unlimited` | `boolean` | No | Whether the product has unlimited stock. |
757
+ | `paystackId` | `string` | No | The internal Paystack Product ID. |
758
+ | `slug` | `string` | Yes | Unique slug for the product. |
759
+ | `metadata` | `string` | No | JSON string of extra product metadata. |
760
+ | `createdAt` | `Date` | Yes | Product creation timestamp. |
761
+ | `updatedAt` | `Date` | Yes | Product last update timestamp. |
762
+
763
+ ### `paystackWebhookEvent`
764
+
765
+ The plugin records verified webhook deliveries with their event type, raw payload, reference (when
766
+ available), processing status, and processed timestamp. This table is provider-namespaced so the
767
+ Paystack and Flutterwave plugins can be installed together without sharing webhook state.
768
+
769
+ | Field | Type | Required | Description |
770
+ | :------------ | :------- | :------- | :----------------------------------------- |
771
+ | `eventId` | `string` | Yes | Stable hash of the exact verified payload. |
772
+ | `eventType` | `string` | Yes | Paystack event name. |
773
+ | `reference` | `string` | No | Transaction reference when available. |
774
+ | `payload` | `string` | Yes | Exact raw webhook payload. |
775
+ | `status` | `string` | Yes | `pending` or `processed`. |
776
+ | `processedAt` | `Date` | No | Processing completion timestamp. |
777
+
778
+ ### v4 schema migration
779
+
780
+ After upgrading the package, generate/apply the Better Auth schema first, then run the trusted
781
+ server-only operation:
782
+
783
+ ```ts
784
+ import { migratePaystackSubscriptionSchema } from "better-auth-paystack";
785
+
786
+ const report = await migratePaystackSubscriptionSchema(ctx, {
787
+ secretKey: process.env.PAYSTACK_SECRET_KEY!,
788
+ credentialEncryptionKey: process.env.PAYSTACK_CREDENTIAL_ENCRYPTION_KEY,
789
+ });
790
+ ```
791
+
792
+ Run it in this order:
793
+
794
+ 1. Upgrade the package.
795
+ 2. Run Better Auth schema generation/migration.
796
+ 3. Run `migratePaystackSubscriptionSchema()` from a trusted server job.
797
+ 4. Verify migration counts and billing behavior.
798
+ 5. Remove legacy columns/tables manually only after verification.
799
+
800
+ The operation preserves legacy rows, keeps original subscription IDs where possible, skips already
801
+ migrated records, encrypts legacy authorization/email tokens, and reports partial failures so a
802
+ later run can retry them.
803
+
804
+ During the compatibility window, customer resolution can still read legacy auth-table customer
805
+ codes. Remove those legacy columns manually after the migration has been verified.
806
+
807
+ ---
808
+
809
+ ## Troubleshooting
810
+
811
+ - **Webhook Signature**: Ensure `PAYSTACK_SECRET_KEY` matches the integration that sends the webhook. Paystack uses this API secret key for `x-paystack-signature`.
812
+ - **Email Verification**: Use `requireEmailVerification: true` to prevent unverified checkouts.
813
+ - **Redirect Failures**: Check your browser console; Paystack often returns 429 errors if you're hitting the test API too frequently.
814
+ - **Reference mismatches**: Ensure `referenceId` is passed correctly for Organization billing.
815
+ - **Authorization Denied**: Verify your `authorizeReference` logic is correctly checking user roles or organization memberships. Unauthorized attempts to verify transactions now return a `401 Unauthorized` response to prevent data leaks.
816
+
817
+ ### Database Indexing
818
+
819
+ The plugin's schema definition includes recommended indexes and uniqueness constraints for performance. When you run `npx better-auth migrate`, these will be automatically applied to your database.
820
+
821
+ After upgrading, run `npx better-auth migrate` (or `npx better-auth generate` for schema-managed
822
+ adapters). The additive `cancelAt`, `canceledAt`, `endedAt`, and `billingInterval` subscription
823
+ columns are nullable; historical rows are populated as future lifecycle events are processed.
824
+
825
+ The following fields are indexed:
826
+
827
+ - **`paystackTransaction`**: `reference` (unique), `userId`, `referenceId`.
828
+ - **`paystackSubscription`**: `subscriptionCode` (unique), `referenceId`, `transactionReference`, `customerCode`, `plan`.
829
+ - **`paystackCustomer`**: `referenceKey` (unique), `referenceId`, `customerCode` (unique).
830
+ - **`paystackPaymentCredential`**: `subscriptionId` (unique).
831
+ - **`paystackProduct`**: `slug` (unique), `paystackId` (unique).
832
+
833
+ Proration upgrades and trusted renewal charges also persist `paystackTransaction` rows, so local transaction history stays aligned with successful off-session charges.
834
+
835
+ ### Syncing Products
836
+
837
+ The plugin provides two ways to keep your product inventory aligned with Paystack:
838
+
839
+ #### 1. Automated Inventory Sync
840
+
841
+ Whenever a successful one-time payment is made (via webhook or manual verification), the plugin automatically calls **`syncProductQuantityFromPaystack`**. This fetches the real-time remaining quantity from the Paystack API and updates your local database record, ensuring your inventory is always accurate.
842
+
843
+ #### 2. Trusted Manual Bulk Sync
844
+
845
+ The public `/paystack/sync-products` endpoint was removed in `2.0.0`.
846
+ Run the trusted server operation from backend code instead:
847
+
848
+ ```ts
849
+ import { syncPaystackProducts } from "better-auth-paystack";
850
+
851
+ const ctx = { context: await auth.$context } as any;
852
+
853
+ await syncPaystackProducts(ctx, paystackOptions);
854
+ ```
855
+
856
+ ### SDK Compatibility Note
857
+
858
+ The plugin now targets the official `@alexasomba/paystack-node` grouped client surface directly.
859
+ If you inject a custom client, it should match the real SDK methods used by the plugin such as `transaction.initialize`, `transaction.verify`, `transaction.chargeAuthorization`, `subscription.create`, `subscription.disable`, and `subscription.enable`.
860
+
861
+ ---
862
+
863
+ ## 🏗️ Development & Contributing
864
+
865
+ This repository is powered by **Vite+**. You use the `vp` CLI to manage the entire workspace.
866
+
867
+ ```bash
868
+ # Install dependencies
869
+ vp i
870
+
871
+ # Check project health (format, lint, types)
872
+ vp check --fix
873
+
874
+ # Build the core library
875
+ vp build
876
+
877
+ # Run tests
878
+ vp test
879
+
880
+ # Run the TanStack Start example
881
+ vp run examples/tanstack dev
882
+ ```
883
+
884
+ Contributions are welcome! Please open an issue or pull request.
885
+
886
+ ## License
887
+
888
+ This project is licensed under the MIT License - see the [LICENSE](LICENSE) file for details.
889
+
890
+ ## Roadmap
891
+
892
+ Future features planned for upcoming versions:
893
+
894
+ ### v1.1.0 - Manual Recurring Subscriptions (Available Now)
895
+
896
+ - [x] **Stored Authorization Codes**: Securely store Paystack authorization codes from verified transactions.
897
+ - [x] **Trusted Renewal Operation**: Server-side helper to charge stored cards for renewals.
898
+ - [ ] **Card Management UI**: Let users view/delete saved payment methods (masked card data only) - _Upcoming_
899
+ - [ ] **Renewal Scheduler Integration**: Documentation for integrating with Cloudflare Workers Cron, Vercel Cron, etc. - _Upcoming_
900
+
901
+ > **Note**: For local-managed subscriptions (no `planCode`), the plugin automatically captures and stores the `authorization_code`. Trigger renewals from trusted backend code with `chargeSubscriptionRenewal(...)`.
902
+
903
+ ### Future Considerations
904
+
905
+ - [ ] Multi-currency support improvements
906
+ - [ ] Invoice generation
907
+ - [ ] Payment retry logic for failed renewals
908
+
909
+ ## Links
910
+
911
+ - GitHub Repository: [alexasomba/better-auth-paystack](https://github.com/alexasomba/better-auth-paystack)
912
+ - Comprehensive and up-to-date Paystack Node SDK: [alexasomba/paystack-node](https://github.com/alexasomba/paystack-node)
913
+ - Comprehensive and up-to-date Paystack Inline SDK: [alexasomba/paystack-inline](https://github.com/alexasomba/paystack-inline)
914
+ - [TanStack Start Example Implementation](https://github.com/alexasomba/better-auth-paystack/tree/main/examples/tanstack)
915
+ - Paystack Webhooks: https://paystack.com/docs/payments/webhooks/
916
+ - Paystack Transaction API: https://paystack.com/docs/api/transaction/
917
+ - Paystack Subscription API: https://paystack.com/docs/api/subscription/
918
+ - Paystack Plan API: https://paystack.com/docs/api/plan/
919
+ - [Better Auth Documentation](https://www.better-auth.com/docs)