@paddle/better-auth 0.0.0-stage → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Paddle.com Market Ltd.
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,550 @@
1
- # Temporary Holding Version
1
+ # @paddle/better-auth
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Paddle Billing plugin for [Better Auth](https://better-auth.com). Webhook-driven local subscription
4
+ state, server-created transactions, and a drop-in checkout component for Paddle's overlay/inline
5
+ checkout — no default payment link required.
6
+
7
+ > Status: pre-release. APIs may change before 1.0.
8
+
9
+ ## Contents
10
+
11
+ - [How it works](#how-it-works)
12
+ - [Prerequisites](#prerequisites)
13
+ - [Install](#install)
14
+ - [Server setup](#server-setup)
15
+ - [Paddle customers](#paddle-customers)
16
+ - [Client setup](#client-setup)
17
+ - [Checkout](#checkout)
18
+ - [Managing subscriptions](#managing-subscriptions)
19
+ - [Payment history and invoices](#payment-history-and-invoices)
20
+ - [Access control](#access-control)
21
+ - [Webhook events](#webhook-events)
22
+ - [Options](#options)
23
+ - [Environment variables](#environment-variables)
24
+
25
+ ## How it works
26
+
27
+ Paddle is the source of truth for billing; this plugin keeps a **local mirror** of each
28
+ subscription so your app can read entitlement without calling Paddle on every request.
29
+
30
+ 1. A signed-in user hits checkout. The plugin creates a Paddle **transaction** server-side (tagged
31
+ with the user id) and redirects the browser to your checkout page.
32
+ 2. The `PaddleCheckout` component opens Paddle's overlay/inline checkout for that transaction.
33
+ 3. Paddle processes payment and sends **webhooks**. The plugin verifies each one, reduces every
34
+ `subscription.*` event into a row in the `subscription` table, and fires your grant/revoke and
35
+ lifecycle callbacks.
36
+ 4. Your app reads subscription state from its own database — no Paddle round-trip on the hot path.
37
+
38
+ Because state arrives via webhooks, the local row is **eventually consistent**: it can lag Paddle by
39
+ however long delivery takes.
40
+
41
+ ## Prerequisites
42
+
43
+ **Products and prices must exist in Paddle before you configure the plugin.** The plugin never
44
+ creates them — it references existing Paddle **price IDs** (`pri_...`), so set them up first:
45
+
46
+ 1. Create a Paddle account and switch to the **sandbox** for development.
47
+ 2. In the Paddle dashboard, create a **product** for each thing you sell, then add one or more
48
+ **prices** to it (e.g. a monthly price and an annual price for your "Pro" plan). You can also do
49
+ this via the [Paddle API](https://developer.paddle.com/api-reference/prices/overview).
50
+ 3. Copy each price's `pri_...` id — these go into `subscription.plans` (see below).
51
+ 4. Grab your credentials (see [Environment variables](#environment-variables)): a server-side
52
+ **API key**, a client-side **client token**, and a **webhook secret** for the notification
53
+ destination you'll create in [Webhook events](#webhook-events).
54
+
55
+ A plan in this plugin is just a friendly name mapped to Paddle price ids:
56
+
57
+ ```ts
58
+ subscription: {
59
+ enabled: true,
60
+ plans: [
61
+ { name: "pro", priceId: "pri_monthly_pro", annualPriceId: "pri_annual_pro" },
62
+ { name: "team", priceId: "pri_monthly_team", annualPriceId: "pri_annual_team", limits: { seats: 10 } },
63
+ ],
64
+ }
65
+ ```
66
+
67
+ `plans` may also be an **async function** returning that array (`() => Promise<PaddlePlan[]>`), which
68
+ is useful if you load prices from Paddle or your own store at startup rather than hard-coding ids.
69
+ Either way, the ids must already exist in Paddle. `limits` is an optional free-form bag you can read
70
+ back off the resolved plan for your own entitlement logic.
71
+
72
+ ## Install
73
+
74
+ ```bash
75
+ pnpm add @paddle/better-auth @paddle/paddle-node-sdk
76
+ # for the React checkout component:
77
+ pnpm add @paddle/paddle-js
78
+ ```
79
+
80
+ `@paddle/paddle-node-sdk`, `better-auth`, and (for the React component) `@paddle/paddle-js` and
81
+ `react` are peer dependencies — install them in your app.
82
+
83
+ ## Server setup
84
+
85
+ ```ts
86
+ import { betterAuth } from "better-auth";
87
+ import { Paddle, Environment } from "@paddle/paddle-node-sdk";
88
+ import { paddle } from "@paddle/better-auth";
89
+
90
+ const paddleClient = new Paddle(process.env.PADDLE_API_KEY!, { environment: Environment.sandbox });
91
+
92
+ export const auth = betterAuth({
93
+ plugins: [
94
+ paddle({
95
+ paddleClient,
96
+ webhookSecret: process.env.PADDLE_WEBHOOK_SECRET!,
97
+ checkoutPage: "/checkout", // your page that renders <PaddleCheckout />
98
+ subscription: {
99
+ enabled: true,
100
+ plans: [{ name: "pro", priceId: "pri_...", annualPriceId: "pri_..." }],
101
+ },
102
+ }),
103
+ ],
104
+ });
105
+ ```
106
+
107
+ Run `npx @better-auth/cli migrate` (or `generate`) to add the `subscription` table and the
108
+ `user.paddleCustomerId` column. Then point a Paddle notification destination at
109
+ `https://your-app.com/api/auth/paddle/webhook` — see [Webhook events](#webhook-events) for what to
110
+ subscribe to.
111
+
112
+ For production, construct the client with `{ environment: Environment.production }` and use your
113
+ live credentials.
114
+
115
+ ## Paddle customers
116
+
117
+ Each user gets a Paddle customer at sign-up, with the id stored in `user.paddleCustomerId`. With
118
+ `createCustomerOnSignUp: false` it is created on the user's first `checkout` or `portal` call instead.
119
+ The plugin tags every customer it creates with the user's id in `custom_data.userId`.
120
+
121
+ When a user's email changes in your app, the plugin updates the email on their Paddle customer, so
122
+ Paddle's emails follow the user and the old address is free for whoever signs up with it next. The
123
+ user's name is not synced. If Paddle rejects the change, for example because another customer already
124
+ has that address, the plugin logs the error and the user's change still goes through.
125
+
126
+ ### Linking an existing customer
127
+
128
+ Paddle allows one customer per email, so when Paddle already has a customer for the user's email the
129
+ plugin can't create a second one. It links the existing customer instead. Linking hands over that
130
+ customer's portal, invoices and saved payment methods, and a matching email alone doesn't prove the
131
+ user owns them: sign-up doesn't verify the address, and addresses get reused. The plugin decides in
132
+ this order:
133
+
134
+ | The existing customer | Result |
135
+ | --- | --- |
136
+ | is already stored on this user | Linked. |
137
+ | is stored on another user in your app | `403` with code `CUSTOMER_HELD_BY_ANOTHER_USER`. |
138
+ | is tagged with this user's id in `custom_data.userId` | Linked, whether or not the email is verified. |
139
+ | is none of the above, and the user's email is verified | Linked. |
140
+ | is none of the above, and the user's email is unverified | `403` with code `EMAIL_VERIFICATION_REQUIRED`. |
141
+
142
+ `checkout` and `portal` return the `403`. The sign-up hook only logs it, so sign-up itself always
143
+ succeeds and the user meets the error on their first `checkout` or `portal` call. Nothing is stored
144
+ when linking is refused, so the same call works once the cause is fixed:
145
+
146
+ ```ts
147
+ const { error } = await authClient.paddle.checkout({ plan: "pro" });
148
+ if (error?.code === "EMAIL_VERIFICATION_REQUIRED") showVerifyEmailPrompt();
149
+ if (error?.code === "CUSTOMER_HELD_BY_ANOTHER_USER") showContactSupportMessage();
150
+ ```
151
+
152
+ - **`EMAIL_VERIFICATION_REQUIRED`**: the user verifies their email and tries again. A user whose email
153
+ has no existing Paddle customer never sees this. To keep unverified users from reaching checkout at
154
+ all, turn on Better Auth's email verification (`emailVerification.sendOnSignUp` and
155
+ `emailAndPassword.requireEmailVerification`).
156
+ - **`CUSTOMER_HELD_BY_ANOTHER_USER`**: the user can't fix this themselves. It means the other
157
+ account's Paddle customer still has this address although the account no longer uses it, for example
158
+ because an email change failed to reach Paddle. Update that customer's email in Paddle, and the new
159
+ user then gets a customer of their own.
160
+
161
+ In development the unverified case shows up after a database reset: the old Paddle customer still
162
+ owns the email, so sign up with a fresh address (`you+2@example.com`) or verify the email.
163
+
164
+ ## Client setup
165
+
166
+ ```ts
167
+ import { createAuthClient } from "better-auth/client";
168
+ import { paddleClient } from "@paddle/better-auth/client";
169
+
170
+ export const authClient = createAuthClient({ plugins: [paddleClient()] });
171
+ ```
172
+
173
+ This adds a typed `authClient.paddle.*` namespace:
174
+
175
+ | Method | Endpoint | Purpose |
176
+ | --- | --- | --- |
177
+ | `paddle.checkout({ plan, annual?, quantity?, customData?, disableRedirect? })` | `POST /paddle/checkout` | Create a transaction and redirect to your checkout page. |
178
+ | `paddle.subscription.list()` | `GET /paddle/subscription/list` | List the current user's subscription rows. |
179
+ | `paddle.subscription.update({ plan, annual?, subscriptionId? })` | `POST /paddle/subscription/update` | Upgrade / downgrade / switch billing cycle. |
180
+ | `paddle.subscription.preview({ plan, annual?, subscriptionId? })` | `POST /paddle/subscription/preview` | Show what an `update` would charge, without making it. |
181
+ | `paddle.subscription.cancel({ subscriptionId?, effectiveFrom? })` | `POST /paddle/subscription/cancel` | Cancel a subscription. |
182
+ | `paddle.subscription.restore({ subscriptionId? })` | `POST /paddle/subscription/restore` | Undo a scheduled cancellation or pause. |
183
+ | `paddle.subscription.pause({ subscriptionId?, effectiveFrom? })` | `POST /paddle/subscription/pause` | Pause a subscription. |
184
+ | `paddle.subscription.resume({ subscriptionId?, onResume? })` | `POST /paddle/subscription/resume` | Resume a paused subscription immediately. |
185
+ | `paddle.portal({ subscriptionId? })` | `POST /paddle/portal` | Get a Paddle-hosted customer portal URL. |
186
+ | `paddle.transaction.list({ query?: { cursor?, perPage? } })` | `GET /paddle/transaction/list` | List the current user's payments, newest first. |
187
+ | `paddle.transaction.invoice({ transactionId, disposition? })` | `POST /paddle/transaction/invoice` | Get a short-lived invoice PDF URL. |
188
+
189
+ All of these except `checkout`'s redirect require an authenticated session. Where `subscriptionId`
190
+ is optional, the plugin resolves the caller's single non-canceled subscription automatically and
191
+ returns a `400` if there is more than one (pass the id explicitly in that case).
192
+
193
+ ## Checkout
194
+
195
+ Kick off checkout from your pricing page:
196
+
197
+ ```ts
198
+ await authClient.paddle.checkout({ plan: "pro" }); // navigates to /checkout?txn=txn_...
199
+ ```
200
+
201
+ `checkout` returns a `403` when the user's email matches a Paddle customer the plugin won't link; see
202
+ [Linking an existing customer](#linking-an-existing-customer).
203
+
204
+ ### One subscription per user
205
+
206
+ `checkout` returns a `400` with code `ALREADY_SUBSCRIBED` when the user already has a subscription
207
+ that isn't canceled: `active`, `trialing`, `past_due` or `paused`. A second checkout would start a
208
+ second subscription and bill the user twice. Send them to your billing page instead, and change the
209
+ plan on the existing subscription with [`subscription.update`](#upgrades-and-downgrades):
210
+
211
+ ```ts
212
+ const { error } = await authClient.paddle.checkout({ plan: "team" });
213
+ if (error?.code === "ALREADY_SUBSCRIBED") router.push("/account/billing");
214
+ ```
215
+
216
+ Once the subscription is `canceled`, the user can check out again. The block only applies to
217
+ `checkout`: a subscription you create in the Paddle dashboard or through the API is not stopped.
218
+
219
+ If you sell several subscriptions to the same user, turn the block off with
220
+ `subscription.allowMultipleSubscriptions: true`. The management calls then need a `subscriptionId`
221
+ whenever the user has more than one.
222
+
223
+ Better Auth's client follows the `{ url, redirect: true }` response automatically. To open checkout
224
+ on the current page instead, pass `disableRedirect: true` and hand the transaction id to
225
+ `usePaddleCheckout`:
226
+
227
+ ```tsx
228
+ const { open } = usePaddleCheckout({ clientToken: process.env.NEXT_PUBLIC_PADDLE_CLIENT_TOKEN! });
229
+
230
+ const { data } = await authClient.paddle.checkout({ plan: "pro", disableRedirect: true });
231
+ if (data) await open(data.transactionId);
232
+ ```
233
+
234
+ Then render the checkout component on your `checkoutPage`. It reads the transaction id from the URL
235
+ query param and opens Paddle checkout:
236
+
237
+ ```tsx
238
+ // app/checkout/page.tsx
239
+ "use client";
240
+ import { PaddleCheckout } from "@paddle/better-auth/react";
241
+
242
+ export default function CheckoutPage() {
243
+ return (
244
+ <PaddleCheckout
245
+ clientToken={process.env.NEXT_PUBLIC_PADDLE_CLIENT_TOKEN!}
246
+ environment="sandbox" // or "production"
247
+ displayMode="inline" // or "overlay"
248
+ theme="light" // or "dark"
249
+ onCompleted={() => (window.location.href = "/welcome")}
250
+ />
251
+ );
252
+ }
253
+ ```
254
+
255
+ `PaddleCheckout` props: `clientToken` (required), `environment`, `displayMode`, `theme`,
256
+ `onCompleted(data)`, `fallback` (rendered when the URL has no valid transaction id), and `paramName`
257
+ (the query param carrying the transaction id — must match the server's `checkoutParam`, default
258
+ `"txn"`).
259
+
260
+ `onCompleted` firing means the checkout UI finished — the subscription becomes readable in your
261
+ database once the webhook arrives, which is usually under a second later but not instantaneous.
262
+ Before sending the user to a page gated on that subscription, wait for it:
263
+
264
+ ```ts
265
+ const { data, error } = await authClient.paddle.subscription.waitFor({ transactionId });
266
+ if (data) router.push("/pro");
267
+ else if (error.code === "TIMEOUT") showStillConfirmingMessage();
268
+ ```
269
+
270
+ `waitFor` checks `subscription.list` immediately and then every `intervalMs` (default `500`) until a
271
+ row with that `paddleTransactionId` appears, returning it as `data`. It gives up after `timeoutMs`
272
+ (default `30000`) with `error.code === "TIMEOUT"`, stops at the first failed `list` call with that
273
+ call's error, and returns `error.code === "ABORTED"` if you pass a `signal` that aborts. It only reads
274
+ your database. One-off (non-subscription) purchases never create a row, so don't wait on those.
275
+
276
+ ## Managing subscriptions
277
+
278
+ Read state from your own database (populated by webhooks):
279
+
280
+ ```ts
281
+ const subscriptions = await authClient.paddle.subscription.list();
282
+ // each row: { plan, status, priceId, quantity, periodEnd, cancelAtPeriodEnd, ... }
283
+ ```
284
+
285
+ `plan` is the name of the configured plan that owns the subscription's current price, so it follows
286
+ upgrades and downgrades. It is `null` when the price isn't in `subscription.plans`. Gate features on
287
+ `plan` (or `priceId`) as well as `status`: an `active` row only means the customer is paying for
288
+ something in your Paddle catalog.
289
+
290
+ ### Upgrades and downgrades
291
+
292
+ **Yes — plan changes are supported.** There's no separate "upgrade" vs "downgrade" call: both are a
293
+ plan (price) swap via `subscription.update`. Paddle handles the proration.
294
+
295
+ ```ts
296
+ // Move the user to the "team" plan.
297
+ await authClient.paddle.subscription.update({ plan: "team" });
298
+
299
+ // Switch the same plan from monthly to annual billing.
300
+ await authClient.paddle.subscription.update({ plan: "pro", annual: true });
301
+ ```
302
+
303
+ The resulting `subscription.updated` webhook updates the local row and fires `onSubscriptionUpdated`.
304
+
305
+ How the change is billed is set on the server with `subscription.prorationBillingMode`, not by the
306
+ caller, because a mode like `do_not_bill` would let a user upgrade without paying. It accepts
307
+ `prorated_immediately` (default), `prorated_next_billing_period`, `full_immediately`,
308
+ `full_next_billing_period` and `do_not_bill`, or a function that picks one per change:
309
+
310
+ ```ts
311
+ subscription: {
312
+ enabled: true,
313
+ plans,
314
+ // Charge upgrades now; let downgrades take effect on the next bill.
315
+ prorationBillingMode: ({ subscription, priceId }) =>
316
+ isUpgrade(subscription.priceId, priceId) ? "prorated_immediately" : "prorated_next_billing_period",
317
+ }
318
+ ```
319
+
320
+ The function receives the local `subscription` row as it is before the change, the `plan` being moved
321
+ to and its `priceId`. `isUpgrade` is yours to write: the plugin doesn't know how your prices rank.
322
+
323
+ > The update reuses the subscription's **cached quantity**, so you can't change plan *and* quantity
324
+ > in one call — do a quantity change through the Paddle API/dashboard.
325
+
326
+ ### Preview a plan change
327
+
328
+ `preview` takes the same body as `update` and asks Paddle what that exact change would bill, without
329
+ making it:
330
+
331
+ ```ts
332
+ const { data } = await authClient.paddle.subscription.preview({ plan: "pro", annual: true });
333
+ // {
334
+ // subscriptionId: "sub_…",
335
+ // currencyCode: "GBP",
336
+ // immediate: { action: "charge", amount: "6045" }, // or "credit"; null when nothing is billed now
337
+ // next: { amount: "7457", billedAt: "2027-11-09T15:40:54.896Z" },
338
+ // }
339
+ ```
340
+
341
+ Amounts are Paddle's minor-unit strings, tax included, so `"6045"` is £60.45. Convert using the
342
+ currency's own decimal places rather than assuming two, since some currencies (JPY, KRW) have none:
343
+
344
+ ```ts
345
+ function formatAmount(amount: string, currency: string) {
346
+ const format = new Intl.NumberFormat(undefined, { style: "currency", currency });
347
+ const digits = format.resolvedOptions().maximumFractionDigits ?? 2;
348
+ return format.format(Number(amount) / 10 ** digits);
349
+ }
350
+ ```
351
+
352
+ `immediate` is `null` when `subscription.prorationBillingMode` is a `*_next_billing_period` mode or
353
+ `do_not_bill`, where any proration is folded into `next`. A preview is a quote, not a reservation: call `update` with the same body to apply
354
+ it.
355
+
356
+ ### Cancel and restore
357
+
358
+ ```ts
359
+ // Cancel at the end of the current period (access continues until then).
360
+ await authClient.paddle.subscription.cancel(); // effectiveFrom defaults to "next_billing_period"
361
+
362
+ // Cancel right now.
363
+ await authClient.paddle.subscription.cancel({ effectiveFrom: "immediately" });
364
+
365
+ // Undo a scheduled (end-of-period) cancellation or pause before it takes effect.
366
+ await authClient.paddle.subscription.restore();
367
+ ```
368
+
369
+ `restore` only works while a cancellation or pause is *scheduled*; it returns a `400` once the
370
+ subscription has actually canceled or paused, or when nothing is scheduled.
371
+
372
+ ### Pause and resume
373
+
374
+ ```ts
375
+ // Pause at the end of the current period (access continues until then).
376
+ await authClient.paddle.subscription.pause(); // effectiveFrom defaults to "next_billing_period"
377
+
378
+ // Pause right now.
379
+ await authClient.paddle.subscription.pause({ effectiveFrom: "immediately" });
380
+
381
+ // Resume a paused subscription right now.
382
+ await authClient.paddle.subscription.resume();
383
+ await authClient.paddle.subscription.resume({ onResume: "continue_existing_billing_period" });
384
+ ```
385
+
386
+ `resume` only works on a subscription that is actually `paused`, and returns a `400` otherwise. To
387
+ cancel a pause that is still scheduled, use `restore`. `onResume` is passed through to Paddle, which
388
+ defaults to `start_new_billing_period`.
389
+
390
+ Pausing revokes access and resuming grants it again, through `onRevokeAccess` / `onGrantAccess`, once
391
+ the `subscription.paused` / `subscription.resumed` webhooks arrive.
392
+
393
+ ### Customer portal
394
+
395
+ For self-serve management (update payment method, cancel, view invoices) hand the user a
396
+ Paddle-hosted portal link:
397
+
398
+ ```ts
399
+ const { data } = await authClient.paddle.portal({ subscriptionId: "sub_..." });
400
+ window.location.href = data.url;
401
+ // data.cancelUrl / data.updatePaymentMethodUrl are also returned when subscriptionId is passed
402
+ ```
403
+
404
+ ## Payment history and invoices
405
+
406
+ Payment history is read from Paddle on each request rather than stored locally, so it includes every
407
+ payment the customer has ever made, with no backfill, no table and no extra webhook events. It lists
408
+ the signed-in user's `paid` and `completed` transactions, newest first:
409
+
410
+ ```ts
411
+ const { data } = await authClient.paddle.transaction.list();
412
+ // {
413
+ // transactions: [{
414
+ // id: "txn_…", status: "completed", origin: "subscription_recurring",
415
+ // subscriptionId: "sub_…", invoiceNumber: "325-10001",
416
+ // currencyCode: "GBP", total: "747", billedAt: "2026-11-09T14:57:44Z", createdAt: "…",
417
+ // }],
418
+ // nextCursor: "txn_…", // null on the last page
419
+ // }
420
+
421
+ const next = await authClient.paddle.transaction.list({ query: { cursor: data.nextCursor } });
422
+ ```
423
+
424
+ `total` is a minor-unit string with tax included, the same as in [`preview`](#preview-a-plan-change).
425
+ `origin` says why the payment happened, for example `web` for the first checkout,
426
+ `subscription_recurring` for a renewal and `subscription_update` for a plan change.
427
+
428
+ To download an invoice:
429
+
430
+ ```ts
431
+ const { data } = await authClient.paddle.transaction.invoice({ transactionId: "txn_…" });
432
+ window.location.href = data.url;
433
+ ```
434
+
435
+ The URL comes from Paddle and expires, so fetch it when the user clicks rather than storing it. The
436
+ route returns a `404` for a transaction that isn't the user's (or doesn't exist), and a `400` before
437
+ the transaction has an invoice. Pass `disposition: "inline"` to open the PDF in the browser instead of
438
+ downloading it.
439
+
440
+ Each call makes a Paddle API request, so cache on your side if a page lists transactions on every load.
441
+
442
+ ## Access control
443
+
444
+ The plugin fires callbacks on every access-affecting status transition — grant on
445
+ `active`/`trialing`/`resumed`, revoke on `canceled`/`paused` (and `past_due` if `revokePastDue` is
446
+ on). Use them to flip a flag, adjust entitlements, or send email:
447
+
448
+ ```ts
449
+ paddle({
450
+ // ...
451
+ onGrantAccess: async ({ userId, subscription, reason }) => {
452
+ await db.user.update({ where: { id: userId }, data: { plan: subscription.plan, active: true } });
453
+ },
454
+ onRevokeAccess: async ({ userId, reason }) => {
455
+ await db.user.update({ where: { id: userId }, data: { active: false } });
456
+ },
457
+ });
458
+ ```
459
+
460
+ Or gate synchronously by reading the mirrored row — the `subscription` table holds `status`, `plan`,
461
+ `priceId`, `periodEnd`, `cancelAtPeriodEnd`, and trial dates, so no Paddle call is needed on a
462
+ request.
463
+
464
+ By default a `past_due` subscription **keeps** access (dunning grace period) while Paddle retries
465
+ the payment; set `revokePastDue: true` to cut access the moment a payment fails. If the retries run
466
+ out and Paddle cancels or pauses the subscription, `onRevokeAccess` fires then. With
467
+ `revokePastDue: true` access is already gone by that point, so it doesn't fire again. Make every callback
468
+ idempotent — webhooks are at-least-once.
469
+
470
+ ## Webhook events
471
+
472
+ Point a Paddle [notification destination](https://developer.paddle.com/webhooks/overview) at
473
+ `https://your-app.com/api/auth/paddle/webhook`.
474
+
475
+ **Subscribe to every `subscription.*` event.** These are the only events the plugin consumes: it
476
+ reduces all of them into the local `subscription` table and fires the grant/revoke and lifecycle
477
+ callbacks. Subscribing to the whole family (rather than a hand-picked subset) keeps your state
478
+ correct — access transitions are driven by the subscription's `status`, not the event name, and it
479
+ future-proofs you against events Paddle adds later.
480
+
481
+ | Event | Why you need it |
482
+ | --- | --- |
483
+ | `subscription.created` | Creates the local row for a new subscription; fires `onSubscriptionCreated`. |
484
+ | `subscription.activated` | Trial converted or first payment taken (`status: active`) → grants access. |
485
+ | `subscription.trialing` | Subscription entered its trial (`status: trialing`) → grants access. |
486
+ | `subscription.updated` | Plan / price / quantity / scheduled-change updates; fires `onSubscriptionUpdated`. |
487
+ | `subscription.paused` | `status: paused` → revokes access. |
488
+ | `subscription.resumed` | Reactivated after a pause → re-grants access. |
489
+ | `subscription.canceled` | `status: canceled` → revokes access; fires `onSubscriptionCanceled`. |
490
+ | `subscription.past_due` | Payment failed, Paddle is retrying. Access is kept during dunning unless `revokePastDue: true`. |
491
+ | `subscription.imported` | Subscriptions migrated into Paddle (e.g. from Paddle Classic); reduced like any other update. |
492
+
493
+ A new subscription belongs to the user whose `paddleCustomerId` matches its Paddle customer, and it
494
+ keeps that owner from then on. The plugin doesn't take the owner from `custom_data.userId`, because
495
+ anyone can open a checkout with your client token and put another user's id there.
496
+
497
+ When no user is linked to the customer, the plugin logs an error and stores nothing. Paddle doesn't
498
+ resend those events, so if you create subscriptions outside the plugin, set `paddleCustomerId` on the
499
+ user through your database first. Your `onEvent` callback still receives every event.
500
+
501
+ Paddle can deliver these out of order. If `subscription.activated` or `subscription.updated` arrives
502
+ before `subscription.created`, that event creates the row and grants access. `onSubscriptionCreated`
503
+ still fires when `subscription.created` arrives, and its `subscription` is the newer state already
504
+ stored, not the older one in the late event.
505
+
506
+ Everything else is delivered untouched to your [`onEvent`](#options) callback — the plugin does
507
+ nothing with it on its own. Subscribe to these only if you want to handle them yourself:
508
+
509
+ | Event | Typical use via `onEvent` |
510
+ | --- | --- |
511
+ | `transaction.completed` | Payment settled — store receipts/invoices, fulfil one-time (non-subscription) purchases. |
512
+ | `transaction.paid` | Funds received, ahead of the transaction fully completing. |
513
+ | `transaction.payment_failed` | A failed payment attempt — custom dunning notifications, analytics. |
514
+ | `customer.updated` | Keep locally cached customer details (email, name) in sync. |
515
+ | `adjustment.created` | Refunds and credits — reconcile revenue, or revoke access on a full refund. |
516
+
517
+ If all you need is subscription state and access control, the `subscription.*` events alone are
518
+ sufficient.
519
+
520
+ ## Options
521
+
522
+ | Option | Description |
523
+ | --- | --- |
524
+ | `paddleClient` | A configured `@paddle/paddle-node-sdk` `Paddle` instance. Required. |
525
+ | `webhookSecret` | Secret for the notification destination, used to verify webhook signatures. Required. |
526
+ | `checkoutPage` | Your page that renders `<PaddleCheckout />`. Relative paths resolve against the app origin. Required. |
527
+ | `checkoutParam` | Query param carrying the transaction id on the checkout page redirect. Default `"txn"`. |
528
+ | `createCustomerOnSignUp` | Create a Paddle customer for every new user automatically. Default `true`. |
529
+ | `getCustomerCreateParams` | `(data: { user }) => { name?, customData? }` — customize the params sent to `customers.create`. |
530
+ | `onCustomerCreate` | `(data: { user, customerId }) => void` — fires once, only when a new Paddle customer is actually created (not when an [existing customer is linked](#linking-an-existing-customer)). |
531
+ | `subscription.enabled` | Turn subscription checkout and management on. |
532
+ | `subscription.plans` | Array of `{ name, priceId, annualPriceId?, limits? }`, or an async function returning it. Prices must already exist in Paddle. |
533
+ | `subscription.prorationBillingMode` | How plan changes are billed: a Paddle proration mode, or `({ subscription, plan, priceId }) => mode` to decide per change. Server-side only. Default `"prorated_immediately"`. |
534
+ | `subscription.allowMultipleSubscriptions` | Let `checkout` start a subscription for a user who already has one that isn't canceled. Default `false`: `checkout` returns a `400` with code `ALREADY_SUBSCRIBED`. See [One subscription per user](#one-subscription-per-user). |
535
+ | `subscription.requireEmailVerification` | Reject `/paddle/checkout` with 403 for unverified emails. Default `false`. Linking an [existing customer](#linking-an-existing-customer) needs a verified email whatever this is set to. |
536
+ | `revokePastDue` | Revoke access when a subscription goes `past_due`. Default `false` (dunning grace period — you keep access while Paddle retries the payment). |
537
+ | `onGrantAccess` / `onRevokeAccess` | `(data: { userId, subscription, reason }) => void` — fire on every access-affecting status transition (grant reasons: `active`, `trialing`, `resumed`; revoke reasons: `canceled`, `paused`, `past_due`). |
538
+ | `onEvent` | `(event) => void` — catch-all for every verified webhook event, regardless of type. |
539
+ | `subscription.onSubscriptionCreated` / `onSubscriptionUpdated` / `onSubscriptionCanceled` | Lifecycle callbacks scoped to the matching webhook event type, called with `{ userId, subscription, event }`. |
540
+
541
+ ## Environment variables
542
+
543
+ | Variable | Where | Purpose |
544
+ | --- | --- | --- |
545
+ | `PADDLE_API_KEY` | Server | Authenticates the `@paddle/paddle-node-sdk` client. |
546
+ | `PADDLE_WEBHOOK_SECRET` | Server | Verifies incoming webhook signatures (`webhookSecret`). |
547
+ | `NEXT_PUBLIC_PADDLE_CLIENT_TOKEN` | Client | Client-side token for `<PaddleCheckout />` (safe to expose). |
548
+
549
+ Use sandbox credentials with `Environment.sandbox` in development and live credentials with
550
+ `Environment.production` in production.
@@ -0,0 +1,59 @@
1
+ import * as better_auth_client from 'better-auth/client';
2
+ import { SubscriptionRow, paddle } from './index.js';
3
+ import '@paddle/paddle-node-sdk';
4
+ import 'better-auth';
5
+ import 'zod/v4/core';
6
+ import 'zod';
7
+
8
+ interface WaitForSubscriptionOptions {
9
+ /** The `txn_...` id the checkout was opened for. */
10
+ transactionId: string;
11
+ /** Default 30000. */
12
+ timeoutMs?: number;
13
+ /** Default 500. */
14
+ intervalMs?: number;
15
+ signal?: AbortSignal;
16
+ }
17
+ interface WaitForSubscriptionError {
18
+ status: number;
19
+ statusText: string;
20
+ code?: string;
21
+ message?: string;
22
+ }
23
+ type WaitForSubscriptionResult = {
24
+ data: SubscriptionRow;
25
+ error: null;
26
+ } | {
27
+ data: null;
28
+ error: WaitForSubscriptionError;
29
+ };
30
+ declare const paddleClient: () => {
31
+ id: "paddle";
32
+ $InferServerPlugin: ReturnType<typeof paddle>;
33
+ pathMethods: {
34
+ "/paddle/checkout": "POST";
35
+ "/paddle/subscription/cancel": "POST";
36
+ "/paddle/subscription/restore": "POST";
37
+ "/paddle/subscription/update": "POST";
38
+ "/paddle/subscription/pause": "POST";
39
+ "/paddle/subscription/resume": "POST";
40
+ "/paddle/subscription/preview": "POST";
41
+ "/paddle/transaction/invoice": "POST";
42
+ "/paddle/portal": "POST";
43
+ };
44
+ getActions: ($fetch: better_auth_client.BetterFetch) => {
45
+ paddle: {
46
+ subscription: {
47
+ /**
48
+ * Polls the local subscription list until the row created by `transactionId`'s
49
+ * webhook appears. Bridges the gap between Paddle.js `checkout.completed` and the
50
+ * `subscription.created` webhook landing.
51
+ */
52
+ waitFor: (options: WaitForSubscriptionOptions) => Promise<WaitForSubscriptionResult>;
53
+ };
54
+ };
55
+ };
56
+ };
57
+
58
+ export { paddleClient };
59
+ export type { WaitForSubscriptionError, WaitForSubscriptionOptions, WaitForSubscriptionResult };