better-auth-paystack 3.5.5 → 4.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -1,981 +1,116 @@
1
- # Better Auth Paystack Plugin
1
+ [English](README.md) · [Español](README.es-ES.md) · [Français](README.fr-FR.md)
2
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.
3
+ # Better Auth Paystack
4
4
 
5
- <div align="center">
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
- ![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)
7
+ ## Install
13
8
 
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
9
+ ```sh
10
+ pnpm add better-auth better-auth-paystack @alexasomba/paystack-node
37
11
  ```
38
12
 
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
- ---
13
+ Requires Node.js 22+, Better Auth `>=1.4.22 <2`, and `@alexasomba/paystack-node` `^1.12.1`.
56
14
 
57
- ## Quick Start
15
+ See the [API and compatibility policy](COMPATIBILITY.md).
58
16
 
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
- ```
17
+ ## Configure Better Auth
69
18
 
70
- #### Migrating from the scoped package
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
- 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"
21
+ ```ts
103
22
  import { createPaystack } from "@alexasomba/paystack-node";
104
23
  import { betterAuth } from "better-auth";
105
24
  import { paystack } from "better-auth-paystack";
106
- import { admin } from "better-auth/plugins";
107
25
 
108
- const paystackClient = createPaystack({
109
- secretKey: process.env.PAYSTACK_SECRET_KEY!,
110
- });
26
+ const secretKey = process.env.PAYSTACK_SECRET_KEY!;
111
27
 
112
28
  export const auth = betterAuth({
113
29
  plugins: [
114
- admin(),
115
30
  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
- },
31
+ secretKey,
32
+ paystackClient: createPaystack({ secretKey }),
138
33
  products: {
139
- products: [{ name: "credits_50", amount: 200000, currency: "NGN" }],
34
+ products: [{ name: "credits_50", price: 200_000, currency: "NGN" }],
140
35
  },
141
36
  }),
142
37
  ],
143
38
  });
144
39
  ```
145
40
 
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.
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).
149
42
 
150
- ### 4. Configure Client Plugin
151
-
152
- ```ts title="client.ts"
43
+ ```ts
153
44
  import { paystackClient } from "better-auth-paystack/client";
154
45
  import { createAuthClient } from "better-auth/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
46
 
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" }
47
+ export const authClient = createAuthClient({ plugins: [paystackClient()] });
243
48
  ```
244
49
 
245
- ### 2. One-Time Payments
246
-
247
- #### Fixed Products
50
+ ## Take a payment
248
51
 
249
- Define pre-configured products in your server settings and purchase them by name.
52
+ Call this from a signed-in browser session. The server resolves the product's price in currency minor units.
250
53
 
251
54
  ```ts
252
- await authClient.paystack.transaction.initialize({
55
+ const { data, error } = await authClient.transaction.initialize({
253
56
  product: "credits_50",
57
+ callbackURL: new URL("/billing/return", window.location.origin).href,
254
58
  });
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
59
 
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
- });
60
+ if (error) {
61
+ throw new Error(error.message ?? "Could not start Paystack checkout");
358
62
  }
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
63
  if (data?.kind === "checkout") {
385
- window.location.href = data.url;
386
- }
387
-
388
- if (data?.kind === "prorated") {
389
- console.log(data.message);
64
+ window.location.assign(data.url);
390
65
  }
391
66
  ```
392
67
 
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
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
- 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.
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`.
399
71
 
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
- ```
72
+ ## Subscriptions and organization billing
409
73
 
410
- If a subscription payment is later verified with a disallowed channel, the plugin rejects activation instead of silently creating the subscription.
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)
411
77
 
