better-auth-paystack 3.5.6 → 4.0.1

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