@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 +21 -0
- package/README.md +549 -2
- package/dist/client.d.ts +59 -0
- package/dist/client.js +77 -0
- package/dist/index.d.ts +549 -0
- package/dist/index.js +756 -0
- package/dist/react/index.d.ts +30 -0
- package/dist/react/index.js +90 -0
- package/package.json +75 -4
package/dist/index.js
ADDED
|
@@ -0,0 +1,756 @@
|
|
|
1
|
+
// src/customer.ts
|
|
2
|
+
import { APIError } from "better-auth/api";
|
|
3
|
+
async function getOrCreatePaddleCustomer(args) {
|
|
4
|
+
const { options, adapter, user } = args;
|
|
5
|
+
if (user.paddleCustomerId) return user.paddleCustomerId;
|
|
6
|
+
const paddle2 = options.paddleClient;
|
|
7
|
+
const extra = await options.getCustomerCreateParams?.({ user }) ?? {};
|
|
8
|
+
let customerId;
|
|
9
|
+
let created = false;
|
|
10
|
+
try {
|
|
11
|
+
const customer = await paddle2.customers.create({
|
|
12
|
+
email: user.email,
|
|
13
|
+
name: extra.name ?? user.name ?? void 0,
|
|
14
|
+
customData: { ...extra.customData, userId: user.id }
|
|
15
|
+
});
|
|
16
|
+
customerId = customer.id;
|
|
17
|
+
created = true;
|
|
18
|
+
} catch (error) {
|
|
19
|
+
if (!isCustomerConflict(error)) throw error;
|
|
20
|
+
const existing = await findCustomerByEmail(paddle2, user.email);
|
|
21
|
+
if (!existing) throw error;
|
|
22
|
+
await assertCanLink({ adapter, user, existing });
|
|
23
|
+
customerId = existing.id;
|
|
24
|
+
}
|
|
25
|
+
await adapter.update({
|
|
26
|
+
model: "user",
|
|
27
|
+
where: [{ field: "id", value: user.id }],
|
|
28
|
+
update: { paddleCustomerId: customerId }
|
|
29
|
+
});
|
|
30
|
+
if (created) await options.onCustomerCreate?.({ user, customerId });
|
|
31
|
+
return customerId;
|
|
32
|
+
}
|
|
33
|
+
async function syncCustomerEmail(args) {
|
|
34
|
+
const { options, user } = args;
|
|
35
|
+
if (!user.paddleCustomerId) return;
|
|
36
|
+
const paddle2 = options.paddleClient;
|
|
37
|
+
const customer = await paddle2.customers.get(user.paddleCustomerId);
|
|
38
|
+
if (customer.email === user.email) return;
|
|
39
|
+
await paddle2.customers.update(user.paddleCustomerId, { email: user.email });
|
|
40
|
+
}
|
|
41
|
+
function isCustomerConflict(error) {
|
|
42
|
+
if (typeof error !== "object" || error === null) return false;
|
|
43
|
+
const { code, status, statusCode } = error;
|
|
44
|
+
if (code === "customer_already_exists") return true;
|
|
45
|
+
return status === 409 || statusCode === 409;
|
|
46
|
+
}
|
|
47
|
+
async function assertCanLink(args) {
|
|
48
|
+
const { adapter, user, existing } = args;
|
|
49
|
+
const holder = await adapter.findOne({
|
|
50
|
+
model: "user",
|
|
51
|
+
where: [{ field: "paddleCustomerId", value: existing.id }]
|
|
52
|
+
});
|
|
53
|
+
if (holder) {
|
|
54
|
+
if (holder.id === user.id) return;
|
|
55
|
+
throw new APIError("FORBIDDEN", {
|
|
56
|
+
message: "This email belongs to another account's billing customer",
|
|
57
|
+
code: "CUSTOMER_HELD_BY_ANOTHER_USER"
|
|
58
|
+
});
|
|
59
|
+
}
|
|
60
|
+
if (existing.customData?.userId === user.id) return;
|
|
61
|
+
if (!user.emailVerified) {
|
|
62
|
+
throw new APIError("FORBIDDEN", {
|
|
63
|
+
message: "Email verification required",
|
|
64
|
+
code: "EMAIL_VERIFICATION_REQUIRED"
|
|
65
|
+
});
|
|
66
|
+
}
|
|
67
|
+
}
|
|
68
|
+
async function findCustomerByEmail(paddle2, email) {
|
|
69
|
+
for await (const customer of paddle2.customers.list({ email: [email] })) {
|
|
70
|
+
return customer;
|
|
71
|
+
}
|
|
72
|
+
return null;
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
// src/routes/checkout.ts
|
|
76
|
+
import { APIError as APIError3, createAuthEndpoint, sessionMiddleware } from "better-auth/api";
|
|
77
|
+
import { z } from "zod";
|
|
78
|
+
|
|
79
|
+
// src/checkout-url.ts
|
|
80
|
+
function buildCheckoutUrl(args) {
|
|
81
|
+
const origin = new URL(args.baseURL).origin;
|
|
82
|
+
const url = new URL(args.checkoutPage, origin);
|
|
83
|
+
url.searchParams.set(args.checkoutParam ?? "txn", args.transactionId);
|
|
84
|
+
return url.toString();
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
// src/paddle-error.ts
|
|
88
|
+
import { APIError as APIError2 } from "better-auth/api";
|
|
89
|
+
function isPaddleApiError(error) {
|
|
90
|
+
return typeof error === "object" && error !== null && typeof error.code === "string" && typeof error.detail === "string";
|
|
91
|
+
}
|
|
92
|
+
async function withPaddleErrors(fn) {
|
|
93
|
+
try {
|
|
94
|
+
return await fn();
|
|
95
|
+
} catch (error) {
|
|
96
|
+
if (isPaddleApiError(error)) {
|
|
97
|
+
const status = error.code.endsWith("_not_found") ? "NOT_FOUND" : "UNPROCESSABLE_ENTITY";
|
|
98
|
+
throw new APIError2(status, { message: error.detail, code: error.code });
|
|
99
|
+
}
|
|
100
|
+
throw error;
|
|
101
|
+
}
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
// src/plans.ts
|
|
105
|
+
async function resolvePlans(plans) {
|
|
106
|
+
return typeof plans === "function" ? plans() : plans;
|
|
107
|
+
}
|
|
108
|
+
function resolvePriceId(plans, name, annual) {
|
|
109
|
+
const plan = plans.find((p) => p.name.toLowerCase() === name.toLowerCase());
|
|
110
|
+
if (!plan) return null;
|
|
111
|
+
return { plan, priceId: annual && plan.annualPriceId ? plan.annualPriceId : plan.priceId };
|
|
112
|
+
}
|
|
113
|
+
function planNameByPriceId(plans, priceId) {
|
|
114
|
+
const plan = plans.find((p) => p.priceId === priceId || p.annualPriceId === priceId);
|
|
115
|
+
return plan?.name ?? null;
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
// src/routes/checkout.ts
|
|
119
|
+
var checkout = (options) => createAuthEndpoint(
|
|
120
|
+
"/paddle/checkout",
|
|
121
|
+
{
|
|
122
|
+
method: "POST",
|
|
123
|
+
use: [sessionMiddleware],
|
|
124
|
+
body: z.object({
|
|
125
|
+
plan: z.string(),
|
|
126
|
+
annual: z.boolean().optional(),
|
|
127
|
+
quantity: z.number().int().min(1).default(1),
|
|
128
|
+
customData: z.record(z.string(), z.any()).optional(),
|
|
129
|
+
disableRedirect: z.boolean().optional()
|
|
130
|
+
})
|
|
131
|
+
},
|
|
132
|
+
async (ctx) => {
|
|
133
|
+
if (!options.subscription?.enabled) {
|
|
134
|
+
throw new APIError3("BAD_REQUEST", { message: "Subscriptions are not enabled" });
|
|
135
|
+
}
|
|
136
|
+
const { user } = ctx.context.session;
|
|
137
|
+
if (options.subscription.requireEmailVerification && !user.emailVerified) {
|
|
138
|
+
throw new APIError3("FORBIDDEN", { message: "Email verification required" });
|
|
139
|
+
}
|
|
140
|
+
const plans = await resolvePlans(options.subscription.plans);
|
|
141
|
+
const resolved = resolvePriceId(plans, ctx.body.plan, ctx.body.annual);
|
|
142
|
+
if (!resolved) {
|
|
143
|
+
throw new APIError3("BAD_REQUEST", { message: `Unknown plan: ${ctx.body.plan}` });
|
|
144
|
+
}
|
|
145
|
+
if (!options.subscription.allowMultipleSubscriptions) {
|
|
146
|
+
const subscriptions = await ctx.context.adapter.findMany({
|
|
147
|
+
model: "subscription",
|
|
148
|
+
where: [{ field: "referenceId", value: user.id }]
|
|
149
|
+
});
|
|
150
|
+
if (subscriptions.some((subscription) => subscription.status !== "canceled")) {
|
|
151
|
+
throw new APIError3("BAD_REQUEST", {
|
|
152
|
+
message: "You already have a subscription. Change its plan instead of starting a new checkout.",
|
|
153
|
+
code: "ALREADY_SUBSCRIBED"
|
|
154
|
+
});
|
|
155
|
+
}
|
|
156
|
+
}
|
|
157
|
+
const customerId = await getOrCreatePaddleCustomer({
|
|
158
|
+
options,
|
|
159
|
+
adapter: ctx.context.adapter,
|
|
160
|
+
user
|
|
161
|
+
});
|
|
162
|
+
const transaction = await withPaddleErrors(
|
|
163
|
+
() => options.paddleClient.transactions.create({
|
|
164
|
+
items: [{ priceId: resolved.priceId, quantity: ctx.body.quantity }],
|
|
165
|
+
customerId,
|
|
166
|
+
customData: { ...ctx.body.customData, userId: user.id }
|
|
167
|
+
})
|
|
168
|
+
);
|
|
169
|
+
return ctx.json({
|
|
170
|
+
transactionId: transaction.id,
|
|
171
|
+
url: buildCheckoutUrl({
|
|
172
|
+
checkoutPage: options.checkoutPage,
|
|
173
|
+
checkoutParam: options.checkoutParam,
|
|
174
|
+
baseURL: ctx.context.baseURL,
|
|
175
|
+
transactionId: transaction.id
|
|
176
|
+
}),
|
|
177
|
+
redirect: !ctx.body.disableRedirect
|
|
178
|
+
});
|
|
179
|
+
}
|
|
180
|
+
);
|
|
181
|
+
|
|
182
|
+
// src/routes/portal.ts
|
|
183
|
+
import { createAuthEndpoint as createAuthEndpoint2, sessionMiddleware as sessionMiddleware2 } from "better-auth/api";
|
|
184
|
+
import { z as z2 } from "zod";
|
|
185
|
+
var portal = (options) => createAuthEndpoint2(
|
|
186
|
+
"/paddle/portal",
|
|
187
|
+
{
|
|
188
|
+
method: "POST",
|
|
189
|
+
use: [sessionMiddleware2],
|
|
190
|
+
body: z2.object({ subscriptionId: z2.string().optional() })
|
|
191
|
+
},
|
|
192
|
+
async (ctx) => {
|
|
193
|
+
const customerId = await getOrCreatePaddleCustomer({
|
|
194
|
+
options,
|
|
195
|
+
adapter: ctx.context.adapter,
|
|
196
|
+
user: ctx.context.session.user
|
|
197
|
+
});
|
|
198
|
+
const session = await withPaddleErrors(
|
|
199
|
+
() => options.paddleClient.customerPortalSessions.create(
|
|
200
|
+
customerId,
|
|
201
|
+
ctx.body.subscriptionId ? [ctx.body.subscriptionId] : []
|
|
202
|
+
)
|
|
203
|
+
);
|
|
204
|
+
const sub = session.urls.subscriptions?.find(
|
|
205
|
+
(s) => s.id === ctx.body.subscriptionId
|
|
206
|
+
);
|
|
207
|
+
return ctx.json({
|
|
208
|
+
url: session.urls.general.overview,
|
|
209
|
+
cancelUrl: ctx.body.subscriptionId ? sub?.cancelSubscription : void 0,
|
|
210
|
+
updatePaymentMethodUrl: ctx.body.subscriptionId ? sub?.updateSubscriptionPaymentMethod : void 0
|
|
211
|
+
});
|
|
212
|
+
}
|
|
213
|
+
);
|
|
214
|
+
|
|
215
|
+
// src/routes/subscription.ts
|
|
216
|
+
import { APIError as APIError4, createAuthEndpoint as createAuthEndpoint3, sessionMiddleware as sessionMiddleware3 } from "better-auth/api";
|
|
217
|
+
import { z as z3 } from "zod";
|
|
218
|
+
async function findOwnedSubscription(ctx, subscriptionId) {
|
|
219
|
+
const userId = ctx.context.session.user.id;
|
|
220
|
+
const rows = await ctx.context.adapter.findMany({
|
|
221
|
+
model: "subscription",
|
|
222
|
+
where: [{ field: "referenceId", value: userId }]
|
|
223
|
+
});
|
|
224
|
+
if (subscriptionId) {
|
|
225
|
+
const match = rows.find((r) => r.paddleSubscriptionId === subscriptionId);
|
|
226
|
+
if (!match) {
|
|
227
|
+
throw new APIError4("NOT_FOUND", { message: "Subscription not found" });
|
|
228
|
+
}
|
|
229
|
+
return match;
|
|
230
|
+
}
|
|
231
|
+
const active = rows.filter((r) => r.status !== "canceled");
|
|
232
|
+
if (active.length === 0) {
|
|
233
|
+
throw new APIError4("NOT_FOUND", { message: "Subscription not found" });
|
|
234
|
+
}
|
|
235
|
+
if (active.length > 1) {
|
|
236
|
+
throw new APIError4("BAD_REQUEST", {
|
|
237
|
+
message: "Multiple active subscriptions found; pass subscriptionId"
|
|
238
|
+
});
|
|
239
|
+
}
|
|
240
|
+
return active[0];
|
|
241
|
+
}
|
|
242
|
+
var RESTORABLE_ACTIONS = /* @__PURE__ */ new Set(["cancel", "pause"]);
|
|
243
|
+
function scheduledAction(row) {
|
|
244
|
+
if (!row.scheduledChange) return null;
|
|
245
|
+
try {
|
|
246
|
+
return JSON.parse(row.scheduledChange).action ?? null;
|
|
247
|
+
} catch {
|
|
248
|
+
return null;
|
|
249
|
+
}
|
|
250
|
+
}
|
|
251
|
+
var subscriptionList = (_options) => createAuthEndpoint3(
|
|
252
|
+
"/paddle/subscription/list",
|
|
253
|
+
{ method: "GET", use: [sessionMiddleware3] },
|
|
254
|
+
async (ctx) => {
|
|
255
|
+
const rows = await ctx.context.adapter.findMany({
|
|
256
|
+
model: "subscription",
|
|
257
|
+
where: [{ field: "referenceId", value: ctx.context.session.user.id }]
|
|
258
|
+
});
|
|
259
|
+
return ctx.json(rows);
|
|
260
|
+
}
|
|
261
|
+
);
|
|
262
|
+
var subscriptionCancel = (options) => createAuthEndpoint3(
|
|
263
|
+
"/paddle/subscription/cancel",
|
|
264
|
+
{
|
|
265
|
+
method: "POST",
|
|
266
|
+
use: [sessionMiddleware3],
|
|
267
|
+
body: z3.object({
|
|
268
|
+
subscriptionId: z3.string().optional(),
|
|
269
|
+
effectiveFrom: z3.enum(["next_billing_period", "immediately"]).default("next_billing_period")
|
|
270
|
+
})
|
|
271
|
+
},
|
|
272
|
+
async (ctx) => {
|
|
273
|
+
const row = await findOwnedSubscription(ctx, ctx.body.subscriptionId);
|
|
274
|
+
const result = await withPaddleErrors(
|
|
275
|
+
() => options.paddleClient.subscriptions.cancel(row.paddleSubscriptionId, {
|
|
276
|
+
effectiveFrom: ctx.body.effectiveFrom
|
|
277
|
+
})
|
|
278
|
+
);
|
|
279
|
+
return ctx.json({ subscriptionId: row.paddleSubscriptionId, status: result.status });
|
|
280
|
+
}
|
|
281
|
+
);
|
|
282
|
+
var subscriptionRestore = (options) => createAuthEndpoint3(
|
|
283
|
+
"/paddle/subscription/restore",
|
|
284
|
+
{
|
|
285
|
+
method: "POST",
|
|
286
|
+
use: [sessionMiddleware3],
|
|
287
|
+
body: z3.object({ subscriptionId: z3.string().optional() })
|
|
288
|
+
},
|
|
289
|
+
async (ctx) => {
|
|
290
|
+
const row = await findOwnedSubscription(ctx, ctx.body.subscriptionId);
|
|
291
|
+
const action = scheduledAction(row);
|
|
292
|
+
if (!action || !RESTORABLE_ACTIONS.has(action)) {
|
|
293
|
+
throw new APIError4("BAD_REQUEST", { message: "No scheduled cancellation or pause to restore" });
|
|
294
|
+
}
|
|
295
|
+
const result = await withPaddleErrors(
|
|
296
|
+
() => options.paddleClient.subscriptions.update(row.paddleSubscriptionId, {
|
|
297
|
+
scheduledChange: null
|
|
298
|
+
})
|
|
299
|
+
);
|
|
300
|
+
return ctx.json({ subscriptionId: row.paddleSubscriptionId, status: result.status });
|
|
301
|
+
}
|
|
302
|
+
);
|
|
303
|
+
var subscriptionPause = (options) => createAuthEndpoint3(
|
|
304
|
+
"/paddle/subscription/pause",
|
|
305
|
+
{
|
|
306
|
+
method: "POST",
|
|
307
|
+
use: [sessionMiddleware3],
|
|
308
|
+
body: z3.object({
|
|
309
|
+
subscriptionId: z3.string().optional(),
|
|
310
|
+
effectiveFrom: z3.enum(["next_billing_period", "immediately"]).default("next_billing_period")
|
|
311
|
+
})
|
|
312
|
+
},
|
|
313
|
+
async (ctx) => {
|
|
314
|
+
const row = await findOwnedSubscription(ctx, ctx.body.subscriptionId);
|
|
315
|
+
const result = await withPaddleErrors(
|
|
316
|
+
() => options.paddleClient.subscriptions.pause(row.paddleSubscriptionId, {
|
|
317
|
+
effectiveFrom: ctx.body.effectiveFrom
|
|
318
|
+
})
|
|
319
|
+
);
|
|
320
|
+
return ctx.json({ subscriptionId: row.paddleSubscriptionId, status: result.status });
|
|
321
|
+
}
|
|
322
|
+
);
|
|
323
|
+
var subscriptionResume = (options) => createAuthEndpoint3(
|
|
324
|
+
"/paddle/subscription/resume",
|
|
325
|
+
{
|
|
326
|
+
method: "POST",
|
|
327
|
+
use: [sessionMiddleware3],
|
|
328
|
+
body: z3.object({
|
|
329
|
+
subscriptionId: z3.string().optional(),
|
|
330
|
+
onResume: z3.enum(["start_new_billing_period", "continue_existing_billing_period"]).optional()
|
|
331
|
+
})
|
|
332
|
+
},
|
|
333
|
+
async (ctx) => {
|
|
334
|
+
const row = await findOwnedSubscription(ctx, ctx.body.subscriptionId);
|
|
335
|
+
if (row.status !== "paused") {
|
|
336
|
+
throw new APIError4("BAD_REQUEST", { message: "Subscription is not paused" });
|
|
337
|
+
}
|
|
338
|
+
const result = await withPaddleErrors(
|
|
339
|
+
() => options.paddleClient.subscriptions.resume(row.paddleSubscriptionId, {
|
|
340
|
+
effectiveFrom: "immediately",
|
|
341
|
+
...ctx.body.onResume ? { onResume: ctx.body.onResume } : {}
|
|
342
|
+
})
|
|
343
|
+
);
|
|
344
|
+
return ctx.json({ subscriptionId: row.paddleSubscriptionId, status: result.status });
|
|
345
|
+
}
|
|
346
|
+
);
|
|
347
|
+
var planChangeBody = z3.object({
|
|
348
|
+
subscriptionId: z3.string().optional(),
|
|
349
|
+
plan: z3.string(),
|
|
350
|
+
annual: z3.boolean().optional()
|
|
351
|
+
});
|
|
352
|
+
async function resolvePlanChange(ctx, options) {
|
|
353
|
+
if (!options.subscription?.enabled) {
|
|
354
|
+
throw new APIError4("BAD_REQUEST", { message: "Subscriptions are not enabled" });
|
|
355
|
+
}
|
|
356
|
+
const row = await findOwnedSubscription(ctx, ctx.body.subscriptionId);
|
|
357
|
+
const plans = await resolvePlans(options.subscription.plans);
|
|
358
|
+
const resolved = resolvePriceId(plans, ctx.body.plan, ctx.body.annual);
|
|
359
|
+
if (!resolved) {
|
|
360
|
+
throw new APIError4("BAD_REQUEST", { message: `Unknown plan: ${ctx.body.plan}` });
|
|
361
|
+
}
|
|
362
|
+
const configured = options.subscription.prorationBillingMode ?? "prorated_immediately";
|
|
363
|
+
const prorationBillingMode = typeof configured === "function" ? await configured({ subscription: row, plan: resolved.plan, priceId: resolved.priceId }) : configured;
|
|
364
|
+
return {
|
|
365
|
+
row,
|
|
366
|
+
request: {
|
|
367
|
+
items: [{ priceId: resolved.priceId, quantity: row.quantity }],
|
|
368
|
+
prorationBillingMode
|
|
369
|
+
}
|
|
370
|
+
};
|
|
371
|
+
}
|
|
372
|
+
var subscriptionUpdate = (options) => createAuthEndpoint3(
|
|
373
|
+
"/paddle/subscription/update",
|
|
374
|
+
{ method: "POST", use: [sessionMiddleware3], body: planChangeBody },
|
|
375
|
+
async (ctx) => {
|
|
376
|
+
const { row, request } = await resolvePlanChange(ctx, options);
|
|
377
|
+
const result = await withPaddleErrors(
|
|
378
|
+
() => options.paddleClient.subscriptions.update(row.paddleSubscriptionId, request)
|
|
379
|
+
);
|
|
380
|
+
return ctx.json({ subscriptionId: row.paddleSubscriptionId, status: result.status });
|
|
381
|
+
}
|
|
382
|
+
);
|
|
383
|
+
var subscriptionPreview = (options) => createAuthEndpoint3(
|
|
384
|
+
"/paddle/subscription/preview",
|
|
385
|
+
{ method: "POST", use: [sessionMiddleware3], body: planChangeBody },
|
|
386
|
+
async (ctx) => {
|
|
387
|
+
const { row, request } = await resolvePlanChange(ctx, options);
|
|
388
|
+
const preview = await withPaddleErrors(
|
|
389
|
+
() => options.paddleClient.subscriptions.previewUpdate(row.paddleSubscriptionId, request)
|
|
390
|
+
);
|
|
391
|
+
const summary = preview.updateSummary?.result;
|
|
392
|
+
const billedNow = request.prorationBillingMode.endsWith("_immediately");
|
|
393
|
+
const immediate = !billedNow ? null : summary ? { action: summary.action, amount: summary.amount } : preview.immediateTransaction ? { action: "charge", amount: preview.immediateTransaction.details.totals.grandTotal } : null;
|
|
394
|
+
const result = {
|
|
395
|
+
subscriptionId: row.paddleSubscriptionId,
|
|
396
|
+
currencyCode: preview.currencyCode,
|
|
397
|
+
immediate,
|
|
398
|
+
next: preview.nextTransaction ? { amount: preview.nextTransaction.details.totals.grandTotal, billedAt: preview.nextBilledAt } : null
|
|
399
|
+
};
|
|
400
|
+
return ctx.json(result);
|
|
401
|
+
}
|
|
402
|
+
);
|
|
403
|
+
|
|
404
|
+
// src/routes/transaction.ts
|
|
405
|
+
import { APIError as APIError5, createAuthEndpoint as createAuthEndpoint4, sessionMiddleware as sessionMiddleware4 } from "better-auth/api";
|
|
406
|
+
import { z as z4 } from "zod";
|
|
407
|
+
var INVOICED_STATUSES = /* @__PURE__ */ new Set(["billed", "completed"]);
|
|
408
|
+
async function findPaddleCustomerId(ctx) {
|
|
409
|
+
const user = await ctx.context.adapter.findOne({
|
|
410
|
+
model: "user",
|
|
411
|
+
where: [{ field: "id", value: ctx.context.session.user.id }]
|
|
412
|
+
});
|
|
413
|
+
return user?.paddleCustomerId ?? null;
|
|
414
|
+
}
|
|
415
|
+
var transactionList = (options) => createAuthEndpoint4(
|
|
416
|
+
"/paddle/transaction/list",
|
|
417
|
+
{
|
|
418
|
+
method: "GET",
|
|
419
|
+
use: [sessionMiddleware4],
|
|
420
|
+
query: z4.object({
|
|
421
|
+
cursor: z4.string().optional(),
|
|
422
|
+
perPage: z4.coerce.number().int().min(1).max(50).optional()
|
|
423
|
+
}).optional()
|
|
424
|
+
},
|
|
425
|
+
async (ctx) => {
|
|
426
|
+
const customerId = await findPaddleCustomerId(ctx);
|
|
427
|
+
if (!customerId) {
|
|
428
|
+
return ctx.json({ transactions: [], nextCursor: null });
|
|
429
|
+
}
|
|
430
|
+
const collection = options.paddleClient.transactions.list({
|
|
431
|
+
customerId: [customerId],
|
|
432
|
+
status: ["paid", "completed"],
|
|
433
|
+
orderBy: "billed_at[DESC]",
|
|
434
|
+
...ctx.query?.perPage ? { perPage: ctx.query.perPage } : {},
|
|
435
|
+
...ctx.query?.cursor ? { after: ctx.query.cursor } : {}
|
|
436
|
+
});
|
|
437
|
+
const items = await withPaddleErrors(() => collection.next());
|
|
438
|
+
const transactions = items.map(
|
|
439
|
+
(t) => ({
|
|
440
|
+
id: t.id,
|
|
441
|
+
status: t.status,
|
|
442
|
+
origin: t.origin,
|
|
443
|
+
subscriptionId: t.subscriptionId,
|
|
444
|
+
invoiceNumber: t.invoiceNumber,
|
|
445
|
+
currencyCode: t.currencyCode,
|
|
446
|
+
total: t.details?.totals?.grandTotal ?? null,
|
|
447
|
+
billedAt: t.billedAt,
|
|
448
|
+
createdAt: t.createdAt
|
|
449
|
+
})
|
|
450
|
+
);
|
|
451
|
+
return ctx.json({
|
|
452
|
+
transactions,
|
|
453
|
+
nextCursor: collection.hasMore ? transactions.at(-1)?.id ?? null : null
|
|
454
|
+
});
|
|
455
|
+
}
|
|
456
|
+
);
|
|
457
|
+
var transactionInvoice = (options) => createAuthEndpoint4(
|
|
458
|
+
"/paddle/transaction/invoice",
|
|
459
|
+
{
|
|
460
|
+
method: "POST",
|
|
461
|
+
use: [sessionMiddleware4],
|
|
462
|
+
body: z4.object({
|
|
463
|
+
transactionId: z4.string(),
|
|
464
|
+
disposition: z4.enum(["attachment", "inline"]).optional()
|
|
465
|
+
})
|
|
466
|
+
},
|
|
467
|
+
async (ctx) => {
|
|
468
|
+
const notFound = () => new APIError5("NOT_FOUND", { message: "Transaction not found" });
|
|
469
|
+
const customerId = await findPaddleCustomerId(ctx);
|
|
470
|
+
if (!customerId) throw notFound();
|
|
471
|
+
const transaction = await withPaddleErrors(
|
|
472
|
+
() => options.paddleClient.transactions.get(ctx.body.transactionId)
|
|
473
|
+
).catch((error) => {
|
|
474
|
+
throw error instanceof APIError5 && error.status === "NOT_FOUND" ? notFound() : error;
|
|
475
|
+
});
|
|
476
|
+
if (transaction.customerId !== customerId) throw notFound();
|
|
477
|
+
if (!INVOICED_STATUSES.has(transaction.status)) {
|
|
478
|
+
throw new APIError5("BAD_REQUEST", { message: "This transaction has no invoice yet" });
|
|
479
|
+
}
|
|
480
|
+
const invoice = await withPaddleErrors(
|
|
481
|
+
() => options.paddleClient.transactions.getInvoicePDF(
|
|
482
|
+
transaction.id,
|
|
483
|
+
ctx.body.disposition ? { disposition: ctx.body.disposition } : {}
|
|
484
|
+
)
|
|
485
|
+
);
|
|
486
|
+
return ctx.json({ url: invoice.url });
|
|
487
|
+
}
|
|
488
|
+
);
|
|
489
|
+
|
|
490
|
+
// src/routes/webhook.ts
|
|
491
|
+
import { APIError as APIError6, createAuthEndpoint as createAuthEndpoint5 } from "better-auth/api";
|
|
492
|
+
|
|
493
|
+
// src/webhook/reducer.ts
|
|
494
|
+
var GRANTED = /* @__PURE__ */ new Set(["active", "trialing"]);
|
|
495
|
+
function reduceSubscriptionEvent(args) {
|
|
496
|
+
const occurredAt = new Date(args.occurredAt);
|
|
497
|
+
if (Number.isNaN(occurredAt.getTime())) {
|
|
498
|
+
return { action: "skip", reason: "invalid occurredAt" };
|
|
499
|
+
}
|
|
500
|
+
if (args.existing) {
|
|
501
|
+
const last = args.existing.lastEventAt instanceof Date ? args.existing.lastEventAt : new Date(args.existing.lastEventAt);
|
|
502
|
+
if (last >= occurredAt) {
|
|
503
|
+
if (args.data.transactionId && !args.existing.paddleTransactionId) {
|
|
504
|
+
return { action: "backfill", patch: { paddleTransactionId: args.data.transactionId } };
|
|
505
|
+
}
|
|
506
|
+
return { action: "skip", reason: "stale event" };
|
|
507
|
+
}
|
|
508
|
+
}
|
|
509
|
+
const { data } = args;
|
|
510
|
+
const item = data.items?.[0];
|
|
511
|
+
const priceId = item?.price?.id ?? null;
|
|
512
|
+
const plan = priceId ? planNameByPriceId(args.plans, priceId) : null;
|
|
513
|
+
const row = {
|
|
514
|
+
plan,
|
|
515
|
+
paddleCustomerId: data.customerId,
|
|
516
|
+
paddleSubscriptionId: data.id,
|
|
517
|
+
paddleTransactionId: data.transactionId ?? args.existing?.paddleTransactionId ?? null,
|
|
518
|
+
status: data.status,
|
|
519
|
+
priceId,
|
|
520
|
+
quantity: item?.quantity ?? 1,
|
|
521
|
+
periodStart: toDate(data.currentBillingPeriod?.startsAt),
|
|
522
|
+
periodEnd: toDate(data.currentBillingPeriod?.endsAt),
|
|
523
|
+
trialStart: toDate(item?.trialDates?.startsAt),
|
|
524
|
+
trialEnd: toDate(item?.trialDates?.endsAt),
|
|
525
|
+
cancelAtPeriodEnd: data.scheduledChange?.action === "cancel",
|
|
526
|
+
scheduledChange: data.scheduledChange ? JSON.stringify(data.scheduledChange) : null,
|
|
527
|
+
lastEventAt: occurredAt
|
|
528
|
+
};
|
|
529
|
+
return { action: "upsert", row, access: accessChange(args.existing?.status ?? null, data.status, args.revokePastDue) };
|
|
530
|
+
}
|
|
531
|
+
function accessChange(previous, next, revokePastDue) {
|
|
532
|
+
if (previous === next) return null;
|
|
533
|
+
if (GRANTED.has(next) && !GRANTED.has(previous ?? "")) {
|
|
534
|
+
if (previous === "paused") return { grant: "resumed" };
|
|
535
|
+
return { grant: next === "trialing" ? "trialing" : "active" };
|
|
536
|
+
}
|
|
537
|
+
const hadAccess = GRANTED.has(previous ?? "") || previous === "past_due" && !revokePastDue;
|
|
538
|
+
if (!GRANTED.has(next) && hadAccess) {
|
|
539
|
+
if (next === "canceled") return { revoke: "canceled" };
|
|
540
|
+
if (next === "paused") return { revoke: "paused" };
|
|
541
|
+
if (next === "past_due") return revokePastDue ? { revoke: "past_due" } : null;
|
|
542
|
+
}
|
|
543
|
+
return null;
|
|
544
|
+
}
|
|
545
|
+
function toDate(value) {
|
|
546
|
+
return value ? new Date(value) : null;
|
|
547
|
+
}
|
|
548
|
+
|
|
549
|
+
// src/routes/webhook.ts
|
|
550
|
+
var webhook = (options) => createAuthEndpoint5(
|
|
551
|
+
"/paddle/webhook",
|
|
552
|
+
{
|
|
553
|
+
method: "POST",
|
|
554
|
+
metadata: { isAction: false },
|
|
555
|
+
cloneRequest: true
|
|
556
|
+
},
|
|
557
|
+
async (ctx) => {
|
|
558
|
+
const signature = ctx.request?.headers.get("paddle-signature");
|
|
559
|
+
const rawBody = await ctx.request?.text();
|
|
560
|
+
if (!signature || !rawBody) {
|
|
561
|
+
throw new APIError6("UNAUTHORIZED", { message: "Missing Paddle signature" });
|
|
562
|
+
}
|
|
563
|
+
let event;
|
|
564
|
+
try {
|
|
565
|
+
event = await options.paddleClient.webhooks.unmarshal(rawBody, options.webhookSecret, signature);
|
|
566
|
+
} catch {
|
|
567
|
+
ctx.context.logger.warn("paddle: webhook signature verification failed");
|
|
568
|
+
throw new APIError6("UNAUTHORIZED", { message: "Invalid Paddle signature" });
|
|
569
|
+
}
|
|
570
|
+
if (event.eventType.startsWith("subscription.")) {
|
|
571
|
+
await handleSubscriptionEvent(ctx, options, event);
|
|
572
|
+
}
|
|
573
|
+
await options.onEvent?.(event);
|
|
574
|
+
return ctx.json({ received: true });
|
|
575
|
+
}
|
|
576
|
+
);
|
|
577
|
+
async function handleSubscriptionEvent(ctx, options, event, callbacksFired = false) {
|
|
578
|
+
const adapter = ctx.context.adapter;
|
|
579
|
+
const data = event.data;
|
|
580
|
+
const plans = options.subscription ? await resolvePlans(options.subscription.plans) : [];
|
|
581
|
+
const existing = await adapter.findOne({
|
|
582
|
+
model: "subscription",
|
|
583
|
+
where: [{ field: "paddleSubscriptionId", value: data.id }]
|
|
584
|
+
});
|
|
585
|
+
const result = reduceSubscriptionEvent({
|
|
586
|
+
eventType: event.eventType,
|
|
587
|
+
occurredAt: typeof event.occurredAt === "string" ? event.occurredAt : event.occurredAt.toISOString(),
|
|
588
|
+
data,
|
|
589
|
+
existing,
|
|
590
|
+
plans,
|
|
591
|
+
revokePastDue: options.revokePastDue ?? false
|
|
592
|
+
});
|
|
593
|
+
if (result.action === "skip") return;
|
|
594
|
+
if (result.action === "backfill") {
|
|
595
|
+
if (!callbacksFired && event.eventType === "subscription.created") {
|
|
596
|
+
await options.subscription?.onSubscriptionCreated?.({
|
|
597
|
+
userId: existing.referenceId,
|
|
598
|
+
subscription: { ...existing, ...result.patch },
|
|
599
|
+
event
|
|
600
|
+
});
|
|
601
|
+
}
|
|
602
|
+
await adapter.update({
|
|
603
|
+
model: "subscription",
|
|
604
|
+
where: [{ field: "paddleSubscriptionId", value: data.id }],
|
|
605
|
+
update: { ...result.patch, updatedAt: /* @__PURE__ */ new Date() }
|
|
606
|
+
});
|
|
607
|
+
return;
|
|
608
|
+
}
|
|
609
|
+
const referenceId = existing?.referenceId ?? await findCustomerOwner(adapter, data.customerId);
|
|
610
|
+
if (!referenceId) {
|
|
611
|
+
ctx.context.logger.error(
|
|
612
|
+
`paddle: no user is linked to customer ${data.customerId}; ignoring ${event.eventType} for ${data.id}`
|
|
613
|
+
);
|
|
614
|
+
return;
|
|
615
|
+
}
|
|
616
|
+
const row = { ...result.row, referenceId };
|
|
617
|
+
const callbackPayload = {
|
|
618
|
+
userId: referenceId,
|
|
619
|
+
subscription: row,
|
|
620
|
+
event
|
|
621
|
+
};
|
|
622
|
+
if (!callbacksFired) {
|
|
623
|
+
if (event.eventType === "subscription.created") {
|
|
624
|
+
await options.subscription?.onSubscriptionCreated?.(callbackPayload);
|
|
625
|
+
} else if (event.eventType === "subscription.canceled") {
|
|
626
|
+
await options.subscription?.onSubscriptionCanceled?.(callbackPayload);
|
|
627
|
+
} else {
|
|
628
|
+
await options.subscription?.onSubscriptionUpdated?.(callbackPayload);
|
|
629
|
+
}
|
|
630
|
+
if (result.access) {
|
|
631
|
+
if ("grant" in result.access) {
|
|
632
|
+
await options.onGrantAccess?.({ ...callbackPayload, reason: result.access.grant });
|
|
633
|
+
} else {
|
|
634
|
+
await options.onRevokeAccess?.({ ...callbackPayload, reason: result.access.revoke });
|
|
635
|
+
}
|
|
636
|
+
}
|
|
637
|
+
}
|
|
638
|
+
if (existing) {
|
|
639
|
+
const written = await adapter.update({
|
|
640
|
+
model: "subscription",
|
|
641
|
+
where: [
|
|
642
|
+
{ field: "paddleSubscriptionId", value: data.id },
|
|
643
|
+
{ field: "lastEventAt", operator: "lt", value: row.lastEventAt }
|
|
644
|
+
],
|
|
645
|
+
update: { ...row, updatedAt: /* @__PURE__ */ new Date() }
|
|
646
|
+
});
|
|
647
|
+
if (!written) await handleSubscriptionEvent(ctx, options, event, true);
|
|
648
|
+
} else {
|
|
649
|
+
try {
|
|
650
|
+
await adapter.create({
|
|
651
|
+
model: "subscription",
|
|
652
|
+
data: { ...row, createdAt: /* @__PURE__ */ new Date(), updatedAt: /* @__PURE__ */ new Date() }
|
|
653
|
+
});
|
|
654
|
+
} catch (error) {
|
|
655
|
+
const winner = await adapter.findOne({
|
|
656
|
+
model: "subscription",
|
|
657
|
+
where: [{ field: "paddleSubscriptionId", value: data.id }]
|
|
658
|
+
});
|
|
659
|
+
if (!winner) throw error;
|
|
660
|
+
await handleSubscriptionEvent(ctx, options, event, true);
|
|
661
|
+
}
|
|
662
|
+
}
|
|
663
|
+
}
|
|
664
|
+
async function findCustomerOwner(adapter, customerId) {
|
|
665
|
+
const user = await adapter.findOne({
|
|
666
|
+
model: "user",
|
|
667
|
+
where: [{ field: "paddleCustomerId", value: customerId }]
|
|
668
|
+
});
|
|
669
|
+
return user?.id;
|
|
670
|
+
}
|
|
671
|
+
|
|
672
|
+
// src/schema.ts
|
|
673
|
+
function getSchema() {
|
|
674
|
+
return {
|
|
675
|
+
user: {
|
|
676
|
+
fields: {
|
|
677
|
+
paddleCustomerId: { type: "string", required: false, input: false }
|
|
678
|
+
}
|
|
679
|
+
},
|
|
680
|
+
subscription: {
|
|
681
|
+
fields: {
|
|
682
|
+
plan: { type: "string", required: false },
|
|
683
|
+
referenceId: { type: "string", required: true },
|
|
684
|
+
paddleCustomerId: { type: "string", required: true },
|
|
685
|
+
paddleSubscriptionId: { type: "string", required: true, unique: true },
|
|
686
|
+
paddleTransactionId: { type: "string", required: false },
|
|
687
|
+
status: { type: "string", required: true },
|
|
688
|
+
priceId: { type: "string", required: false },
|
|
689
|
+
quantity: { type: "number", required: false, defaultValue: 1 },
|
|
690
|
+
periodStart: { type: "date", required: false },
|
|
691
|
+
periodEnd: { type: "date", required: false },
|
|
692
|
+
trialStart: { type: "date", required: false },
|
|
693
|
+
trialEnd: { type: "date", required: false },
|
|
694
|
+
cancelAtPeriodEnd: { type: "boolean", required: false, defaultValue: false },
|
|
695
|
+
scheduledChange: { type: "string", required: false },
|
|
696
|
+
lastEventAt: { type: "date", required: true },
|
|
697
|
+
createdAt: { type: "date", required: true, defaultValue: () => /* @__PURE__ */ new Date() },
|
|
698
|
+
updatedAt: { type: "date", required: true, defaultValue: () => /* @__PURE__ */ new Date() }
|
|
699
|
+
}
|
|
700
|
+
}
|
|
701
|
+
};
|
|
702
|
+
}
|
|
703
|
+
|
|
704
|
+
// src/index.ts
|
|
705
|
+
var paddle = (options) => {
|
|
706
|
+
return {
|
|
707
|
+
id: "paddle",
|
|
708
|
+
schema: getSchema(),
|
|
709
|
+
init(ctx) {
|
|
710
|
+
return {
|
|
711
|
+
options: {
|
|
712
|
+
databaseHooks: {
|
|
713
|
+
user: {
|
|
714
|
+
create: {
|
|
715
|
+
after: async (user) => {
|
|
716
|
+
if (options.createCustomerOnSignUp === false) return;
|
|
717
|
+
try {
|
|
718
|
+
await getOrCreatePaddleCustomer({ options, adapter: ctx.adapter, user });
|
|
719
|
+
} catch (error) {
|
|
720
|
+
ctx.logger.error("paddle: failed to create customer on signup", error);
|
|
721
|
+
}
|
|
722
|
+
}
|
|
723
|
+
},
|
|
724
|
+
update: {
|
|
725
|
+
after: async (user) => {
|
|
726
|
+
try {
|
|
727
|
+
await syncCustomerEmail({ options, user });
|
|
728
|
+
} catch (error) {
|
|
729
|
+
ctx.logger.error("paddle: failed to sync customer email", error);
|
|
730
|
+
}
|
|
731
|
+
}
|
|
732
|
+
}
|
|
733
|
+
}
|
|
734
|
+
}
|
|
735
|
+
}
|
|
736
|
+
};
|
|
737
|
+
},
|
|
738
|
+
endpoints: {
|
|
739
|
+
paddleCheckout: checkout(options),
|
|
740
|
+
paddlePortal: portal(options),
|
|
741
|
+
paddleWebhook: webhook(options),
|
|
742
|
+
paddleSubscriptionList: subscriptionList(options),
|
|
743
|
+
paddleSubscriptionCancel: subscriptionCancel(options),
|
|
744
|
+
paddleSubscriptionRestore: subscriptionRestore(options),
|
|
745
|
+
paddleSubscriptionUpdate: subscriptionUpdate(options),
|
|
746
|
+
paddleSubscriptionPause: subscriptionPause(options),
|
|
747
|
+
paddleSubscriptionResume: subscriptionResume(options),
|
|
748
|
+
paddleSubscriptionPreview: subscriptionPreview(options),
|
|
749
|
+
paddleTransactionList: transactionList(options),
|
|
750
|
+
paddleTransactionInvoice: transactionInvoice(options)
|
|
751
|
+
}
|
|
752
|
+
};
|
|
753
|
+
};
|
|
754
|
+
export {
|
|
755
|
+
paddle
|
|
756
|
+
};
|