412
- ### Webhook Security
78
+ ## Standalone starters
413
79
 
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.
80
+ Scaffold a project with npm. TanStack Start is the default.
418
81
 
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 after the Paystack tokenization charge succeeds and a new trial begins.
457
- - `onTrialEnd`: Called when a trial converts to an active subscription.
458
- - `onTrialExpired`: Called when a trial ends without conversion.
459
-
460
- Paystack does not offer a no-charge trial authorization flow. The plugin tokenizes the payment
461
- method with a small one-time charge before the local trial; the default amount uses Paystack's
462
- documented minimum for NGN, GHS, ZAR, KES, or USD. For another currency, configure
463
- `freeTrial.tokenizationCharge` in minor units. Your UI must tell the customer the exact amount
464
- before calling `initializeTransaction` and then send `confirmTrialTokenizationCharge: true`.
465
- The response includes `trial.tokenizationCharge`; the subscription remains `incomplete` until
466
- the successful-charge webhook starts the trial. Refunds are not automatic; handle them explicitly
467
- with your own policy and [Paystack's refund API](https://paystack.com/docs/payments/refunds/) if you
468
- promise one. See the provider guidance for [charging cards](https://paystack.com/docs/payments/charge-card/)
469
- and [webhook events](https://paystack.com/docs/payments/webhooks/).
470
-
471
- Callback failures leave webhook deliveries retryable (HTTP 503). Trusted transaction
472
- reconciliation also persists a lifecycle delivery journal before subscription activation,
473
- so a failed completion/update hook can resume from another verification transport without
474
- resetting the billing period or repeating an already checkpointed hook. Application hooks
475
- must remain idempotent by payment reference: a process can stop after an external side effect
476
- and before its delivery checkpoint. Claims expire after five minutes for crash recovery.
477
- Trial-start hooks use the same recovery mechanism after signed tokenization-charge webhooks.
478
- Remote trial subscription creation is reserved before dispatch. If the provider response is
479
- lost, the plugin keeps the reservation unresolved instead of creating a duplicate subscription;
480
- reconcile the existing provider subscription (including its signed `subscription.create` event)
481
- before retrying. A stored successful provider response can resume local activation normally.
482
-
483
- #### Global Hook
484
-
485
- - `onEvent`: Receives every webhook event payload sent from Paystack for custom processing.
486
-
487
- ### Trusted Server Operations
488
-
489
- Recurring renewals and Paystack catalog sync are intentionally not exposed through the browser auth client.
490
- Invoke them from trusted backend code only:
491
-
492
- ```ts
493
- import {
494
- chargeSubscriptionRenewal,
495
- reconcilePaystackTransaction,
496
- syncPaystackPlans,
497
- syncPaystackProducts,
498
- } from "better-auth-paystack";
499
-
500
- const ctx = { context: await auth.$context } as any;
501
-
502
- await chargeSubscriptionRenewal(ctx, paystackOptions, {
503
- subscriptionId: "sub_123",
504
- });
505
-
506
- const settlement = await reconcilePaystackTransaction(ctx, paystackOptions, {
507
- reference: "PAYSTACK_REFERENCE",
508
- source: "queue",
509
- referenceId: "user_or_org_id",
510
- });
511
-
512
- if (settlement.ok) {
513
- console.log(settlement.transaction.status, settlement.subscription.updated);
514
- }
515
-
516
- await syncPaystackProducts(ctx, paystackOptions);
517
- await syncPaystackPlans(ctx, paystackOptions);
82
+ ```sh
83
+ npm create better-auth-paystack@latest my-app
84
+ npm create better-auth-paystack@latest my-next-app -- --template nextjs
85
+ npm create better-auth-paystack@latest my-worker -- --template hono
518
86
  ```
519
87
 
520
- 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.
88
+ Set the environment variables from the generated README, then run `pnpm install --frozen-lockfile` and `pnpm dev`.
521
89
 
522
- ### Authorization & Security
90
+ 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)
523
91
 
524
- #### `authorizeReference`
92
+ From a repository checkout, export a starter with the released package or with a local tarball built by `vp pack` followed by `pnpm pack`.
525
93
 
526
- Control who can manage billing for specific references (Users or Organizations).
527
-
528
- ```ts
529
- paystack({
530
- subscription: {
531
- authorizeReference: async ({ user, referenceId, action }) => {
532
- // Example: Only allow Org Admins to initialize transactions
533
- if (referenceId.startsWith("org_")) {
534
- const member = await db.findOne({
535
- model: "member",
536
- where: [
537
- { field: "organizationId", value: referenceId },
538
- { field: "userId", value: user.id },
539
- ],
540
- });
541
- return member?.role === "admin";
542
- }
543
- return user.id === referenceId;
544
- },
545
- },
546
- });
94
+ ```sh
95
+ pnpm starter:export tanstack /tmp/paystack-starter
96
+ pnpm starter:export tanstack /tmp/paystack-local --tarball /path/to/better-auth-paystack.tgz
547
97
  ```
548
98
 
549
- ---
550
-
551
- ## Client SDK Reference
552
-
553
- The client plugin exposes fully typed canonical methods under `authClient.paystack`, `authClient.transaction`, and `authClient.subscription`.
554
-
555
- - `authClient.transaction.initialize`, `verify`, `list`
556
- - `authClient.subscription.create`, `upgrade`, `cancel`, `restore`, `list`, `billingPortal`
557
- - `authClient.paystack.config`, `listProducts`, `listPlans`, plus the transaction/subscription helpers above
558
-
559
- Legacy compatibility aliases remain available for migration, but new code should use the canonical methods:
560
-
561
- - `authClient.subscription.disable(...)` -> use `authClient.subscription.cancel(...)`
562
- - `authClient.subscription.enable(...)` -> use `authClient.subscription.restore(...)`
99
+ Paystack also publishes Next.js and Hono starter archives. Use `nextjs` or `hono` as the demo name to export either one.
563
100
 
564
- ### `authClient.subscription.upgrade` / `create`
101
+ ## Demo and agent skills
565
102
 
566
- Initializes a transaction to create or upgrade a subscription.
103
+ The [TanStack Start demo](examples/tanstack/README.md) includes setup instructions, billing screens, and test commands.
567
104
 
568
- ```ts
569
- type upgradeSubscription = {
570
- /**
571
- * The name of the plan to subscribe to.
572
- */
573
- plan: string;
574
- /**
575
- * The email of the subscriber. Defaults to the current user's email.
576
- */
577
- email?: string;
578
- /**
579
- * Amount to charge (if not using a Paystack Plan Code).
580
- */
581
- amount?: number;
582
- /**
583
- * Currency code (e.g., "NGN").
584
- */
585
- currency?: string;
586
- /**
587
- * The callback URL to redirect to after payment.
588
- */
589
- callbackURL?: string;
590
- /** Required for trial plans after your UI has disclosed the one-time tokenization charge. */
591
- confirmTrialTokenizationCharge?: boolean;
592
- /**
593
- * Additional metadata to store with the transaction.
594
- */
595
- metadata?: Record<string, unknown>;
596
- /**
597
- * Reference ID for the subscription owner (User ID or Org ID).
598
- * Defaults to the current user's ID.
599
- */
600
- referenceId?: string;
601
- /**
602
- * Number of seats to purchase (for team plans).
603
- */
604
- quantity?: number;
605
- };
606
- ```
607
-
608
- ### `authClient.paystack.transaction.initialize`
609
-
610
- Same as `upgrade`, but can also be used for one-time payments by omitting `plan` and providing `amount` or `product`.
105
+ The npm package includes [agent skills](skills). With pnpm 12.11 or later, run `pnpm approve` after installing the package and approve its skills when prompted. TanStack Intent can list and load the same files from your project.
611
106
 
612
- ```ts
613
- type initializeTransaction = {
614
- /**
615
- * Plan name (for subscriptions).
616
- */
617
- plan?: string;
618
- /**
619
- * Product name (for one-time purchases).
620
- */
621
- product?: string;
622
- /**
623
- * Amount to charge (if sending raw amount).
624
- */
625
- amount?: number;
626
- /**
627
- * For existing locally managed subscriptions, calculate a mid-cycle delta and either
628
- * charge the saved authorization or return a checkout redirect for interactive payment.
629
- */
630
- prorateAndCharge?: boolean;
631
- // ... same as upgradeSubscription
632
- };
633
-
634
- type initializeTransactionResult =
635
- | {
636
- kind: "checkout";
637
- url: string;
638
- reference: string;
639
- accessCode: string;
640
- redirect: true;
641
- }
642
- | { kind: "scheduled"; status: "success"; message: string; scheduled: true }
643
- | { kind: "prorated"; status: "success"; message: string; prorated: true };
107
+ ```sh
108
+ pnpm dlx @tanstack/intent list
109
+ pnpm dlx @tanstack/intent load better-auth-paystack#better-auth-paystack-setup
644
110
  ```
645
111
 
646
- ### `authClient.subscription.list`
647
-
648
- 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`.
649
-
650
- ```ts
651
- type listSubscriptions = {
652
- query?: {
653
- /**
654
- * Filter by reference ID (User ID or Org ID).
655
- */
656
- referenceId?: string;
657
- };
658
- };
659
- ```
660
-
661
- ### `authClient.subscription.cancel` / `restore`
662
-
663
- Cancel or restore a subscription.
664
-
665
- - **Cancel**: Sets `cancelAtPeriodEnd: true`. The subscription remains `active` until the end of the current billing period, after which it moves to `canceled`.
666
- - **Restore**: Reactivates a subscription that is scheduled to cancel.
667
-
668
- ```ts
669
- type cancelSubscription = {
670
- /**
671
- * Optional reference owner (user ID or org ID) when managing another billing entity.
672
- */
673
- referenceId?: string;
674
- /**
675
- * The Paystack subscription code (e.g. SUB_...)
676
- */
677
- subscriptionCode: string;
678
- /**
679
- * The email token required by Paystack to manage the subscription.
680
- * Optional: The server will try to fetch it if omitted.
681
- */
682
- emailToken?: string;
683
- /**
684
- * When true, keep the subscription active until the current period ends.
685
- */
686
- atPeriodEnd?: boolean;
687
- };
688
- ```
689
-
690
- ## Schema Reference
691
-
692
- The plugin extends your database with the following fields and tables.
693
-
694
- ### `user` and `organization`
695
-
696
- Paystack customer codes are no longer added to Better Auth auth tables. Organization `email`
697
- remains available for billing fallback.
698
-
699
- | Field | Type | Required | Description |
700
- | :------ | :------- | :------- | :--------------------------------------------------------------------------------- |
701
- | `email` | `string` | No | The billing email for the organization. Falls back to the owner's email if absent. |
702
-
703
- ### `paystackCustomer`
704
-
705
- | Field | Type | Required | Description |
706
- | :-------------- | :------- | :------- | :----------------------------------- |
707
- | `referenceType` | `string` | Yes | `user` or `organization`. |
708
- | `referenceId` | `string` | Yes | Owning Better Auth identifier. |
709
- | `referenceKey` | `string` | Yes | Unique provider-owned reference key. |
710
- | `customerCode` | `string` | Yes | Paystack customer code. |
711
- | `email` | `string` | No | Billing email. |
712
-
713
- ### `paystackPaymentCredential`
714
-
715
- Payment credentials are stored separately as AES-256-GCM ciphertext. Plaintext values are not
716
- returned by subscription APIs, callbacks, logs, or client actions. Set `credentialEncryptionKey`
717
- to a dedicated production secret; the plugin falls back to `secretKey` for compatibility.
718
-
719
- | Field | Type | Required | Description |
720
- | :--------------------------- | :------- | :------- | :---------------------------------------- |
721
- | `subscriptionId` | `string` | Yes | Unique Paystack subscription ID. |
722
- | `authorizationCodeEncrypted` | `string` | No | Encrypted recurring-charge authorization. |
723
- | `emailTokenEncrypted` | `string` | No | Encrypted subscription-management token. |
724
-
725
- ### `paystackSubscription`
726
-
727
- | Field | Type | Required | Description |
728
- | :--------------------- | :-------- | :------- | :------------------------------------------------------------------- |
729
- | `plan` | `string` | Yes | Lowercased name of the active plan. |
730
- | `referenceId` | `string` | Yes | Associated User ID or Organization ID. |
731
- | `userId` | `string` | Yes | User who initiated the subscription checkout. |
732
- | `customerCode` | `string` | No | The Paystack customer code for this subscription. |
733
- | `subscriptionCode` | `string` | No | The unique code for the subscription (e.g., `SUB_...` or `LOC_...`). |
734
- | `transactionReference` | `string` | No | The reference of the transaction that started the subscription. |
735
- | `planCode` | `string` | No | The Paystack plan code, when Paystack manages the subscription. |
736
- | `status` | `string` | Yes | `active`, `trialing`, `canceled`, `incomplete`. |
737
- | `periodStart` | `Date` | No | Start date of the current billing period. |
738
- | `periodEnd` | `Date` | No | End date of the current billing period. |
739
- | `trialStart` | `Date` | No | Start date of the trial period. |
740
- | `trialEnd` | `Date` | No | End date of the trial period. |
741
- | `cancelAtPeriodEnd` | `boolean` | No | Whether to cancel at the end of the current period. |
742
- | `cancelAt` | `Date` | No | Scheduled cancellation timestamp. |
743
- | `canceledAt` | `Date` | No | Cancellation timestamp. |
744
- | `endedAt` | `Date` | No | Subscription end timestamp. |
745
- | `billingInterval` | `string` | No | Billing interval used by the plan. |
746
- | `groupId` | `string` | No | Optional subscription group. |
747
- | `pendingPlan` | `string` | No | Plan pending a future lifecycle change. |
748
- | `seats` | `number` | No | Purchased seat count for team billing. |
749
- | `createdAt` | `Date` | Yes | Record creation timestamp. |
750
- | `updatedAt` | `Date` | Yes | Record update timestamp. |
751
-
752
- ### `paystackTransaction`
753
-
754
- | Field | Type | Required | Description |
755
- | :------------ | :------- | :------- | :--------------------------------------------------- |
756
- | `reference` | `string` | Yes | Unique transaction reference. |
757
- | `referenceId` | `string` | Yes | Associated User ID or Organization ID. |
758
- | `userId` | `string` | Yes | The ID of the user who initiated the transaction. |
759
- | `amount` | `number` | Yes | Transaction amount in smallest currency unit. |
760
- | `currency` | `string` | Yes | Currency code (e.g., "NGN"). |
761
- | `status` | `string` | Yes | `success`, `pending`, `failed`, `abandoned`. |
762
- | `plan` | `string` | No | Name of the plan associated with the transaction. |
763
- | `product` | `string` | No | Name of the product associated with the transaction. |
764
- | `metadata` | `string` | No | JSON string of extra transaction metadata. |
765
- | `paystackId` | `string` | No | The internal Paystack ID for the transaction. |
766
- | `createdAt` | `Date` | Yes | Transaction creation timestamp. |
767
- | `updatedAt` | `Date` | Yes | Transaction last update timestamp. |
768
-
769
- ### `paystackProduct`
770
-
771
- | Field | Type | Required | Description |
772
- | :------------ | :-------- | :------- | :--------------------------------------- |
773
- | `name` | `string` | Yes | Product name. |
774
- | `description` | `string` | No | Product description. |
775
- | `price` | `number` | Yes | Price in smallest currency unit. |
776
- | `currency` | `string` | Yes | Currency code (e.g., "NGN"). |
777
- | `quantity` | `number` | No | Available stock quantity. |
778
- | `unlimited` | `boolean` | No | Whether the product has unlimited stock. |
779
- | `paystackId` | `string` | No | The internal Paystack Product ID. |
780
- | `slug` | `string` | Yes | Unique slug for the product. |
781
- | `metadata` | `string` | No | JSON string of extra product metadata. |
782
- | `createdAt` | `Date` | Yes | Product creation timestamp. |
783
- | `updatedAt` | `Date` | Yes | Product last update timestamp. |
784
-
785
- ### `paystackWebhookEvent`
786
-
787
- The plugin records verified webhook deliveries with their event type, raw payload, reference (when
788
- available), processing status, and processed timestamp. This table is provider-namespaced so the
789
- Paystack and Flutterwave plugins can be installed together without sharing webhook state.
790
-
791
- | Field | Type | Required | Description |
792
- | :------------ | :------- | :------- | :----------------------------------------- |
793
- | `eventId` | `string` | Yes | Stable hash of the exact verified payload. |
794
- | `eventType` | `string` | Yes | Paystack event name. |
795
- | `reference` | `string` | No | Transaction reference when available. |
796
- | `payload` | `string` | Yes | Exact raw webhook payload. |
797
- | `status` | `string` | Yes | `pending` or `processed`. |
798
- | `processedAt` | `Date` | No | Processing completion timestamp. |
799
-
800
- ### v4 schema migration
801
-
802
- After upgrading the package, generate/apply the Better Auth schema first, then run the trusted
803
- server-only operation:
804
-
805
- ```ts
806
- import { migratePaystackSubscriptionSchema } from "better-auth-paystack";
807
-
808
- const report = await migratePaystackSubscriptionSchema(ctx, {
809
- secretKey: process.env.PAYSTACK_SECRET_KEY!,
810
- credentialEncryptionKey: process.env.PAYSTACK_CREDENTIAL_ENCRYPTION_KEY,
811
- });
812
- ```
813
-
814
- Run it in this order:
815
-
816
- 1. Upgrade the package.
817
- 2. Run Better Auth schema generation/migration.
818
- 3. Run `migratePaystackSubscriptionSchema()` from a trusted server job.
819
- 4. Verify migration counts and billing behavior.
820
- 5. Remove legacy columns/tables manually only after verification.
821
-
822
- The operation preserves legacy rows, keeps original subscription IDs where possible, skips already
823
- migrated records, encrypts legacy authorization/email tokens, and reports partial failures so a
824
- later run can retry them.
825
-
826
- During the compatibility window, customer resolution can still read legacy auth-table customer
827
- codes. Remove those legacy columns manually after the migration has been verified.
828
-
829
- ---
830
-
831
- ## Troubleshooting
832
-
833
- - **Webhook Signature**: Ensure `PAYSTACK_SECRET_KEY` matches the integration that sends the webhook. Paystack uses this API secret key for `x-paystack-signature`.
834
- - **Email Verification**: Use `requireEmailVerification: true` to prevent unverified checkouts.
835
- - **Redirect Failures**: Check your browser console; Paystack often returns 429 errors if you're hitting the test API too frequently.
836
- - **Reference mismatches**: Ensure `referenceId` is passed correctly for Organization billing.
837
- - **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.
838
-
839
- ### Database Indexing
840
-
841
- 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.
842
-
843
- After upgrading, run `npx better-auth migrate` (or `npx better-auth generate` for schema-managed
844
- adapters). The additive `cancelAt`, `canceledAt`, `endedAt`, and `billingInterval` subscription
845
- columns are nullable; historical rows are populated as future lifecycle events are processed.
846
-
847
- The following fields are indexed:
848
-
849
- - **`paystackTransaction`**: `reference` (unique), `userId`, `referenceId`.
850
- - **`paystackSubscription`**: `subscriptionCode` (unique), `referenceId`, `transactionReference`, `customerCode`, `plan`.
851
- - **`paystackCustomer`**: `referenceKey` (unique), `referenceId`, `customerCode` (unique).
852
- - **`paystackPaymentCredential`**: `subscriptionId` (unique).
853
- - **`paystackProduct`**: `slug` (unique), `paystackId` (unique).
854
-
855
- Proration upgrades and trusted renewal charges also persist `paystackTransaction` rows, so local transaction history stays aligned with successful off-session charges.
856
-
857
- ### Syncing Products
858
-
859
- The plugin provides two ways to keep your product inventory aligned with Paystack:
860
-
861
- #### 1. Automated Inventory Sync
862
-
863
- 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.
864
-
865
- #### 2. Trusted Manual Bulk Sync
866
-
867
- The public `/paystack/sync-products` endpoint was removed in `2.0.0`.
868
- Run the trusted server operation from backend code instead:
869
-
870
- ```ts
871
- import { syncPaystackProducts } from "better-auth-paystack";
872
-
873
- const ctx = { context: await auth.$context } as any;
874
-
875
- await syncPaystackProducts(ctx, paystackOptions);
876
- ```
877
-
878
- ### SDK Compatibility Note
879
-
880
- The plugin now targets the official `@alexasomba/paystack-node` grouped client surface directly.
881
- 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`.
882
-
883
- ---
884
-
885
- ## 🏗️ Development & Contributing
886
-
887
- This repository is powered by **Vite+**. You use the `vp` CLI to manage the entire workspace.
888
-
889
- ```bash
890
- # Install dependencies
891
- vp install
892
-
893
- # Check project health (format, lint, types)
894
- vp check --fix
895
-
896
- # Build the core library
897
- vp pack
898
-
899
- # Run tests
900
- vp test
901
-
902
- # Run the TanStack Start example
903
- vp -C examples/tanstack dev
904
- ```
905
-
906
- Contributions are welcome! Please open an issue or pull request.
907
-
908
- ## License
909
-
910
- This project is licensed under the MIT License - see the [LICENSE](LICENSE) file for details.
911
-
912
- ## Roadmap
913
-
914
- Future features planned for upcoming versions:
915
-
916
- ### v1.1.0 - Manual Recurring Subscriptions (Available Now)
917
-
918
- - [x] **Stored Authorization Codes**: Securely store Paystack authorization codes from verified transactions.
919
- - [x] **Trusted Renewal Operation**: Server-side helper to charge stored cards for renewals.
920
- - [ ] **Card Management UI**: Let users view/delete saved payment methods (masked card data only) - _Upcoming_
921
- - [ ] **Renewal Scheduler Integration**: Documentation for integrating with Cloudflare Workers Cron, Vercel Cron, etc. - _Upcoming_
922
-
923
- > **Note**: For local-managed subscriptions (no `planCode`), the plugin automatically captures and stores the `authorization_code`. Trigger renewals from trusted backend code with `chargeSubscriptionRenewal(...)`.
924
-
925
- ### Future Considerations
926
-
927
- - [ ] Multi-currency support improvements
928
- - [ ] Invoice generation
929
- - [ ] Payment retry logic for failed renewals
930
-
931
- ## Links
932
-
933
- - GitHub Repository: [alexasomba/better-auth-paystack](https://github.com/alexasomba/better-auth-paystack)
934
- - Comprehensive and up-to-date Paystack Node SDK: [alexasomba/paystack-node](https://github.com/alexasomba/paystack-node)
935
- - Comprehensive and up-to-date Paystack Inline SDK: [alexasomba/paystack-inline](https://github.com/alexasomba/paystack-inline)
936
- - [TanStack Start Example Implementation](https://github.com/alexasomba/better-auth-paystack/tree/main/examples/tanstack)
937
- - Paystack Webhooks: https://paystack.com/docs/payments/webhooks/
938
- - Paystack Transaction API: https://paystack.com/docs/api/transaction/
939
- - Paystack Subscription API: https://paystack.com/docs/api/subscription/
940
- - Paystack Plan API: https://paystack.com/docs/api/plan/
941
- - [Better Auth Documentation](https://www.better-auth.com/docs)
942
-
943
- ### Optional subscription operation hooks
944
-
945
- `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.
946
-
947
- 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.
948
-
949
- Return one of:
950
-
951
- - `{ 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.
952
- - `{ kind: "replay", result }`: return an existing `PaystackInitializeResult` of the appropriate operation kind without another provider call or SDK write.
953
- - `{ kind: "block", message? }`: reject this operation without dispatch or mutation.
954
-
955
- `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.
956
-
957
- 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.
958
-
959
- A fail-closed configuration while an application reservation service is unavailable:
960
-
961
- ```ts
962
- import type { PaystackSubscriptionOperationHooks } from "better-auth-paystack";
963
-
964
- const operationHooks: PaystackSubscriptionOperationHooks = {
965
- before: () =>
966
- Promise.resolve({
967
- kind: "block",
968
- message: "Subscription changes are temporarily unavailable.",
969
- }),
970
- };
971
-
972
- // Pass operationHooks under paystack({ subscription: { enabled: true, plans, operationHooks } }).
973
- ```
974
-
975
- 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.
976
-
977
- ### Pricing and webhook delivery
112
+ ## Develop
978
113
 
979
- 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.
114
+ 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.
980
115
 
981
- 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.
116
+ [MIT license](LICENSE)