better-auth-paystack 0.0.0 → 3.1.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (35) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +842 -0
  3. package/dist/client.d.mts +151 -0
  4. package/dist/client.d.mts.map +1 -0
  5. package/dist/client.mjs +129 -0
  6. package/dist/client.mjs.map +1 -0
  7. package/dist/index-BfHLsAWb.d.mts +781 -0
  8. package/dist/index-BfHLsAWb.d.mts.map +1 -0
  9. package/dist/index.d.mts +2 -0
  10. package/dist/index.mjs +2760 -0
  11. package/dist/index.mjs.map +1 -0
  12. package/dist/version-Db-470Pe.mjs +73 -0
  13. package/dist/version-Db-470Pe.mjs.map +1 -0
  14. package/package.json +118 -8
  15. package/skills/better-auth-paystack-setup/SKILL.md +144 -0
  16. package/skills/better-auth-paystack-setup/agents/openai.yaml +6 -0
  17. package/skills/paystack-billing-flows/SKILL.md +154 -0
  18. package/skills/paystack-billing-flows/agents/openai.yaml +6 -0
  19. package/skills/paystack-catalog-limits/SKILL.md +183 -0
  20. package/skills/paystack-catalog-limits/agents/openai.yaml +6 -0
  21. package/skills/paystack-client-api/SKILL.md +120 -0
  22. package/skills/paystack-client-api/agents/openai.yaml +6 -0
  23. package/skills/paystack-local-subscriptions/SKILL.md +97 -0
  24. package/skills/paystack-local-subscriptions/agents/openai.yaml +6 -0
  25. package/skills/paystack-organization-billing/SKILL.md +159 -0
  26. package/skills/paystack-organization-billing/agents/openai.yaml +6 -0
  27. package/skills/paystack-schema-migrations/SKILL.md +94 -0
  28. package/skills/paystack-schema-migrations/agents/openai.yaml +6 -0
  29. package/skills/paystack-tanstack-start/SKILL.md +170 -0
  30. package/skills/paystack-tanstack-start/agents/openai.yaml +6 -0
  31. package/skills/paystack-testing-fixtures/SKILL.md +97 -0
  32. package/skills/paystack-testing-fixtures/agents/openai.yaml +6 -0
  33. package/skills/paystack-webhooks-events/SKILL.md +106 -0
  34. package/skills/paystack-webhooks-events/agents/openai.yaml +6 -0
  35. package/index.js +0 -1
package/dist/index.mjs ADDED
@@ -0,0 +1,2760 @@
1
+ import { a as getMetadataBoolean, c as hasPaystackMetadata, i as createRenewalMetadata, l as parsePaystackMetadata, n as createCheckoutMetadata, o as getMetadataNumber, r as createProrationMetadata, s as getMetadataString, t as PACKAGE_VERSION, u as stringifyPaystackMetadata } from "./version-Db-470Pe.mjs";
2
+ import { HIDE_METADATA, defineErrorCodes } from "better-auth";
3
+ import { APIError, createAuthEndpoint, createAuthMiddleware, getSessionFromCtx, originCheck, sessionMiddleware } from "better-auth/api";
4
+ import { defu } from "defu";
5
+ import { z } from "zod";
6
+ import { PaystackError, PaystackResponse } from "@alexasomba/paystack-node";
7
+ import { mergeSchema } from "better-auth/db";
8
+ //#region src/billing-store.ts
9
+ function sortSubscriptionsForCurrent(subscriptions) {
10
+ const statusRank = /* @__PURE__ */ new Map([
11
+ ["active", 0],
12
+ ["trialing", 1],
13
+ ["incomplete", 2],
14
+ ["past_due", 3],
15
+ ["canceled", 4]
16
+ ]);
17
+ return [...subscriptions].sort((a, b) => {
18
+ const rankA = statusRank.get(a.status) ?? 99;
19
+ const rankB = statusRank.get(b.status) ?? 99;
20
+ if (rankA !== rankB) return rankA - rankB;
21
+ return new Date(b.updatedAt).getTime() - new Date(a.updatedAt).getTime();
22
+ });
23
+ }
24
+ function createBillingStore(ctx) {
25
+ return createBillingStoreFromAdapter(ctx.context.adapter);
26
+ }
27
+ function createBillingStoreFromAdapter(adapter) {
28
+ const findOne = async (model, where) => await adapter.findOne({
29
+ model,
30
+ where
31
+ }) ?? null;
32
+ const findMany = async (model, where) => await adapter.findMany({
33
+ model,
34
+ ...where ? { where } : {}
35
+ }) ?? [];
36
+ return {
37
+ findSubscriptionById: (id) => findOne("subscription", [{
38
+ field: "id",
39
+ value: id
40
+ }]),
41
+ findSubscriptionByCode: (subscriptionCode) => findOne("subscription", [{
42
+ field: "paystackSubscriptionCode",
43
+ value: subscriptionCode
44
+ }]),
45
+ findSubscriptionsByReference: (referenceId) => findMany("subscription", [{
46
+ field: "referenceId",
47
+ value: referenceId
48
+ }]),
49
+ async findCurrentSubscription(referenceId, groupId) {
50
+ const subscriptions = await this.findSubscriptionsByReference(referenceId);
51
+ return sortSubscriptionsForCurrent(groupId === void 0 ? subscriptions : subscriptions.filter((subscription) => groupId === null ? subscription.groupId === void 0 || subscription.groupId === null || subscription.groupId === "" : subscription.groupId === groupId))[0] ?? null;
52
+ },
53
+ async retireCompetingSubscriptions(referenceId, groupId, exceptId) {
54
+ const competitors = (await this.findSubscriptionsByReference(referenceId)).filter((subscription) => subscription.id !== exceptId && (subscription.status === "active" || subscription.status === "trialing") && (groupId === null ? subscription.groupId === void 0 || subscription.groupId === null || subscription.groupId === "" : subscription.groupId === groupId));
55
+ const now = /* @__PURE__ */ new Date();
56
+ for (const subscription of competitors) await this.updateSubscription(subscription.id, {
57
+ status: "canceled",
58
+ cancelAtPeriodEnd: false,
59
+ canceledAt: now,
60
+ endedAt: now,
61
+ updatedAt: now
62
+ });
63
+ },
64
+ findSubscriptionsByTransactionReference: (reference) => findMany("subscription", [{
65
+ field: "paystackTransactionReference",
66
+ value: reference
67
+ }]),
68
+ createSubscription: async (data) => await adapter.create({
69
+ model: "subscription",
70
+ data
71
+ }),
72
+ updateSubscription: (id, update) => adapter.update({
73
+ model: "subscription",
74
+ update,
75
+ where: [{
76
+ field: "id",
77
+ value: id
78
+ }]
79
+ }),
80
+ updateSubscriptionByCode: (subscriptionCode, update) => adapter.update({
81
+ model: "subscription",
82
+ update,
83
+ where: [{
84
+ field: "paystackSubscriptionCode",
85
+ value: subscriptionCode
86
+ }]
87
+ }),
88
+ createTransaction: async (data) => await adapter.create({
89
+ model: "paystackTransaction",
90
+ data
91
+ }),
92
+ findTransactionByReference: (reference) => findOne("paystackTransaction", [{
93
+ field: "reference",
94
+ value: reference
95
+ }]),
96
+ updateTransactionByReference: (reference, update) => adapter.update({
97
+ model: "paystackTransaction",
98
+ update,
99
+ where: [{
100
+ field: "reference",
101
+ value: reference
102
+ }]
103
+ }),
104
+ async listTransactions(referenceId) {
105
+ return (await findMany("paystackTransaction", [{
106
+ field: "referenceId",
107
+ value: referenceId
108
+ }])).sort((a, b) => b.createdAt.getTime() - a.createdAt.getTime());
109
+ },
110
+ async listProducts() {
111
+ return (await findMany("paystackProduct")).sort((a, b) => a.name.localeCompare(b.name));
112
+ },
113
+ findProductByName: (name) => findOne("paystackProduct", [{
114
+ field: "name",
115
+ value: name
116
+ }]),
117
+ findProductBySlug: (slug) => findOne("paystackProduct", [{
118
+ field: "slug",
119
+ value: slug
120
+ }]),
121
+ async updateProduct(id, update) {
122
+ await adapter.update({
123
+ model: "paystackProduct",
124
+ update,
125
+ where: [{
126
+ field: "id",
127
+ value: id
128
+ }]
129
+ });
130
+ },
131
+ async upsertProductByPaystackId(paystackId, data) {
132
+ const existing = await findOne("paystackProduct", [{
133
+ field: "paystackId",
134
+ value: paystackId
135
+ }]);
136
+ if (existing?.id !== void 0) {
137
+ const { createdAt: _createdAt, ...update } = data;
138
+ await adapter.update({
139
+ model: "paystackProduct",
140
+ update,
141
+ where: [{
142
+ field: "id",
143
+ value: String(existing.id)
144
+ }]
145
+ });
146
+ return;
147
+ }
148
+ await adapter.create({
149
+ model: "paystackProduct",
150
+ data
151
+ });
152
+ },
153
+ listPlans: () => findMany("paystackPlan"),
154
+ findPlanByName: (name) => findOne("paystackPlan", [{
155
+ field: "name",
156
+ value: name
157
+ }]),
158
+ findPlanByCode: (planCode) => findOne("paystackPlan", [{
159
+ field: "planCode",
160
+ value: planCode
161
+ }]),
162
+ async upsertPlanByPaystackId(paystackId, data) {
163
+ const existing = await findOne("paystackPlan", [{
164
+ field: "paystackId",
165
+ value: paystackId
166
+ }]);
167
+ if (existing?.id !== void 0) {
168
+ const { createdAt: _createdAt, ...update } = data;
169
+ await adapter.update({
170
+ model: "paystackPlan",
171
+ update,
172
+ where: [{
173
+ field: "id",
174
+ value: existing.id
175
+ }]
176
+ });
177
+ return;
178
+ }
179
+ await adapter.create({
180
+ model: "paystackPlan",
181
+ data
182
+ });
183
+ },
184
+ findUser: (id) => findOne("user", [{
185
+ field: "id",
186
+ value: id
187
+ }]),
188
+ findOrganization: (id) => findOne("organization", [{
189
+ field: "id",
190
+ value: id
191
+ }]),
192
+ findOrganizationOwner: (organizationId) => findOne("member", [{
193
+ field: "organizationId",
194
+ value: organizationId
195
+ }, {
196
+ field: "role",
197
+ value: "owner"
198
+ }]),
199
+ listMembers: (organizationId) => findMany("member", [{
200
+ field: "organizationId",
201
+ value: organizationId
202
+ }]),
203
+ listTeams: (organizationId) => findMany("team", [{
204
+ field: "organizationId",
205
+ value: organizationId
206
+ }]),
207
+ async saveCustomerCode(referenceId, customerCode, isOrganization) {
208
+ await adapter.update({
209
+ model: isOrganization ? "organization" : "user",
210
+ update: { paystackCustomerCode: customerCode },
211
+ where: [{
212
+ field: "id",
213
+ value: referenceId
214
+ }]
215
+ });
216
+ }
217
+ };
218
+ }
219
+ //#endregion
220
+ //#region src/paystack-sdk.ts
221
+ /**
222
+ * Interface for checking if a result is a PaystackResponse from the SDK v1.9.1+
223
+ */
224
+ function IsPaystackResponse(value) {
225
+ return value instanceof PaystackResponse;
226
+ }
227
+ /**
228
+ * Unwraps a Paystack SDK result, extracting the data or throwing an APIError if the request failed.
229
+ * Leverages the native .unwrap() method in SDK v1.9.1+ if available.
230
+ */
231
+ function unwrapSdkResult(result) {
232
+ if (IsPaystackResponse(result)) try {
233
+ return result.unwrap();
234
+ } catch (e) {
235
+ if (e instanceof PaystackError) throw new APIError("BAD_REQUEST", {
236
+ message: e.message,
237
+ status: e.status
238
+ });
239
+ throw new APIError("BAD_REQUEST", { message: e?.message ?? "Paystack API error" });
240
+ }
241
+ let current = result;
242
+ while (current !== null && current !== void 0 && typeof current === "object") {
243
+ const body = current;
244
+ if (body.status === false) throw new APIError("BAD_REQUEST", { message: body.message ?? "Paystack API error" });
245
+ if ("authorization_url" in body || "reference" in body || "customer_code" in body) break;
246
+ if ("data" in body && body.data !== void 0 && body.data !== null && typeof body.data === "object") {
247
+ current = body.data;
248
+ continue;
249
+ }
250
+ break;
251
+ }
252
+ return current;
253
+ }
254
+ /**
255
+ * Returns the operations object from a Paystack client.
256
+ * For v1.9.1+, the client itself uses the grouped structure.
257
+ */
258
+ function getPaystackOps(client) {
259
+ return client;
260
+ }
261
+ function createPaystackAdapter(client) {
262
+ const requireClient = () => {
263
+ if (client === void 0 || client === null) throw new APIError("BAD_REQUEST", { message: "Paystack client is not configured" });
264
+ return client;
265
+ };
266
+ return {
267
+ async initializeTransaction(body) {
268
+ return unwrapSdkResult(await requireClient().transaction?.initialize({ body }));
269
+ },
270
+ async verifyTransaction(reference) {
271
+ return unwrapSdkResult(await requireClient().transaction?.verify(reference));
272
+ },
273
+ async chargeAuthorization(body) {
274
+ return unwrapSdkResult(await requireClient().transaction?.chargeAuthorization({ body }));
275
+ },
276
+ async createCustomer(body) {
277
+ return unwrapSdkResult(await requireClient().customer?.create({ body }));
278
+ },
279
+ async fetchCustomer(emailOrCode) {
280
+ return unwrapSdkResult(await requireClient().customer?.fetch(emailOrCode));
281
+ },
282
+ async updateCustomer(emailOrCode, body) {
283
+ return unwrapSdkResult(await requireClient().customer?.update(emailOrCode, { body }));
284
+ },
285
+ async listProducts() {
286
+ return unwrapSdkResult(await requireClient().product?.list({}));
287
+ },
288
+ async fetchProduct(productId) {
289
+ return unwrapSdkResult(await requireClient().product?.fetch(productId));
290
+ },
291
+ async listPlans() {
292
+ return unwrapSdkResult(await requireClient().plan?.list());
293
+ },
294
+ async createSubscription(body) {
295
+ return unwrapSdkResult(await requireClient().subscription?.create({ body }));
296
+ },
297
+ async fetchSubscription(subscriptionCode) {
298
+ return unwrapSdkResult(await requireClient().subscription?.fetch(subscriptionCode));
299
+ },
300
+ async disableSubscription(body) {
301
+ return unwrapSdkResult(await requireClient().subscription?.disable({ body }));
302
+ },
303
+ async enableSubscription(body) {
304
+ return unwrapSdkResult(await requireClient().subscription?.enable({ body }));
305
+ },
306
+ async manageSubscriptionLink(subscriptionCode) {
307
+ return unwrapSdkResult(await requireClient().subscription?.manageLink(subscriptionCode));
308
+ }
309
+ };
310
+ }
311
+ //#endregion
312
+ //#region src/utils.ts
313
+ function getPlanSeatAmount(plan) {
314
+ if (plan.seatAmount !== void 0) {
315
+ if (typeof plan.seatAmount === "number" && Number.isFinite(plan.seatAmount)) return plan.seatAmount;
316
+ throw new Error(`Invalid seatAmount for plan '${plan.name}'. Expected a finite number.`);
317
+ }
318
+ if (plan.seatPriceId === void 0 || plan.seatPriceId === null || plan.seatPriceId === "") return;
319
+ const parsed = typeof plan.seatPriceId === "string" ? Number(plan.seatPriceId) : plan.seatPriceId;
320
+ if (typeof parsed === "number" && Number.isFinite(parsed)) return parsed;
321
+ throw new Error(`Invalid seatPriceId for plan '${plan.name}'. Expected a numeric amount in the smallest currency unit.`);
322
+ }
323
+ function calculatePlanAmount(plan, quantity) {
324
+ return (plan.amount ?? 0) + quantity * (getPlanSeatAmount(plan) ?? 0);
325
+ }
326
+ function normalizeSubscriptionGroup(group) {
327
+ const normalized = group?.trim().toLowerCase();
328
+ return normalized === void 0 || normalized === "" ? null : normalized;
329
+ }
330
+ function isLocalSubscriptionCode(subscriptionCode) {
331
+ return typeof subscriptionCode === "string" && (subscriptionCode.startsWith("LOC_") || subscriptionCode.startsWith("sub_local_"));
332
+ }
333
+ function isLocallyManagedSubscription(subscription) {
334
+ if (isLocalSubscriptionCode(subscription.paystackSubscriptionCode)) return true;
335
+ if (typeof subscription.paystackSubscriptionCode === "string" && subscription.paystackSubscriptionCode !== "") return false;
336
+ return subscription.paystackPlanCode === void 0 || subscription.paystackPlanCode === null || subscription.paystackPlanCode === "";
337
+ }
338
+ function assertLocallyManagedSubscription(subscription, action) {
339
+ if (!isLocallyManagedSubscription(subscription)) throw new Error(`Paystack-managed subscriptions do not support ${action}. Use local billing for seat-based or prorated subscription changes.`);
340
+ }
341
+ async function getPlans(subscriptionOptions) {
342
+ if (subscriptionOptions?.enabled === true) return typeof subscriptionOptions.plans === "function" ? subscriptionOptions.plans() : subscriptionOptions.plans;
343
+ throw new Error("Subscriptions are not enabled in the Paystack options.");
344
+ }
345
+ async function getPlanByName(options, name) {
346
+ if (typeof name !== "string" || name.trim() === "") return null;
347
+ if (options.subscription?.enabled === true) {
348
+ const plans = await getPlans(options.subscription);
349
+ const normalizedName = name.toLowerCase();
350
+ return plans.find((plan) => typeof plan.name === "string" && plan.name.toLowerCase() === normalizedName) ?? null;
351
+ }
352
+ return null;
353
+ }
354
+ async function getProducts(productOptions) {
355
+ if (productOptions?.products) return typeof productOptions.products === "function" ? await productOptions.products() : productOptions.products;
356
+ return [];
357
+ }
358
+ async function getProductByName(options, name) {
359
+ return await getProducts(options.products).then((products) => products !== void 0 && products !== null ? products.find((product) => product.name.toLowerCase() === name.toLowerCase()) ?? null : null);
360
+ }
361
+ function getNextPeriodEnd(startDate, interval) {
362
+ const date = new Date(startDate);
363
+ switch (interval) {
364
+ case "daily":
365
+ date.setDate(date.getDate() + 1);
366
+ break;
367
+ case "weekly":
368
+ date.setDate(date.getDate() + 7);
369
+ break;
370
+ case "monthly":
371
+ date.setMonth(date.getMonth() + 1);
372
+ break;
373
+ case "quarterly":
374
+ date.setMonth(date.getMonth() + 3);
375
+ break;
376
+ case "biannually":
377
+ date.setMonth(date.getMonth() + 6);
378
+ break;
379
+ case "annually":
380
+ date.setFullYear(date.getFullYear() + 1);
381
+ break;
382
+ default: date.setMonth(date.getMonth() + 1);
383
+ }
384
+ return date;
385
+ }
386
+ /**
387
+ * Validates if the amount meets Paystack's minimum transaction requirements.
388
+ * Amounts should be in the smallest currency unit (e.g., kobo, cents).
389
+ */
390
+ function validateMinAmount(amount, currency) {
391
+ const min = {
392
+ NGN: 5e3,
393
+ GHS: 10,
394
+ ZAR: 100,
395
+ KES: 300,
396
+ USD: 200,
397
+ XOF: 100
398
+ }[currency.toUpperCase()];
399
+ return min !== void 0 ? amount >= min : true;
400
+ }
401
+ async function syncProductQuantityFromPaystack(ctx, productName, paystackClient) {
402
+ const store = createBillingStore(ctx);
403
+ let localProduct = await store.findProductByName(productName);
404
+ localProduct ??= await store.findProductBySlug(productName.toLowerCase().replace(/\s+/g, "-"));
405
+ if (localProduct?.paystackId === void 0 || localProduct.paystackId === null || localProduct.paystackId === "") {
406
+ if (localProduct?.id !== void 0 && localProduct.unlimited !== true && typeof localProduct.quantity === "number" && localProduct.quantity > 0) await store.updateProduct(localProduct.id, {
407
+ quantity: localProduct.quantity - 1,
408
+ updatedAt: /* @__PURE__ */ new Date()
409
+ });
410
+ return;
411
+ }
412
+ try {
413
+ const paystackProductId = Number(localProduct.paystackId);
414
+ if (!Number.isFinite(paystackProductId)) return;
415
+ const remoteQuantity = (await createPaystackAdapter(paystackClient).fetchProduct(paystackProductId))?.quantity;
416
+ if (remoteQuantity !== void 0 && localProduct.id !== void 0) await store.updateProduct(localProduct.id, {
417
+ quantity: remoteQuantity,
418
+ updatedAt: /* @__PURE__ */ new Date()
419
+ });
420
+ } catch {
421
+ if (localProduct?.id !== void 0 && localProduct.unlimited !== true && typeof localProduct.quantity === "number" && localProduct.quantity > 0) await store.updateProduct(localProduct.id, {
422
+ quantity: localProduct.quantity - 1,
423
+ updatedAt: /* @__PURE__ */ new Date()
424
+ });
425
+ }
426
+ }
427
+ async function syncSubscriptionSeats(ctx, organizationId, options) {
428
+ if (options.subscription?.enabled !== true) return;
429
+ const store = createBillingStore(ctx);
430
+ const subscriptions = (await store.findSubscriptionsByReference(organizationId)).filter((subscription) => subscription.status === "active" || subscription.status === "trialing");
431
+ const seatSubscriptions = [];
432
+ for (const candidate of subscriptions) {
433
+ const candidatePlan = await getPlanByName(options, candidate.plan);
434
+ if (candidatePlan !== null && getPlanSeatAmount(candidatePlan) !== void 0) seatSubscriptions.push(candidate);
435
+ }
436
+ const quantity = (await store.listMembers(organizationId)).length;
437
+ for (const subscription of seatSubscriptions) {
438
+ if (subscription.paystackSubscriptionCode === void 0 || subscription.paystackSubscriptionCode === null || subscription.paystackSubscriptionCode === "") continue;
439
+ try {
440
+ assertLocallyManagedSubscription(subscription, "automatic seat sync");
441
+ await store.updateSubscription(subscription.id, {
442
+ seats: quantity,
443
+ updatedAt: /* @__PURE__ */ new Date()
444
+ });
445
+ } catch (e) {
446
+ ctx.context.logger.error("Failed to sync subscription seats", e);
447
+ }
448
+ }
449
+ }
450
+ //#endregion
451
+ //#region src/reference-access.ts
452
+ const DEFAULT_BILLING_ORG_ROLES = ["owner", "admin"];
453
+ function normalizeBillingRoles(roles) {
454
+ return new Set(roles.map((value) => value.trim()).filter((value) => value !== ""));
455
+ }
456
+ function getBillingRoles(options) {
457
+ return options.organization?.billingRoles ?? DEFAULT_BILLING_ORG_ROLES;
458
+ }
459
+ function hasBillingRole(role, billingRoles = DEFAULT_BILLING_ORG_ROLES) {
460
+ const allowedRoles = normalizeBillingRoles(billingRoles);
461
+ if (Array.isArray(role)) return role.some((value) => hasBillingRole(value, billingRoles));
462
+ if (typeof role !== "string") return false;
463
+ return role.split(",").map((value) => value.trim()).some((value) => allowedRoles.has(value));
464
+ }
465
+ function resolveBillingReferenceId(input) {
466
+ const body = input.body ?? {};
467
+ const query = input.query ?? {};
468
+ const requestQueryReferenceId = typeof input.requestUrl === "string" ? new URL(input.requestUrl).searchParams.get("referenceId") ?? void 0 : void 0;
469
+ return body.referenceId ?? query.referenceId ?? requestQueryReferenceId ?? input.fallbackUserId;
470
+ }
471
+ async function authorizeBillingReference(ctx, options, data) {
472
+ if (data.referenceId === data.user.id) return;
473
+ if (options.subscription?.enabled === true && typeof options.subscription.authorizeReference === "function") {
474
+ if (await options.subscription.authorizeReference({
475
+ user: data.user,
476
+ session: data.session,
477
+ referenceId: data.referenceId,
478
+ action: data.action
479
+ }, ctx) === true) return;
480
+ throw new APIError("UNAUTHORIZED");
481
+ }
482
+ if (options.organization?.enabled === true) {
483
+ const member = await ctx.context.adapter.findOne({
484
+ model: "member",
485
+ where: [{
486
+ field: "userId",
487
+ value: data.user.id
488
+ }, {
489
+ field: "organizationId",
490
+ value: data.referenceId
491
+ }]
492
+ });
493
+ if (member !== null && member !== void 0 && hasBillingRole(member.role, getBillingRoles(options))) return;
494
+ }
495
+ throw new APIError("UNAUTHORIZED");
496
+ }
497
+ //#endregion
498
+ //#region src/middleware.ts
499
+ const referenceMiddleware = (options, action) => createAuthMiddleware(async (ctx) => {
500
+ const session = ctx.context.session;
501
+ if (session === null || session === void 0) throw new APIError("UNAUTHORIZED");
502
+ const referenceId = resolveBillingReferenceId({
503
+ body: ctx.body,
504
+ query: ctx.query,
505
+ requestUrl: ctx.request?.url,
506
+ fallbackUserId: session.user.id
507
+ });
508
+ await authorizeBillingReference(ctx, options, {
509
+ user: session.user,
510
+ session: session.session,
511
+ referenceId,
512
+ action
513
+ });
514
+ return { context: {
515
+ ...ctx.context,
516
+ referenceId
517
+ } };
518
+ });
519
+ //#endregion
520
+ //#region src/limits.ts
521
+ const getOrganizationSubscription = async (ctx, organizationId, groupId) => {
522
+ return createBillingStore(ctx).findCurrentSubscription(organizationId, groupId);
523
+ };
524
+ const checkSeatLimit = async (ctx, organizationId, seatsToAdd = 1) => {
525
+ const store = createBillingStore(ctx);
526
+ const seatLimit = (await store.findSubscriptionsByReference(organizationId)).filter((subscription) => subscription.status === "active" || subscription.status === "trialing").reduce((maximum, subscription) => typeof subscription.seats === "number" ? Math.max(maximum ?? subscription.seats, subscription.seats) : maximum, void 0);
527
+ const members = await store.listMembers(organizationId);
528
+ if (seatLimit === void 0) return true;
529
+ if (members.length + seatsToAdd > seatLimit) throw new APIError("FORBIDDEN", { message: `Organization member limit reached. Used: ${members.length}, Max: ${seatLimit}` });
530
+ return true;
531
+ };
532
+ async function getOrganizationEntitlements(ctx, organizationId, options) {
533
+ const subscriptions = (await createBillingStore(ctx).findSubscriptionsByReference(organizationId)).filter((subscription) => subscription.status === "active" || subscription.status === "trialing");
534
+ const limits = {};
535
+ const features = /* @__PURE__ */ new Set();
536
+ for (const subscription of subscriptions) {
537
+ const plan = await getPlanByName(options, subscription.plan);
538
+ for (const [name, value] of Object.entries(plan?.limits ?? {})) if (typeof value === "number" && Number.isFinite(value)) limits[name] = Math.max(limits[name] ?? value, value);
539
+ for (const feature of plan?.features ?? []) features.add(feature);
540
+ }
541
+ return {
542
+ limits,
543
+ features: [...features]
544
+ };
545
+ }
546
+ const checkTeamLimit = async (ctx, organizationId, maxTeams) => {
547
+ if ((await createBillingStore(ctx).listTeams(organizationId)).length >= maxTeams) throw new APIError("FORBIDDEN", { message: `Organization team limit reached. Max teams: ${maxTeams}` });
548
+ return true;
549
+ };
550
+ //#endregion
551
+ //#region src/subscription-lifecycle.ts
552
+ async function scheduleSubscriptionLifecycleChange(ctx, input) {
553
+ const groupId = normalizeSubscriptionGroup(input.plan?.group);
554
+ if (input.plan !== void 0 && input.scheduleAtPeriodEnd === true) {
555
+ const existingSub = input.subscriptionId === void 0 ? await getOrganizationSubscription(ctx, input.referenceId, groupId) : await createBillingStore(ctx).findSubscriptionById(input.subscriptionId);
556
+ if (existingSub?.status === "active") {
557
+ await ctx.context.adapter.update({
558
+ model: "subscription",
559
+ where: [{
560
+ field: "id",
561
+ value: existingSub.id
562
+ }],
563
+ update: {
564
+ pendingPlan: input.plan.name,
565
+ updatedAt: /* @__PURE__ */ new Date()
566
+ }
567
+ });
568
+ return {
569
+ kind: "scheduled",
570
+ status: "success",
571
+ message: "Plan change scheduled at period end.",
572
+ scheduled: true
573
+ };
574
+ }
575
+ }
576
+ if (input.cancelAtPeriodEnd === true) {
577
+ const existingSub = input.subscriptionId === void 0 ? await getOrganizationSubscription(ctx, input.referenceId, input.plan === void 0 ? void 0 : groupId) : await createBillingStore(ctx).findSubscriptionById(input.subscriptionId);
578
+ if (existingSub?.status === "active") {
579
+ await ctx.context.adapter.update({
580
+ model: "subscription",
581
+ where: [{
582
+ field: "id",
583
+ value: existingSub.id
584
+ }],
585
+ update: {
586
+ cancelAtPeriodEnd: true,
587
+ cancelAt: existingSub.periodEnd ?? null,
588
+ canceledAt: /* @__PURE__ */ new Date(),
589
+ updatedAt: /* @__PURE__ */ new Date()
590
+ }
591
+ });
592
+ return {
593
+ kind: "scheduled",
594
+ status: "success",
595
+ message: "Subscription cancellation scheduled at period end.",
596
+ scheduled: true
597
+ };
598
+ }
599
+ }
600
+ return null;
601
+ }
602
+ async function resolveTrialLifecycle(ctx, input) {
603
+ const requestedDays = input.plan?.freeTrial?.days !== void 0 && input.plan.freeTrial.days > 0 ? input.plan.freeTrial.days : 0;
604
+ const requested = requestedDays > 0;
605
+ if (!requested) return {
606
+ requestedDays,
607
+ requested: false,
608
+ granted: false
609
+ };
610
+ if ((await ctx.context.adapter.findMany({
611
+ model: "subscription",
612
+ where: [{
613
+ field: "referenceId",
614
+ value: input.referenceId
615
+ }]
616
+ }))?.some((subscription) => subscription.trialStart !== void 0 && subscription.trialStart !== null || subscription.trialEnd !== void 0 && subscription.trialEnd !== null || subscription.status === "trialing") === true) return {
617
+ requestedDays,
618
+ requested,
619
+ granted: false,
620
+ deniedReason: "already_used"
621
+ };
622
+ const trialStart = /* @__PURE__ */ new Date();
623
+ const trialEnd = /* @__PURE__ */ new Date();
624
+ trialEnd.setDate(trialEnd.getDate() + requestedDays);
625
+ return {
626
+ trialStart,
627
+ trialEnd,
628
+ requestedDays,
629
+ requested,
630
+ granted: true
631
+ };
632
+ }
633
+ async function resolveCheckoutTargetEmail(ctx, options, input) {
634
+ const targetEmail = input.email ?? input.user.email;
635
+ if (options.organization?.enabled !== true || input.referenceId === input.user.id || input.referenceId === "") return targetEmail;
636
+ const org = await ctx.context.adapter.findOne({
637
+ model: "organization",
638
+ where: [{
639
+ field: "id",
640
+ value: input.referenceId
641
+ }]
642
+ });
643
+ if (org === void 0 || org === null) return targetEmail;
644
+ const orgWithEmail = org;
645
+ if (orgWithEmail.email !== void 0 && orgWithEmail.email !== null && orgWithEmail.email !== "") return orgWithEmail.email;
646
+ const ownerMember = await ctx.context.adapter.findOne({
647
+ model: "member",
648
+ where: [{
649
+ field: "organizationId",
650
+ value: input.referenceId
651
+ }, {
652
+ field: "role",
653
+ value: "owner"
654
+ }]
655
+ });
656
+ if (ownerMember === void 0 || ownerMember === null) return targetEmail;
657
+ const ownerUser = await ctx.context.adapter.findOne({
658
+ model: "user",
659
+ where: [{
660
+ field: "id",
661
+ value: ownerMember.userId
662
+ }]
663
+ });
664
+ return ownerUser?.email !== void 0 && ownerUser.email !== "" ? ownerUser.email : targetEmail;
665
+ }
666
+ async function handleProratedUpgrade(ctx, options, input) {
667
+ const store = createBillingStore(ctx);
668
+ const existingSub = input.subscriptionId === void 0 ? await store.findCurrentSubscription(input.referenceId, normalizeSubscriptionGroup(input.plan.group)) : await store.findSubscriptionById(input.subscriptionId);
669
+ if (existingSub?.status !== "active" || existingSub.paystackSubscriptionCode === void 0 || existingSub.paystackSubscriptionCode === null || existingSub.paystackSubscriptionCode === "" || existingSub.periodEnd === void 0 || existingSub.periodEnd === null || existingSub.periodStart === void 0 || existingSub.periodStart === null) return null;
670
+ const now = /* @__PURE__ */ new Date();
671
+ const periodEnd = new Date(existingSub.periodEnd);
672
+ const periodStart = new Date(existingSub.periodStart);
673
+ const totalDays = Math.max(1, Math.ceil((periodEnd.getTime() - periodStart.getTime()) / (1e3 * 60 * 60 * 24)));
674
+ const remainingDays = Math.max(0, Math.ceil((periodEnd.getTime() - now.getTime()) / (1e3 * 60 * 60 * 24)));
675
+ let oldAmount = 0;
676
+ if (existingSub.plan !== "") {
677
+ const oldPlan = await getPlanByName(options, existingSub.plan) ?? await store.findPlanByName(existingSub.plan);
678
+ if (oldPlan !== void 0 && oldPlan !== null) oldAmount = calculatePlanAmount(oldPlan, existingSub.seats);
679
+ }
680
+ let membersCount = 1;
681
+ let newSeatCount;
682
+ let newAmount;
683
+ try {
684
+ assertLocallyManagedSubscription(existingSub, "plan or seat changes");
685
+ if (getPlanSeatAmount(input.plan) !== void 0) {
686
+ const members = await store.listMembers(input.referenceId);
687
+ membersCount = members.length > 0 ? members.length : 1;
688
+ }
689
+ newSeatCount = input.quantity ?? existingSub.seats ?? membersCount;
690
+ newAmount = calculatePlanAmount(input.plan, newSeatCount);
691
+ } catch (error) {
692
+ throw new APIError("BAD_REQUEST", { message: error instanceof Error ? error.message : "Invalid seat configuration for plan." });
693
+ }
694
+ const costDifference = newAmount - oldAmount;
695
+ const serializedProrationMetadata = stringifyPaystackMetadata(createProrationMetadata({
696
+ subscriptionId: existingSub.id,
697
+ referenceId: input.referenceId,
698
+ newPlan: input.plan.name.toLowerCase(),
699
+ oldPlan: existingSub.plan,
700
+ newSeatCount,
701
+ remainingDays
702
+ }));
703
+ let completedProrationReference;
704
+ if (costDifference > 0 && remainingDays > 0) {
705
+ const proratedAmount = Math.round(costDifference / totalDays * remainingDays);
706
+ if (proratedAmount < 5e3) throw new APIError("BAD_REQUEST", {
707
+ message: "Prorated upgrade amount is below Paystack's minimum charge. Schedule the change for period end instead.",
708
+ status: 400
709
+ });
710
+ const paystack = createPaystackAdapter(options.paystackClient);
711
+ if (existingSub.paystackAuthorizationCode !== void 0 && existingSub.paystackAuthorizationCode !== null && existingSub.paystackAuthorizationCode !== "") {
712
+ const sdkRes = await paystack.chargeAuthorization({
713
+ email: input.targetEmail,
714
+ amount: proratedAmount,
715
+ authorization_code: existingSub.paystackAuthorizationCode,
716
+ reference: `upg_${existingSub.id}_${Date.now()}_${Math.random().toString(36).substring(7)}`,
717
+ metadata: serializedProrationMetadata
718
+ });
719
+ if (sdkRes?.status !== "success") throw new APIError("BAD_REQUEST", { message: "Failed to process prorated charge via saved authorization." });
720
+ await store.createTransaction({
721
+ reference: sdkRes.reference ?? "",
722
+ paystackId: sdkRes.id !== void 0 && sdkRes.id !== null ? String(sdkRes.id) : void 0,
723
+ referenceId: input.referenceId,
724
+ userId: input.userId,
725
+ amount: sdkRes.amount ?? proratedAmount,
726
+ currency: sdkRes.currency ?? input.finalCurrency,
727
+ status: "success",
728
+ plan: input.plan.name.toLowerCase(),
729
+ metadata: serializedProrationMetadata,
730
+ createdAt: /* @__PURE__ */ new Date(),
731
+ updatedAt: /* @__PURE__ */ new Date()
732
+ });
733
+ completedProrationReference = sdkRes.reference ?? void 0;
734
+ } else {
735
+ const initRes = await paystack.initializeTransaction({
736
+ email: input.targetEmail,
737
+ amount: proratedAmount,
738
+ currency: input.finalCurrency,
739
+ callback_url: input.callbackURL ?? void 0,
740
+ metadata: serializedProrationMetadata,
741
+ ...input.allowedSubscriptionChannels !== void 0 ? { channels: input.allowedSubscriptionChannels } : {}
742
+ });
743
+ await store.createTransaction({
744
+ reference: initRes?.reference ?? "",
745
+ referenceId: input.referenceId,
746
+ userId: input.userId,
747
+ amount: proratedAmount,
748
+ currency: input.finalCurrency,
749
+ status: "pending",
750
+ plan: input.plan.name.toLowerCase(),
751
+ metadata: serializedProrationMetadata,
752
+ createdAt: /* @__PURE__ */ new Date(),
753
+ updatedAt: /* @__PURE__ */ new Date()
754
+ });
755
+ return {
756
+ kind: "checkout",
757
+ url: initRes?.authorization_url,
758
+ reference: initRes?.reference,
759
+ accessCode: initRes?.access_code,
760
+ redirect: true
761
+ };
762
+ }
763
+ }
764
+ await store.updateSubscription(existingSub.id, {
765
+ plan: input.plan.name,
766
+ seats: newSeatCount,
767
+ ...completedProrationReference !== void 0 ? { paystackTransactionReference: completedProrationReference } : {},
768
+ updatedAt: /* @__PURE__ */ new Date()
769
+ });
770
+ return {
771
+ kind: "prorated",
772
+ status: "success",
773
+ message: "Subscription successfully upgraded with prorated charge.",
774
+ prorated: true
775
+ };
776
+ }
777
+ //#endregion
778
+ //#region src/reconciliation.ts
779
+ function getAllowedSubscriptionChannels$1(options) {
780
+ const channels = options.subscription?.allowedPaymentChannels;
781
+ return Array.isArray(channels) && channels.length > 0 ? channels : void 0;
782
+ }
783
+ function isAllowedSubscriptionChannel(channel, allowedChannels) {
784
+ if (allowedChannels === void 0) return true;
785
+ return channel !== void 0 && channel !== null && allowedChannels.includes(channel);
786
+ }
787
+ function createSummary() {
788
+ return {
789
+ transaction: {
790
+ found: false,
791
+ updated: false
792
+ },
793
+ subscription: {
794
+ found: false,
795
+ updated: false,
796
+ prorationApplied: false
797
+ },
798
+ customer: { saved: false },
799
+ product: { synced: false }
800
+ };
801
+ }
802
+ function getErrorMessage(error, fallback) {
803
+ return error instanceof Error && error.message !== "" ? error.message : fallback;
804
+ }
805
+ function createFailureResult(input) {
806
+ return {
807
+ ok: false,
808
+ source: input.source,
809
+ status: input.status,
810
+ reference: input.reference,
811
+ data: input.data,
812
+ error: input.error,
813
+ ...input.summary
814
+ };
815
+ }
816
+ function throwOrReturnFailure(input) {
817
+ if (input.throwOnError) throw new APIError(input.apiStatus, {
818
+ code: input.error.code,
819
+ message: input.error.message,
820
+ status: input.error.status
821
+ });
822
+ return createFailureResult(input);
823
+ }
824
+ function hasReferenceMismatch(input) {
825
+ return input.expectedReferenceId !== void 0 && input.expectedReferenceId !== "" && input.transactionReferenceId !== void 0 && input.transactionReferenceId !== null && input.transactionReferenceId !== "" && input.expectedReferenceId !== input.transactionReferenceId;
826
+ }
827
+ function getNonEmptyString(value) {
828
+ return typeof value === "string" && value !== "" ? value : void 0;
829
+ }
830
+ async function reconcilePaystackTransaction(ctx, options, input) {
831
+ const source = input.source ?? "server";
832
+ const throwOnError = input.throwOnError === true;
833
+ const summary = createSummary();
834
+ const paystack = getPaystackOps(options.paystackClient);
835
+ let data;
836
+ try {
837
+ data = unwrapSdkResult(await paystack?.transaction?.verify(input.reference));
838
+ } catch (error) {
839
+ ctx.context.logger.error("Failed to verify Paystack transaction", error);
840
+ return throwOrReturnFailure({
841
+ throwOnError,
842
+ apiStatus: "BAD_REQUEST",
843
+ source,
844
+ status: "error",
845
+ reference: input.reference,
846
+ data: null,
847
+ summary,
848
+ error: {
849
+ code: "FAILED_TO_VERIFY_TRANSACTION",
850
+ message: getErrorMessage(error, "Failed to verify transaction"),
851
+ status: 400
852
+ }
853
+ });
854
+ }
855
+ if (data === void 0 || data === null) return throwOrReturnFailure({
856
+ throwOnError,
857
+ apiStatus: "BAD_REQUEST",
858
+ source,
859
+ status: "error",
860
+ reference: input.reference,
861
+ data: null,
862
+ summary,
863
+ error: {
864
+ code: "FAILED_TO_VERIFY_TRANSACTION",
865
+ message: "Failed to fetch transaction data from Paystack.",
866
+ status: 400
867
+ }
868
+ });
869
+ const status = data.status ?? "failed";
870
+ const reference = data.reference ?? input.reference;
871
+ const paystackIdRaw = data.id;
872
+ const paystackId = paystackIdRaw !== void 0 && paystackIdRaw !== null ? String(paystackIdRaw) : void 0;
873
+ const authorizationCode = data.authorization?.authorization_code;
874
+ const store = createBillingStore(ctx);
875
+ const txRecord = await store.findTransactionByReference(reference);
876
+ summary.transaction.found = txRecord !== null;
877
+ summary.transaction.previousStatus = txRecord?.status;
878
+ if (hasReferenceMismatch({
879
+ expectedReferenceId: input.referenceId,
880
+ transactionReferenceId: txRecord?.referenceId
881
+ })) return throwOrReturnFailure({
882
+ throwOnError,
883
+ apiStatus: "UNAUTHORIZED",
884
+ source,
885
+ status,
886
+ reference,
887
+ data,
888
+ summary,
889
+ error: {
890
+ code: "REFERENCE_ID_MISMATCH",
891
+ message: "Transaction reference does not belong to the expected billing reference.",
892
+ status: 401
893
+ }
894
+ });
895
+ const referenceId = input.referenceId ?? getNonEmptyString(txRecord?.referenceId) ?? getNonEmptyString(input.actor?.user.id);
896
+ summary.transaction.referenceId = referenceId;
897
+ if (input.actor !== void 0 && referenceId !== void 0 && referenceId !== input.actor.user.id) try {
898
+ await authorizeBillingReference(ctx, options, {
899
+ user: input.actor.user,
900
+ session: input.actor.session,
901
+ referenceId,
902
+ action: "verify-transaction"
903
+ });
904
+ } catch (error) {
905
+ return throwOrReturnFailure({
906
+ throwOnError,
907
+ apiStatus: "UNAUTHORIZED",
908
+ source,
909
+ status,
910
+ reference,
911
+ data,
912
+ summary,
913
+ error: {
914
+ code: "UNAUTHORIZED",
915
+ message: getErrorMessage(error, "Not authorized to reconcile this transaction."),
916
+ status: 401
917
+ }
918
+ });
919
+ }
920
+ const transactionUpdate = {
921
+ status,
922
+ paystackId,
923
+ amount: data.amount,
924
+ currency: data.currency,
925
+ updatedAt: /* @__PURE__ */ new Date()
926
+ };
927
+ const updatedTransaction = await store.updateTransactionByReference(reference, transactionUpdate);
928
+ summary.transaction.updated = updatedTransaction !== null;
929
+ summary.transaction.status = status;
930
+ if (status !== "success") return {
931
+ ok: true,
932
+ source,
933
+ status,
934
+ reference,
935
+ data,
936
+ ...summary
937
+ };
938
+ const allowedSubscriptionChannels = getAllowedSubscriptionChannels$1(options);
939
+ if ((txRecord?.plan !== void 0 && txRecord.plan !== null && txRecord.plan !== "" || Boolean(data.plan)) && isAllowedSubscriptionChannel(data.channel ?? void 0, allowedSubscriptionChannels) === false) {
940
+ await store.updateTransactionByReference(reference, {
941
+ ...transactionUpdate,
942
+ status: "failed"
943
+ });
944
+ summary.transaction.updated = true;
945
+ summary.transaction.status = "failed";
946
+ return throwOrReturnFailure({
947
+ throwOnError,
948
+ apiStatus: "BAD_REQUEST",
949
+ source,
950
+ status: "failed",
951
+ reference,
952
+ data,
953
+ summary,
954
+ error: {
955
+ code: "SUBSCRIPTION_PAYMENT_CHANNEL_NOT_ALLOWED",
956
+ message: `This subscription requires one of: ${allowedSubscriptionChannels?.join(", ") ?? "allowed channels"}.`,
957
+ status: 400
958
+ }
959
+ });
960
+ }
961
+ const paystackCustomerCodeFromPaystack = data.customer?.customer_code;
962
+ if (paystackCustomerCodeFromPaystack !== void 0 && paystackCustomerCodeFromPaystack !== null && paystackCustomerCodeFromPaystack !== "" && referenceId !== void 0 && referenceId !== "") {
963
+ let isOrganization = options.organization?.enabled === true && typeof referenceId === "string" && referenceId.startsWith("org_");
964
+ if (isOrganization === false && options.organization?.enabled === true) isOrganization = await store.findOrganization(referenceId) !== null;
965
+ await store.saveCustomerCode(referenceId, paystackCustomerCodeFromPaystack, isOrganization);
966
+ summary.customer.saved = true;
967
+ summary.customer.referenceId = referenceId;
968
+ summary.customer.customerCode = paystackCustomerCodeFromPaystack;
969
+ summary.customer.model = isOrganization ? "organization" : "user";
970
+ }
971
+ const transaction = updatedTransaction ?? await store.findTransactionByReference(reference);
972
+ if (transaction !== void 0 && transaction !== null && transaction.product !== void 0 && transaction.product !== null && transaction.product !== "" && options.paystackClient !== void 0 && options.paystackClient !== null) {
973
+ await syncProductQuantityFromPaystack(ctx, transaction.product, options.paystackClient);
974
+ summary.product.synced = true;
975
+ summary.product.name = transaction.product;
976
+ }
977
+ if (options.subscription?.enabled !== true) return {
978
+ ok: true,
979
+ source,
980
+ status,
981
+ reference,
982
+ data,
983
+ ...summary
984
+ };
985
+ const metadataObj = parsePaystackMetadata(data.metadata);
986
+ const isTrial = getMetadataBoolean(metadataObj, "isTrial");
987
+ const trialEnd = getMetadataString(metadataObj, "trialEnd");
988
+ const targetPlan = getMetadataString(metadataObj, "plan");
989
+ if (metadataObj.type === "proration") {
990
+ const subscriptionId = getMetadataString(metadataObj, "subscriptionId");
991
+ const newPlan = getMetadataString(metadataObj, "newPlan");
992
+ const newSeatCount = getMetadataNumber(metadataObj, "newSeatCount");
993
+ if (subscriptionId !== void 0 && subscriptionId !== "" && newPlan !== void 0 && newPlan !== "") {
994
+ const updatedSubscription = await store.updateSubscription(subscriptionId, {
995
+ plan: newPlan,
996
+ ...typeof newSeatCount === "number" ? { seats: newSeatCount } : {},
997
+ paystackTransactionReference: reference,
998
+ ...authorizationCode !== void 0 && authorizationCode !== null ? { paystackAuthorizationCode: authorizationCode } : {},
999
+ updatedAt: /* @__PURE__ */ new Date()
1000
+ });
1001
+ summary.subscription.found = updatedSubscription !== null;
1002
+ summary.subscription.updated = updatedSubscription !== null;
1003
+ summary.subscription.id = updatedSubscription?.id ?? subscriptionId;
1004
+ summary.subscription.status = updatedSubscription?.status;
1005
+ summary.subscription.prorationApplied = updatedSubscription !== null;
1006
+ }
1007
+ return {
1008
+ ok: true,
1009
+ source,
1010
+ status,
1011
+ reference,
1012
+ data,
1013
+ ...summary
1014
+ };
1015
+ }
1016
+ let paystackSubscriptionCode;
1017
+ const targetSub = (await store.findSubscriptionsByTransactionReference(reference)).find((subscription) => referenceId === void 0 || referenceId === "" || subscription.referenceId === referenceId);
1018
+ summary.subscription.found = targetSub !== void 0;
1019
+ summary.subscription.id = targetSub?.id;
1020
+ summary.subscription.status = targetSub?.status;
1021
+ if (isTrial && targetPlan !== void 0 && trialEnd !== void 0) {
1022
+ const email = data.customer?.email;
1023
+ const planConfig = (await getPlans(options.subscription)).find((plan) => plan.name.toLowerCase() === targetPlan.toLowerCase());
1024
+ if (planConfig !== void 0 && planConfig !== null && (planConfig.planCode === void 0 || planConfig.planCode === null || planConfig.planCode === "")) paystackSubscriptionCode = `LOC_${reference}`;
1025
+ else if (targetSub?.paystackSubscriptionCode !== void 0 && targetSub.paystackSubscriptionCode !== null && targetSub.paystackSubscriptionCode !== "") paystackSubscriptionCode = targetSub.paystackSubscriptionCode;
1026
+ else if (authorizationCode !== void 0 && authorizationCode !== null && email !== void 0 && email !== null && email !== "" && planConfig?.planCode !== void 0 && planConfig.planCode !== null && planConfig.planCode !== "") paystackSubscriptionCode = unwrapSdkResult(await paystack?.subscription?.create({ body: {
1027
+ customer: email,
1028
+ plan: planConfig.planCode,
1029
+ authorization: authorizationCode,
1030
+ start_date: trialEnd
1031
+ } }))?.subscription_code;
1032
+ } else if (isTrial === false) {
1033
+ const planCodeFromPaystack = data.plan?.plan_code;
1034
+ if (planCodeFromPaystack === void 0 || planCodeFromPaystack === null || planCodeFromPaystack === "") paystackSubscriptionCode = `LOC_${reference}`;
1035
+ else paystackSubscriptionCode = data.subscription?.subscription_code ?? void 0;
1036
+ }
1037
+ let updatedSubscription = null;
1038
+ if (targetSub !== void 0 && targetSub !== null) {
1039
+ const resolvedPlan = (await getPlans(options.subscription)).find((candidate) => candidate.name.toLowerCase() === targetSub.plan.toLowerCase());
1040
+ updatedSubscription = await store.updateSubscription(targetSub.id, {
1041
+ status: isTrial ? "trialing" : "active",
1042
+ billingInterval: resolvedPlan?.interval ?? targetSub.billingInterval ?? null,
1043
+ periodStart: /* @__PURE__ */ new Date(),
1044
+ updatedAt: /* @__PURE__ */ new Date(),
1045
+ ...isTrial && trialEnd !== void 0 ? {
1046
+ trialStart: /* @__PURE__ */ new Date(),
1047
+ trialEnd: new Date(trialEnd),
1048
+ periodEnd: new Date(trialEnd)
1049
+ } : {},
1050
+ ...paystackSubscriptionCode !== void 0 ? { paystackSubscriptionCode } : {},
1051
+ ...authorizationCode !== void 0 && authorizationCode !== null ? { paystackAuthorizationCode: authorizationCode } : {}
1052
+ });
1053
+ summary.subscription.updated = updatedSubscription !== null;
1054
+ summary.subscription.id = updatedSubscription?.id ?? targetSub.id;
1055
+ summary.subscription.status = updatedSubscription?.status ?? targetSub.status;
1056
+ if (updatedSubscription !== null && (updatedSubscription.status === "active" || updatedSubscription.status === "trialing")) await store.retireCompetingSubscriptions(updatedSubscription.referenceId, updatedSubscription.groupId ?? null, updatedSubscription.id);
1057
+ }
1058
+ if (updatedSubscription !== void 0 && updatedSubscription !== null) {
1059
+ const plan = (await getPlans(options.subscription)).find((candidate) => candidate.name.toLowerCase() === updatedSubscription.plan.toLowerCase());
1060
+ if (plan !== void 0) {
1061
+ const callbackData = {
1062
+ event: data,
1063
+ subscription: updatedSubscription,
1064
+ plan
1065
+ };
1066
+ for (const callback of [options.subscription?.onSubscriptionComplete, options.subscription?.onSubscriptionUpdate]) try {
1067
+ await callback?.(callbackData, ctx);
1068
+ } catch (error) {
1069
+ ctx.context.logger.error("Paystack subscription callback failed", error);
1070
+ }
1071
+ if (targetSub?.status === "trialing" && updatedSubscription.status === "active") try {
1072
+ await plan.freeTrial?.onTrialEnd?.(updatedSubscription);
1073
+ } catch (error) {
1074
+ ctx.context.logger.error("Paystack trial end callback failed", error);
1075
+ }
1076
+ }
1077
+ }
1078
+ return {
1079
+ ok: true,
1080
+ source,
1081
+ status,
1082
+ reference,
1083
+ data,
1084
+ ...summary
1085
+ };
1086
+ }
1087
+ //#endregion
1088
+ //#region src/route-modules/checkout.ts
1089
+ const initializeTransactionBodySchema = z.object({
1090
+ plan: z.string().optional(),
1091
+ product: z.string().optional(),
1092
+ amount: z.number().int().positive().optional(),
1093
+ currency: z.string().optional(),
1094
+ email: z.string().optional(),
1095
+ metadata: z.record(z.string(), z.unknown()).optional(),
1096
+ referenceId: z.string().optional(),
1097
+ subscriptionId: z.string().optional(),
1098
+ callbackURL: z.string().optional(),
1099
+ quantity: z.number().int().positive().optional(),
1100
+ scheduleAtPeriodEnd: z.boolean().optional(),
1101
+ cancelAtPeriodEnd: z.boolean().optional(),
1102
+ prorateAndCharge: z.boolean().optional()
1103
+ });
1104
+ //#endregion
1105
+ //#region src/route-modules/catalog.ts
1106
+ async function listStoredProducts(ctx) {
1107
+ return createBillingStore(ctx).listProducts();
1108
+ }
1109
+ async function listStoredPlans(ctx) {
1110
+ return createBillingStore(ctx).listPlans();
1111
+ }
1112
+ async function getConfiguredCatalog(options) {
1113
+ return {
1114
+ plans: options.subscription?.enabled === true ? await getPlans(options.subscription) : [],
1115
+ products: await getProducts(options.products)
1116
+ };
1117
+ }
1118
+ //#endregion
1119
+ //#region src/route-modules/subscriptions.ts
1120
+ const enableDisableBodySchema = z.object({
1121
+ referenceId: z.string().optional(),
1122
+ subscriptionCode: z.string(),
1123
+ emailToken: z.string().optional(),
1124
+ atPeriodEnd: z.boolean().optional()
1125
+ });
1126
+ function decodeBase64UrlToString(value) {
1127
+ const normalized = value.replace(/-/g, "+").replace(/_/g, "/");
1128
+ const padded = normalized + "===".slice((normalized.length + 3) % 4);
1129
+ const binaryString = atob(padded);
1130
+ const bytes = new Uint8Array(binaryString.length);
1131
+ for (let i = 0; i < binaryString.length; i++) bytes[i] = binaryString.charCodeAt(i);
1132
+ return new TextDecoder().decode(bytes);
1133
+ }
1134
+ function tryGetEmailTokenFromSubscriptionManageLink(link) {
1135
+ try {
1136
+ const subscriptionToken = new URL(link).searchParams.get("subscription_token");
1137
+ if (subscriptionToken === void 0 || subscriptionToken === null || subscriptionToken === "") return void 0;
1138
+ const parts = subscriptionToken.split(".");
1139
+ if (parts.length < 2) return void 0;
1140
+ const payloadJson = decodeBase64UrlToString(parts[1] ?? "");
1141
+ const payload = JSON.parse(payloadJson);
1142
+ return typeof payload.email_token === "string" ? payload.email_token : void 0;
1143
+ } catch {
1144
+ return;
1145
+ }
1146
+ }
1147
+ //#endregion
1148
+ //#region src/route-modules/webhook.ts
1149
+ function getWebhookRequest(ctx) {
1150
+ return ctx.requestClone ?? ctx.request;
1151
+ }
1152
+ function getWebhookHeaders(ctx) {
1153
+ return ctx.headers ?? ctx.request?.headers;
1154
+ }
1155
+ function getWebhookClientIP(ctx, headers) {
1156
+ return headers?.get("x-forwarded-for")?.split(",")[0]?.trim() ?? headers?.get("x-real-ip") ?? ctx.request.ip;
1157
+ }
1158
+ //#endregion
1159
+ //#region src/route-modules/shared.ts
1160
+ const PAYSTACK_ERROR_CODES = defineErrorCodes({
1161
+ SUBSCRIPTION_NOT_FOUND: "Subscription not found",
1162
+ SUBSCRIPTION_PLAN_NOT_FOUND: "Subscription plan not found",
1163
+ UNABLE_TO_CREATE_CUSTOMER: "Unable to create customer",
1164
+ FAILED_TO_INITIALIZE_TRANSACTION: "Failed to initialize transaction",
1165
+ FAILED_TO_VERIFY_TRANSACTION: "Failed to verify transaction",
1166
+ FAILED_TO_DISABLE_SUBSCRIPTION: "Failed to disable subscription",
1167
+ FAILED_TO_ENABLE_SUBSCRIPTION: "Failed to enable subscription",
1168
+ EMAIL_VERIFICATION_REQUIRED: "Email verification is required before you can subscribe to a plan",
1169
+ SUBSCRIPTION_PAYMENT_CHANNEL_NOT_ALLOWED: "This subscription only supports specific payment channels"
1170
+ });
1171
+ function getAllowedSubscriptionChannels(options) {
1172
+ const channels = options.subscription?.allowedPaymentChannels;
1173
+ return Array.isArray(channels) && channels.length > 0 ? channels : void 0;
1174
+ }
1175
+ async function hmacSha512Hex(secret, message) {
1176
+ const encoder = new TextEncoder();
1177
+ const keyData = encoder.encode(secret);
1178
+ const msgData = encoder.encode(message);
1179
+ const crypto = globalThis.crypto;
1180
+ if (crypto !== void 0 && crypto !== null && "subtle" in crypto) {
1181
+ const subtle = crypto.subtle;
1182
+ const key = await subtle.importKey("raw", keyData, {
1183
+ name: "HMAC",
1184
+ hash: "SHA-512"
1185
+ }, false, ["sign"]);
1186
+ const signature = await subtle.sign("HMAC", key, msgData);
1187
+ return Array.from(new Uint8Array(signature)).map((b) => b.toString(16).padStart(2, "0")).join("");
1188
+ }
1189
+ const { createHmac } = await import("node:crypto");
1190
+ return createHmac("sha512", secret).update(message).digest("hex");
1191
+ }
1192
+ //#endregion
1193
+ //#region src/routes.ts
1194
+ const paystackWebhook = (options, path = "/webhook") => {
1195
+ return createAuthEndpoint(path, {
1196
+ method: "POST",
1197
+ metadata: {
1198
+ ...HIDE_METADATA,
1199
+ openapi: { operationId: "handlePaystackWebhook" }
1200
+ },
1201
+ cloneRequest: true,
1202
+ disableBody: true
1203
+ }, async (ctx) => {
1204
+ const request = getWebhookRequest(ctx);
1205
+ if (request === void 0 || request === null) throw new APIError("BAD_REQUEST", { message: "Request object is missing from context" });
1206
+ const payload = await request.text();
1207
+ const headers = getWebhookHeaders(ctx);
1208
+ const signature = headers?.get("x-paystack-signature");
1209
+ if (options.webhook?.verifyIP === true) {
1210
+ const trustedIPs = options.webhook.trustedIPs ?? [
1211
+ "52.31.139.75",
1212
+ "52.49.173.169",
1213
+ "52.214.14.220"
1214
+ ];
1215
+ const clientIP = getWebhookClientIP(ctx, headers);
1216
+ if (clientIP !== void 0 && clientIP !== null && trustedIPs.includes(clientIP) === false) throw new APIError("UNAUTHORIZED", {
1217
+ message: `Forbidden IP: ${clientIP}`,
1218
+ status: 401
1219
+ });
1220
+ }
1221
+ if (signature === void 0 || signature === null || signature === "") throw new APIError("UNAUTHORIZED", {
1222
+ message: "Missing x-paystack-signature header",
1223
+ status: 401
1224
+ });
1225
+ if (await hmacSha512Hex(options.secretKey, payload) !== signature) throw new APIError("UNAUTHORIZED", {
1226
+ message: "Invalid Paystack webhook signature",
1227
+ status: 401
1228
+ });
1229
+ const event = JSON.parse(payload);
1230
+ const eventName = event.event;
1231
+ const data = event.data;
1232
+ if (eventName === "charge.success") {
1233
+ const reference = data?.reference;
1234
+ const paystackIdRaw = data?.id;
1235
+ const paystackId = paystackIdRaw !== void 0 && paystackIdRaw !== null ? String(paystackIdRaw) : void 0;
1236
+ if (reference !== void 0 && reference !== null && reference !== "") {
1237
+ try {
1238
+ await ctx.context.adapter.update({
1239
+ model: "paystackTransaction",
1240
+ update: {
1241
+ status: "success",
1242
+ paystackId,
1243
+ updatedAt: /* @__PURE__ */ new Date()
1244
+ },
1245
+ where: [{
1246
+ field: "reference",
1247
+ value: reference
1248
+ }]
1249
+ });
1250
+ } catch (e) {
1251
+ ctx.context.logger.warn("Failed to update transaction status for charge.success", e);
1252
+ }
1253
+ try {
1254
+ const transaction = await ctx.context.adapter.findOne({
1255
+ model: "paystackTransaction",
1256
+ where: [{
1257
+ field: "reference",
1258
+ value: reference
1259
+ }]
1260
+ });
1261
+ if (transaction !== void 0 && transaction !== null && transaction.product !== void 0 && transaction.product !== null && transaction.product !== "") {
1262
+ if (options.paystackClient !== void 0 && options.paystackClient !== null) await syncProductQuantityFromPaystack(ctx, transaction.product, options.paystackClient);
1263
+ }
1264
+ } catch (e) {
1265
+ ctx.context.logger.warn("Failed to sync product quantity", e);
1266
+ }
1267
+ }
1268
+ }
1269
+ if (eventName === "charge.failure") {
1270
+ const reference = data?.reference;
1271
+ if (reference !== void 0 && reference !== null && reference !== "") try {
1272
+ await ctx.context.adapter.update({
1273
+ model: "paystackTransaction",
1274
+ update: {
1275
+ status: "failed",
1276
+ updatedAt: /* @__PURE__ */ new Date()
1277
+ },
1278
+ where: [{
1279
+ field: "reference",
1280
+ value: reference
1281
+ }]
1282
+ });
1283
+ } catch (e) {
1284
+ ctx.context.logger.warn("Failed to update transaction status for charge.failure", e);
1285
+ }
1286
+ }
1287
+ if (options.subscription?.enabled === true) try {
1288
+ if (eventName === "subscription.create") {
1289
+ const subscriptionData = data;
1290
+ const subscriptionCode = subscriptionData.subscription_code ?? "";
1291
+ const customerCode = subscriptionData.customer?.customer_code;
1292
+ const planCode = subscriptionData.plan?.plan_code;
1293
+ const metadataObj = parsePaystackMetadata(subscriptionData.metadata);
1294
+ const referenceIdFromMetadata = typeof metadataObj.referenceId === "string" ? metadataObj.referenceId : void 0;
1295
+ let planNameFromMetadata = typeof metadataObj.plan === "string" ? metadataObj.plan : void 0;
1296
+ if (typeof planNameFromMetadata === "string") planNameFromMetadata = planNameFromMetadata.toLowerCase();
1297
+ const plans = await getPlans(options.subscription);
1298
+ const planFromCode = planCode !== void 0 && planCode !== null && planCode !== "" ? plans.find((p) => p.planCode === planCode) : void 0;
1299
+ const groupIdFromMetadata = typeof metadataObj.groupId === "string" ? normalizeSubscriptionGroup(metadataObj.groupId) : normalizeSubscriptionGroup(planFromCode?.group);
1300
+ const planPart = planFromCode?.name ?? planNameFromMetadata;
1301
+ const planName = planPart !== void 0 && planPart !== null && planPart !== "" ? planPart.toLowerCase() : void 0;
1302
+ if (subscriptionCode !== void 0 && subscriptionCode !== null && subscriptionCode !== "") {
1303
+ const where = [];
1304
+ if (referenceIdFromMetadata !== void 0 && referenceIdFromMetadata !== null && referenceIdFromMetadata !== "") where.push({
1305
+ field: "referenceId",
1306
+ value: referenceIdFromMetadata
1307
+ });
1308
+ else if (customerCode !== void 0 && customerCode !== null && customerCode !== "") where.push({
1309
+ field: "paystackCustomerCode",
1310
+ value: customerCode
1311
+ });
1312
+ if (planName !== void 0 && planName !== null && planName !== "") where.push({
1313
+ field: "plan",
1314
+ value: planName
1315
+ });
1316
+ if (where.length > 0) {
1317
+ const subscription = (await ctx.context.adapter.findMany({
1318
+ model: "subscription",
1319
+ where
1320
+ }))?.find((candidate) => groupIdFromMetadata === null ? candidate.groupId === void 0 || candidate.groupId === null || candidate.groupId === "" : candidate.groupId === groupIdFromMetadata);
1321
+ if (subscription !== void 0 && subscription !== null) {
1322
+ const plan = planFromCode ?? (planName !== void 0 && planName !== null && planName !== "" ? await getPlanByName(options, planName) : void 0);
1323
+ const now = /* @__PURE__ */ new Date();
1324
+ const persistedSubscription = {
1325
+ ...subscription,
1326
+ paystackSubscriptionCode: subscriptionCode,
1327
+ status: "active",
1328
+ billingInterval: plan?.interval ?? subscription.billingInterval ?? null,
1329
+ periodEnd: subscriptionData.next_payment_date !== void 0 && subscriptionData.next_payment_date !== null ? new Date(subscriptionData.next_payment_date) : subscription.periodEnd,
1330
+ updatedAt: now
1331
+ };
1332
+ await ctx.context.adapter.update({
1333
+ model: "subscription",
1334
+ update: {
1335
+ paystackSubscriptionCode: persistedSubscription.paystackSubscriptionCode,
1336
+ status: persistedSubscription.status,
1337
+ billingInterval: persistedSubscription.billingInterval,
1338
+ periodEnd: persistedSubscription.periodEnd,
1339
+ updatedAt: persistedSubscription.updatedAt
1340
+ },
1341
+ where: [{
1342
+ field: "id",
1343
+ value: subscription.id
1344
+ }]
1345
+ });
1346
+ await createBillingStore(ctx).retireCompetingSubscriptions(subscription.referenceId, subscription.groupId ?? null, subscription.id);
1347
+ if (plan !== void 0 && plan !== null) {
1348
+ const callbackData = {
1349
+ event,
1350
+ subscription: persistedSubscription,
1351
+ plan
1352
+ };
1353
+ for (const callback of [
1354
+ options.subscription.onSubscriptionComplete,
1355
+ options.subscription.onSubscriptionCreated,
1356
+ options.subscription.onSubscriptionUpdate
1357
+ ]) try {
1358
+ await callback?.(callbackData, ctx);
1359
+ } catch (error) {
1360
+ ctx.context.logger.error("Paystack subscription callback failed", error);
1361
+ }
1362
+ if (subscription.status === "trialing") try {
1363
+ await plan.freeTrial?.onTrialEnd?.(persistedSubscription);
1364
+ } catch (error) {
1365
+ ctx.context.logger.error("Paystack trial end callback failed", error);
1366
+ }
1367
+ }
1368
+ }
1369
+ }
1370
+ }
1371
+ }
1372
+ if (eventName === "subscription.disable" || eventName === "subscription.not_renew") {
1373
+ const subscriptionData = data;
1374
+ const subscriptionCode = subscriptionData.subscription_code ?? "";
1375
+ if (subscriptionCode !== "") {
1376
+ const existing = await ctx.context.adapter.findOne({
1377
+ model: "subscription",
1378
+ where: [{
1379
+ field: "paystackSubscriptionCode",
1380
+ value: subscriptionCode
1381
+ }]
1382
+ });
1383
+ let newStatus = "canceled";
1384
+ const nextPaymentDate = subscriptionData.next_payment_date;
1385
+ const periodEnd = nextPaymentDate !== void 0 && nextPaymentDate !== null && nextPaymentDate !== "" ? new Date(nextPaymentDate) : existing?.periodEnd !== void 0 && existing.periodEnd !== null ? new Date(existing.periodEnd) : void 0;
1386
+ if (periodEnd !== void 0 && periodEnd.getTime() > Date.now()) newStatus = "active";
1387
+ const now = /* @__PURE__ */ new Date();
1388
+ const persistedSubscription = existing === null || existing === void 0 ? void 0 : {
1389
+ ...existing,
1390
+ status: newStatus,
1391
+ cancelAtPeriodEnd: newStatus === "active",
1392
+ cancelAt: newStatus === "active" ? periodEnd ?? null : null,
1393
+ canceledAt: now,
1394
+ endedAt: newStatus === "canceled" ? now : null,
1395
+ ...periodEnd ? { periodEnd } : {},
1396
+ updatedAt: now
1397
+ };
1398
+ await ctx.context.adapter.update({
1399
+ model: "subscription",
1400
+ update: {
1401
+ status: newStatus,
1402
+ cancelAtPeriodEnd: newStatus === "active",
1403
+ cancelAt: newStatus === "active" ? periodEnd ?? null : null,
1404
+ canceledAt: now,
1405
+ endedAt: newStatus === "canceled" ? now : null,
1406
+ ...periodEnd ? { periodEnd } : {},
1407
+ updatedAt: now
1408
+ },
1409
+ where: [{
1410
+ field: "paystackSubscriptionCode",
1411
+ value: subscriptionCode
1412
+ }]
1413
+ });
1414
+ if (persistedSubscription !== void 0) {
1415
+ try {
1416
+ await options.subscription.onSubscriptionCancel?.({
1417
+ event,
1418
+ subscription: persistedSubscription
1419
+ }, ctx);
1420
+ } catch (error) {
1421
+ ctx.context.logger.error("Paystack subscription cancel callback failed", error);
1422
+ }
1423
+ const plan = await getPlanByName(options, persistedSubscription.plan);
1424
+ if (plan !== void 0 && plan !== null) {
1425
+ try {
1426
+ await options.subscription.onSubscriptionUpdate?.({
1427
+ event,
1428
+ subscription: persistedSubscription,
1429
+ plan
1430
+ }, ctx);
1431
+ } catch (error) {
1432
+ ctx.context.logger.error("Paystack subscription update callback failed", error);
1433
+ }
1434
+ if (existing?.status === "trialing" && newStatus === "canceled") try {
1435
+ await plan.freeTrial?.onTrialExpired?.(persistedSubscription);
1436
+ } catch (error) {
1437
+ ctx.context.logger.error("Paystack trial expiry callback failed", error);
1438
+ }
1439
+ }
1440
+ }
1441
+ }
1442
+ }
1443
+ if (eventName === "charge.success" || eventName === "invoice.update") {
1444
+ const subscriptionCodeRaw = (data?.subscription)?.subscription_code ?? data?.subscription_code;
1445
+ const subscriptionCode = subscriptionCodeRaw !== void 0 && subscriptionCodeRaw !== null && subscriptionCodeRaw !== "" ? subscriptionCodeRaw : void 0;
1446
+ if (subscriptionCode !== void 0) {
1447
+ const existingSub = await ctx.context.adapter.findOne({
1448
+ model: "subscription",
1449
+ where: [{
1450
+ field: "paystackSubscriptionCode",
1451
+ value: subscriptionCode
1452
+ }]
1453
+ });
1454
+ if (existingSub !== void 0 && existingSub !== null && existingSub.pendingPlan !== void 0 && existingSub.pendingPlan !== null && existingSub.pendingPlan !== "") await ctx.context.adapter.update({
1455
+ model: "subscription",
1456
+ update: {
1457
+ plan: existingSub.pendingPlan,
1458
+ pendingPlan: null,
1459
+ updatedAt: /* @__PURE__ */ new Date()
1460
+ },
1461
+ where: [{
1462
+ field: "id",
1463
+ value: existingSub.id
1464
+ }]
1465
+ });
1466
+ }
1467
+ }
1468
+ } catch (_e) {
1469
+ ctx.context.logger.error("Failed to sync Paystack webhook event", _e);
1470
+ }
1471
+ await options.onEvent?.(event);
1472
+ return ctx.json({ received: true });
1473
+ });
1474
+ };
1475
+ const initializeTransaction = (options, path = "/initialize-transaction") => {
1476
+ const subscriptionOptions = options.subscription;
1477
+ return createAuthEndpoint(path, {
1478
+ method: "POST",
1479
+ body: initializeTransactionBodySchema,
1480
+ use: subscriptionOptions?.enabled === true ? [
1481
+ sessionMiddleware,
1482
+ originCheck,
1483
+ referenceMiddleware(options, "initialize-transaction")
1484
+ ] : [sessionMiddleware, originCheck]
1485
+ }, async (ctx) => {
1486
+ const paystack = getPaystackOps(options.paystackClient);
1487
+ const { plan: planName, product: productName, amount: bodyAmount, currency, email, metadata: extraMetadata, callbackURL, quantity, scheduleAtPeriodEnd, cancelAtPeriodEnd, prorateAndCharge, subscriptionId } = ctx.body;
1488
+ if (callbackURL !== void 0 && callbackURL !== null && callbackURL !== "") {
1489
+ const checkTrusted = () => {
1490
+ try {
1491
+ if (callbackURL?.startsWith("/") === true) return true;
1492
+ const baseUrl = ctx.context?.baseURL ?? ctx.request?.url ?? "";
1493
+ if (baseUrl === "") return false;
1494
+ const baseOrigin = new URL(baseUrl).origin;
1495
+ return new URL(callbackURL).origin === baseOrigin;
1496
+ } catch {
1497
+ return false;
1498
+ }
1499
+ };
1500
+ if (checkTrusted() === false) throw new APIError("FORBIDDEN", {
1501
+ message: "callbackURL is not a trusted origin.",
1502
+ status: 403
1503
+ });
1504
+ }
1505
+ const session = await getSessionFromCtx(ctx);
1506
+ if (session === void 0 || session === null) throw new APIError("UNAUTHORIZED");
1507
+ const user = session.user;
1508
+ if (subscriptionOptions?.enabled === true && subscriptionOptions.requireEmailVerification === true && user.emailVerified !== true) throw new APIError("BAD_REQUEST", {
1509
+ code: "EMAIL_VERIFICATION_REQUIRED",
1510
+ message: PAYSTACK_ERROR_CODES.EMAIL_VERIFICATION_REQUIRED.message
1511
+ });
1512
+ let plan;
1513
+ let product;
1514
+ if (planName !== void 0 && planName !== null && planName !== "") {
1515
+ if (subscriptionOptions?.enabled !== true) throw new APIError("BAD_REQUEST", { message: "Subscriptions are not enabled." });
1516
+ plan = await getPlanByName(options, planName) ?? void 0;
1517
+ if (plan === void 0 || plan === null) try {
1518
+ const nativePlan = await ctx.context.adapter.findOne({
1519
+ model: "paystackPlan",
1520
+ where: [{
1521
+ field: "name",
1522
+ value: planName
1523
+ }]
1524
+ });
1525
+ if (nativePlan !== void 0 && nativePlan !== null) plan = nativePlan;
1526
+ else plan = await ctx.context.adapter.findOne({
1527
+ model: "paystackPlan",
1528
+ where: [{
1529
+ field: "planCode",
1530
+ value: planName
1531
+ }]
1532
+ }) ?? void 0;
1533
+ } catch {
1534
+ plan = void 0;
1535
+ }
1536
+ if (plan === void 0 || plan === null) throw new APIError("BAD_REQUEST", {
1537
+ code: "SUBSCRIPTION_PLAN_NOT_FOUND",
1538
+ message: PAYSTACK_ERROR_CODES.SUBSCRIPTION_PLAN_NOT_FOUND.message,
1539
+ status: 400
1540
+ });
1541
+ } else if (productName !== void 0 && productName !== null && productName !== "") {
1542
+ if (typeof productName === "string") {
1543
+ product = await getProductByName(options, productName) ?? void 0;
1544
+ product ??= await ctx.context.adapter.findOne({
1545
+ model: "paystackProduct",
1546
+ where: [{
1547
+ field: "name",
1548
+ value: productName
1549
+ }]
1550
+ }) ?? void 0;
1551
+ }
1552
+ if (product === void 0 || product === null) throw new APIError("BAD_REQUEST", {
1553
+ message: `Product '${productName}' not found.`,
1554
+ status: 400
1555
+ });
1556
+ } else if (bodyAmount === void 0 || bodyAmount === null) throw new APIError("BAD_REQUEST", {
1557
+ message: "Either 'plan', 'product', or 'amount' is required to initialize a transaction.",
1558
+ status: 400
1559
+ });
1560
+ let amount = bodyAmount ?? product?.price ?? product?.amount;
1561
+ const finalCurrency = currency ?? product?.currency ?? product?.currency ?? plan?.currency ?? "NGN";
1562
+ const referenceIdFromCtx = ctx.context.referenceId;
1563
+ const referenceId = ctx.body.referenceId ?? referenceIdFromCtx ?? session.user.id;
1564
+ const groupId = normalizeSubscriptionGroup(plan?.group);
1565
+ if (subscriptionId !== void 0) {
1566
+ const selectedSubscription = await createBillingStore(ctx).findSubscriptionById(subscriptionId);
1567
+ if (selectedSubscription === null || selectedSubscription.referenceId !== referenceId || normalizeSubscriptionGroup(selectedSubscription.groupId) !== groupId) throw new APIError("BAD_REQUEST", { message: "Subscription does not belong to the authorized reference and plan group." });
1568
+ }
1569
+ const scheduledChange = await scheduleSubscriptionLifecycleChange(ctx, {
1570
+ referenceId,
1571
+ subscriptionId,
1572
+ plan,
1573
+ scheduleAtPeriodEnd,
1574
+ cancelAtPeriodEnd
1575
+ });
1576
+ if (scheduledChange !== null) return ctx.json(scheduledChange);
1577
+ if (plan !== void 0) try {
1578
+ if (getPlanSeatAmount(plan) !== void 0) {
1579
+ const members = await ctx.context.adapter.findMany({
1580
+ model: "member",
1581
+ where: [{
1582
+ field: "organizationId",
1583
+ value: referenceId
1584
+ }]
1585
+ });
1586
+ const seatCount = members.length > 0 ? members.length : 1;
1587
+ amount = calculatePlanAmount(plan, quantity ?? seatCount);
1588
+ }
1589
+ } catch (error) {
1590
+ throw new APIError("BAD_REQUEST", { message: error instanceof Error ? error.message : "Invalid seat configuration for plan." });
1591
+ }
1592
+ let url;
1593
+ let reference;
1594
+ let accessCode;
1595
+ const trial = await resolveTrialLifecycle(ctx, {
1596
+ referenceId,
1597
+ plan
1598
+ });
1599
+ const { trialStart, trialEnd } = trial;
1600
+ try {
1601
+ const targetEmail = await resolveCheckoutTargetEmail(ctx, options, {
1602
+ email,
1603
+ referenceId,
1604
+ user
1605
+ });
1606
+ const allowedSubscriptionChannels = plan ? getAllowedSubscriptionChannels(options) : void 0;
1607
+ const metadata = stringifyPaystackMetadata(createCheckoutMetadata({
1608
+ referenceId,
1609
+ userId: user.id,
1610
+ plan: plan !== void 0 ? plan.name.toLowerCase() : void 0,
1611
+ groupId,
1612
+ product: product !== void 0 ? product.name.toLowerCase() : void 0,
1613
+ extra: extraMetadata,
1614
+ trial: {
1615
+ isTrial: trialStart !== void 0,
1616
+ requested: trial.requested,
1617
+ granted: trial.granted,
1618
+ deniedReason: trial.deniedReason,
1619
+ endsAt: trialEnd
1620
+ }
1621
+ }));
1622
+ const initBody = {
1623
+ email: targetEmail,
1624
+ callback_url: callbackURL ?? void 0,
1625
+ metadata,
1626
+ currency: finalCurrency,
1627
+ quantity
1628
+ };
1629
+ if (allowedSubscriptionChannels !== void 0) initBody.channels = allowedSubscriptionChannels;
1630
+ if (plan !== void 0 && prorateAndCharge === true) {
1631
+ const proration = await handleProratedUpgrade(ctx, options, {
1632
+ plan,
1633
+ referenceId,
1634
+ subscriptionId,
1635
+ quantity,
1636
+ targetEmail,
1637
+ userId: user.id,
1638
+ finalCurrency,
1639
+ callbackURL,
1640
+ allowedSubscriptionChannels
1641
+ });
1642
+ if (proration?.kind === "checkout") return ctx.json({
1643
+ kind: "checkout",
1644
+ url: proration.url ?? "",
1645
+ reference: proration.reference ?? "",
1646
+ accessCode: proration.accessCode ?? "",
1647
+ redirect: proration.redirect
1648
+ });
1649
+ if (proration?.kind === "prorated") return ctx.json({
1650
+ kind: "prorated",
1651
+ status: proration.status,
1652
+ message: proration.message,
1653
+ prorated: proration.prorated
1654
+ });
1655
+ }
1656
+ if (plan !== void 0) if (trialStart !== void 0) initBody.amount = 5e3;
1657
+ else {
1658
+ initBody.plan = plan.planCode;
1659
+ initBody.invoice_limit = plan.invoiceLimit;
1660
+ let finalAmount;
1661
+ if (amount !== void 0 && amount !== null) {
1662
+ finalAmount = amount;
1663
+ initBody.quantity = 1;
1664
+ } else finalAmount = (plan.amount ?? 0) * (quantity ?? 1);
1665
+ initBody.amount = Math.max(Math.round(finalAmount), 5e3);
1666
+ }
1667
+ else {
1668
+ if (amount === void 0 || amount === null) throw new APIError("BAD_REQUEST", { message: "Amount is required for one-time payments" });
1669
+ initBody.amount = Math.round(amount);
1670
+ }
1671
+ const sdkRes = unwrapSdkResult(await paystack?.transaction?.initialize({ body: initBody }));
1672
+ url = sdkRes?.authorization_url;
1673
+ reference = sdkRes?.reference;
1674
+ accessCode = sdkRes?.access_code;
1675
+ } catch (error) {
1676
+ ctx.context.logger.error("Failed to initialize Paystack transaction", error);
1677
+ throw new APIError("BAD_REQUEST", {
1678
+ code: "FAILED_TO_INITIALIZE_TRANSACTION",
1679
+ message: error instanceof Error ? error.message : PAYSTACK_ERROR_CODES.FAILED_TO_INITIALIZE_TRANSACTION.message
1680
+ });
1681
+ }
1682
+ await ctx.context.adapter.create({
1683
+ model: "paystackTransaction",
1684
+ data: {
1685
+ reference: reference ?? "",
1686
+ referenceId,
1687
+ userId: user.id,
1688
+ amount: amount ?? 0,
1689
+ currency: plan?.currency ?? currency ?? "NGN",
1690
+ status: "pending",
1691
+ plan: plan !== void 0 ? plan.name.toLowerCase() : void 0,
1692
+ product: product !== void 0 ? product.name.toLowerCase() : void 0,
1693
+ metadata: hasPaystackMetadata(extraMetadata) ? stringifyPaystackMetadata(extraMetadata) : void 0,
1694
+ createdAt: /* @__PURE__ */ new Date(),
1695
+ updatedAt: /* @__PURE__ */ new Date()
1696
+ }
1697
+ });
1698
+ if (plan !== void 0) {
1699
+ let storedCustomerCode = user.paystackCustomerCode;
1700
+ if (options.organization?.enabled === true && referenceId !== user.id) {
1701
+ const org = await ctx.context.adapter.findOne({
1702
+ model: "organization",
1703
+ where: [{
1704
+ field: "id",
1705
+ value: referenceId
1706
+ }]
1707
+ });
1708
+ if (org !== void 0 && org !== null) {
1709
+ const paystackOrg = org;
1710
+ if (paystackOrg.paystackCustomerCode !== void 0 && paystackOrg.paystackCustomerCode !== null && paystackOrg.paystackCustomerCode !== "") storedCustomerCode = paystackOrg.paystackCustomerCode;
1711
+ }
1712
+ }
1713
+ const newSubscription = await ctx.context.adapter.create({
1714
+ model: "subscription",
1715
+ data: {
1716
+ plan: plan.name.toLowerCase(),
1717
+ groupId,
1718
+ referenceId,
1719
+ userId: user.id,
1720
+ paystackCustomerCode: storedCustomerCode ?? "",
1721
+ paystackSubscriptionCode: "",
1722
+ paystackPlanCode: plan.planCode,
1723
+ paystackAuthorizationCode: "",
1724
+ paystackTransactionReference: reference ?? "",
1725
+ status: trialStart !== void 0 ? "trialing" : "incomplete",
1726
+ billingInterval: plan.interval ?? null,
1727
+ seats: quantity ?? 1,
1728
+ periodStart: /* @__PURE__ */ new Date(),
1729
+ periodEnd: new Date(Date.now() + 720 * 60 * 60 * 1e3),
1730
+ cancelAtPeriodEnd: false,
1731
+ trialStart,
1732
+ trialEnd,
1733
+ createdAt: /* @__PURE__ */ new Date(),
1734
+ updatedAt: /* @__PURE__ */ new Date()
1735
+ }
1736
+ });
1737
+ if (trialStart !== void 0 && newSubscription !== void 0 && newSubscription !== null && plan.freeTrial?.onTrialStart !== void 0) await plan.freeTrial.onTrialStart(newSubscription);
1738
+ }
1739
+ return ctx.json({
1740
+ kind: "checkout",
1741
+ url: url ?? "",
1742
+ reference: reference ?? "",
1743
+ accessCode: accessCode ?? "",
1744
+ redirect: true
1745
+ });
1746
+ });
1747
+ };
1748
+ const createSubscription = (options, path = "/create-subscription") => initializeTransaction(options, path);
1749
+ const upgradeSubscription = (options, path = "/upgrade-subscription") => initializeTransaction(options, path);
1750
+ const cancelSubscription = (options, path = "/cancel-subscription") => disablePaystackSubscription(options, path);
1751
+ const restoreSubscription = (options, path = "/restore-subscription") => enablePaystackSubscription(options, path);
1752
+ const verifyTransaction = (options, path = "/verify-transaction") => {
1753
+ return createAuthEndpoint(path, {
1754
+ method: "POST",
1755
+ body: z.object({ reference: z.string() }),
1756
+ use: options.subscription?.enabled === true ? [
1757
+ sessionMiddleware,
1758
+ originCheck,
1759
+ referenceMiddleware(options, "verify-transaction")
1760
+ ] : [sessionMiddleware, originCheck]
1761
+ }, async (ctx) => {
1762
+ const session = await getSessionFromCtx(ctx);
1763
+ const result = await reconcilePaystackTransaction(ctx, options, {
1764
+ reference: ctx.body.reference,
1765
+ source: "browser",
1766
+ actor: session !== void 0 && session !== null ? {
1767
+ user: session.user,
1768
+ session: session.session
1769
+ } : void 0,
1770
+ throwOnError: true
1771
+ });
1772
+ if (!result.ok || result.data === null) throw new APIError("BAD_REQUEST", {
1773
+ code: result.error?.code ?? "FAILED_TO_VERIFY_TRANSACTION",
1774
+ message: result.error?.message ?? PAYSTACK_ERROR_CODES.FAILED_TO_VERIFY_TRANSACTION.message,
1775
+ status: result.error?.status
1776
+ });
1777
+ return ctx.json({
1778
+ status: result.status,
1779
+ reference: result.reference,
1780
+ data: result.data
1781
+ });
1782
+ });
1783
+ };
1784
+ const listSubscriptions = (options, path = "/list-subscriptions") => {
1785
+ const listQuerySchema = z.object({ referenceId: z.string().optional() });
1786
+ const subscriptionOptions = options.subscription;
1787
+ return createAuthEndpoint(path, {
1788
+ method: "GET",
1789
+ query: listQuerySchema,
1790
+ use: subscriptionOptions?.enabled === true ? [
1791
+ sessionMiddleware,
1792
+ originCheck,
1793
+ referenceMiddleware(options, "list-subscriptions")
1794
+ ] : [sessionMiddleware, originCheck]
1795
+ }, async (ctx) => {
1796
+ if (subscriptionOptions?.enabled !== true) throw new APIError("BAD_REQUEST", { message: "Subscriptions are not enabled in the Paystack options." });
1797
+ const session = await getSessionFromCtx(ctx);
1798
+ if (session === void 0 || session === null) throw new APIError("UNAUTHORIZED");
1799
+ const store = createBillingStore(ctx);
1800
+ const referenceIdPart = ctx.context.referenceId;
1801
+ const queryRefId = ctx.query?.referenceId ?? (typeof ctx.request?.url === "string" ? new URL(ctx.request.url).searchParams.get("referenceId") ?? void 0 : void 0);
1802
+ const userId = session.user.id;
1803
+ if (queryRefId !== void 0 && queryRefId !== userId && referenceIdPart !== queryRefId) await authorizeBillingReference(ctx, options, {
1804
+ user: session.user,
1805
+ session: session.session,
1806
+ referenceId: queryRefId,
1807
+ action: "list-subscriptions"
1808
+ });
1809
+ const referenceId = queryRefId ?? referenceIdPart ?? userId;
1810
+ const res = await store.findSubscriptionsByReference(referenceId);
1811
+ return ctx.json({ subscriptions: res });
1812
+ });
1813
+ };
1814
+ const listTransactions = (options, path = "/list-transactions") => {
1815
+ return createAuthEndpoint(path, {
1816
+ method: "GET",
1817
+ query: z.object({ referenceId: z.string().optional() }),
1818
+ use: options.subscription?.enabled === true ? [
1819
+ sessionMiddleware,
1820
+ originCheck,
1821
+ referenceMiddleware(options, "list-transactions")
1822
+ ] : [sessionMiddleware, originCheck]
1823
+ }, async (ctx) => {
1824
+ const session = await getSessionFromCtx(ctx);
1825
+ if (session === void 0 || session === null) throw new APIError("UNAUTHORIZED");
1826
+ const store = createBillingStore(ctx);
1827
+ const referenceIdPart = ctx.context.referenceId;
1828
+ const queryRefId = ctx.query?.referenceId ?? (typeof ctx.request?.url === "string" ? new URL(ctx.request.url).searchParams.get("referenceId") ?? void 0 : void 0);
1829
+ const userId = session.user.id;
1830
+ if (queryRefId !== void 0 && queryRefId !== userId && referenceIdPart !== queryRefId) await authorizeBillingReference(ctx, options, {
1831
+ user: session.user,
1832
+ session: session.session,
1833
+ referenceId: queryRefId,
1834
+ action: "list-transactions"
1835
+ });
1836
+ const referenceId = queryRefId ?? referenceIdPart ?? userId;
1837
+ const transactions = await store.listTransactions(referenceId);
1838
+ return ctx.json({ transactions });
1839
+ });
1840
+ };
1841
+ const disablePaystackSubscription = (options, path = "/disable-subscription") => {
1842
+ return createAuthEndpoint(path, {
1843
+ method: "POST",
1844
+ body: enableDisableBodySchema,
1845
+ use: options.subscription?.enabled === true ? [
1846
+ sessionMiddleware,
1847
+ originCheck,
1848
+ referenceMiddleware(options, "disable-subscription")
1849
+ ] : [sessionMiddleware, originCheck]
1850
+ }, async (ctx) => {
1851
+ const { subscriptionCode, atPeriodEnd } = ctx.body;
1852
+ const paystack = getPaystackOps(options.paystackClient);
1853
+ try {
1854
+ if (isLocalSubscriptionCode(subscriptionCode)) {
1855
+ const sub = await ctx.context.adapter.findOne({
1856
+ model: "subscription",
1857
+ where: [{
1858
+ field: "paystackSubscriptionCode",
1859
+ value: subscriptionCode
1860
+ }]
1861
+ });
1862
+ if (sub !== null && sub !== void 0) {
1863
+ const now = /* @__PURE__ */ new Date();
1864
+ const immediate = atPeriodEnd === false;
1865
+ await ctx.context.adapter.update({
1866
+ model: "subscription",
1867
+ update: {
1868
+ status: immediate ? "canceled" : "active",
1869
+ cancelAtPeriodEnd: !immediate,
1870
+ cancelAt: immediate ? null : sub.periodEnd ?? null,
1871
+ canceledAt: now,
1872
+ endedAt: immediate ? now : null,
1873
+ updatedAt: now
1874
+ },
1875
+ where: [{
1876
+ field: "id",
1877
+ value: sub.id
1878
+ }]
1879
+ });
1880
+ return ctx.json({ status: "success" });
1881
+ }
1882
+ throw new APIError("BAD_REQUEST", { message: "Subscription not found" });
1883
+ }
1884
+ let emailToken = ctx.body.emailToken;
1885
+ let nextPaymentDate;
1886
+ try {
1887
+ const fetchRes = unwrapSdkResult(await paystack?.subscription?.fetch(subscriptionCode));
1888
+ if (fetchRes !== void 0 && fetchRes !== null) {
1889
+ emailToken ??= fetchRes.email_token ?? void 0;
1890
+ nextPaymentDate = fetchRes.next_payment_date ?? void 0;
1891
+ }
1892
+ } catch {}
1893
+ if (emailToken === void 0 || emailToken === null || emailToken === "") try {
1894
+ const link = unwrapSdkResult(await paystack?.subscription?.manageLink(subscriptionCode))?.link;
1895
+ if (link !== void 0 && link !== null && link !== "") emailToken = tryGetEmailTokenFromSubscriptionManageLink(link);
1896
+ } catch {}
1897
+ if (emailToken === void 0 || emailToken === null || emailToken === "") throw new Error("Could not retrieve email_token for subscription disable.");
1898
+ await paystack?.subscription?.disable({ body: {
1899
+ code: subscriptionCode,
1900
+ token: emailToken
1901
+ } });
1902
+ const periodEnd = nextPaymentDate !== void 0 && nextPaymentDate !== null && nextPaymentDate !== "" ? new Date(nextPaymentDate) : void 0;
1903
+ const sub = await ctx.context.adapter.findOne({
1904
+ model: "subscription",
1905
+ where: [{
1906
+ field: "paystackSubscriptionCode",
1907
+ value: subscriptionCode
1908
+ }]
1909
+ });
1910
+ if (sub !== void 0 && sub !== null) {
1911
+ const now = /* @__PURE__ */ new Date();
1912
+ const immediate = atPeriodEnd === false;
1913
+ await ctx.context.adapter.update({
1914
+ model: "subscription",
1915
+ update: {
1916
+ status: immediate ? "canceled" : "active",
1917
+ cancelAtPeriodEnd: !immediate,
1918
+ cancelAt: immediate ? null : periodEnd ?? sub.periodEnd ?? null,
1919
+ canceledAt: now,
1920
+ endedAt: immediate ? now : null,
1921
+ periodEnd,
1922
+ updatedAt: now
1923
+ },
1924
+ where: [{
1925
+ field: "id",
1926
+ value: sub.id
1927
+ }]
1928
+ });
1929
+ } else ctx.context.logger.warn(`Could not find subscription with code ${subscriptionCode} to disable`);
1930
+ return ctx.json({ status: "success" });
1931
+ } catch (error) {
1932
+ ctx.context.logger.error("Failed to disable subscription", error);
1933
+ throw new APIError("BAD_REQUEST", {
1934
+ code: "FAILED_TO_DISABLE_SUBSCRIPTION",
1935
+ message: error instanceof Error ? error.message : PAYSTACK_ERROR_CODES.FAILED_TO_DISABLE_SUBSCRIPTION.message
1936
+ });
1937
+ }
1938
+ });
1939
+ };
1940
+ const enablePaystackSubscription = (options, path = "/enable-subscription") => {
1941
+ return createAuthEndpoint(path, {
1942
+ method: "POST",
1943
+ body: enableDisableBodySchema,
1944
+ use: options.subscription?.enabled === true ? [
1945
+ sessionMiddleware,
1946
+ originCheck,
1947
+ referenceMiddleware(options, "enable-subscription")
1948
+ ] : [sessionMiddleware, originCheck]
1949
+ }, async (ctx) => {
1950
+ const { subscriptionCode } = ctx.body;
1951
+ const paystack = getPaystackOps(options.paystackClient);
1952
+ try {
1953
+ let emailToken = ctx.body.emailToken;
1954
+ if (emailToken === void 0 || emailToken === null || emailToken === "") try {
1955
+ const fetchRes = unwrapSdkResult(await paystack?.subscription?.fetch(subscriptionCode));
1956
+ if (fetchRes !== void 0 && fetchRes !== null) emailToken = fetchRes.email_token ?? void 0;
1957
+ } catch {}
1958
+ if (emailToken === void 0 || emailToken === null || emailToken === "") try {
1959
+ const link = unwrapSdkResult(await paystack?.subscription?.manageLink(subscriptionCode))?.link;
1960
+ if (link !== void 0 && link !== null && link !== "") emailToken = tryGetEmailTokenFromSubscriptionManageLink(link);
1961
+ } catch {}
1962
+ if (emailToken === void 0 || emailToken === null || emailToken === "") throw new APIError("BAD_REQUEST", { message: "Could not retrieve email_token for subscription enable." });
1963
+ await paystack?.subscription?.enable({ body: {
1964
+ code: subscriptionCode,
1965
+ token: emailToken
1966
+ } });
1967
+ await ctx.context.adapter.update({
1968
+ model: "subscription",
1969
+ update: {
1970
+ status: "active",
1971
+ cancelAtPeriodEnd: false,
1972
+ cancelAt: null,
1973
+ canceledAt: null,
1974
+ endedAt: null,
1975
+ updatedAt: /* @__PURE__ */ new Date()
1976
+ },
1977
+ where: [{
1978
+ field: "paystackSubscriptionCode",
1979
+ value: subscriptionCode
1980
+ }]
1981
+ });
1982
+ return ctx.json({ status: "success" });
1983
+ } catch (error) {
1984
+ ctx.context.logger.error("Failed to enable subscription", error);
1985
+ throw new APIError("BAD_REQUEST", {
1986
+ code: "FAILED_TO_ENABLE_SUBSCRIPTION",
1987
+ message: error instanceof Error ? error.message : PAYSTACK_ERROR_CODES.FAILED_TO_ENABLE_SUBSCRIPTION.message
1988
+ });
1989
+ }
1990
+ });
1991
+ };
1992
+ const getSubscriptionManageLink = (options, path = "/subscription-manage-link") => {
1993
+ const manageLinkQuerySchema = z.object({ subscriptionCode: z.string() });
1994
+ const useMiddlewares = options.subscription?.enabled === true ? [
1995
+ sessionMiddleware,
1996
+ originCheck,
1997
+ referenceMiddleware(options, "get-subscription-manage-link")
1998
+ ] : [sessionMiddleware, originCheck];
1999
+ const handler = async (ctx) => {
2000
+ const { subscriptionCode } = ctx.query;
2001
+ if (isLocalSubscriptionCode(subscriptionCode)) return ctx.json({
2002
+ link: null,
2003
+ message: "Local subscriptions cannot be managed on Paystack"
2004
+ });
2005
+ const paystack = getPaystackOps(options.paystackClient);
2006
+ try {
2007
+ const res = unwrapSdkResult(await paystack?.subscription?.manageLink(subscriptionCode));
2008
+ return ctx.json({ link: res?.link || null });
2009
+ } catch (error) {
2010
+ ctx.context.logger.error("Failed to get subscription manage link", error);
2011
+ throw new APIError("BAD_REQUEST", { message: error instanceof Error ? error.message : "Failed to get subscription manage link" });
2012
+ }
2013
+ };
2014
+ return createAuthEndpoint(path, {
2015
+ method: "GET",
2016
+ query: manageLinkQuerySchema,
2017
+ use: useMiddlewares
2018
+ }, handler);
2019
+ };
2020
+ const listProducts = (_options, path = "/list-products") => {
2021
+ return createAuthEndpoint(path, {
2022
+ method: "GET",
2023
+ metadata: { openapi: { operationId: "listPaystackProducts" } }
2024
+ }, async (ctx) => {
2025
+ const products = await listStoredProducts(ctx);
2026
+ return ctx.json({ products });
2027
+ });
2028
+ };
2029
+ const listPlans = (_options, path = "/list-plans") => {
2030
+ return createAuthEndpoint(path, {
2031
+ method: "GET",
2032
+ metadata: { ...HIDE_METADATA },
2033
+ use: [sessionMiddleware]
2034
+ }, async (ctx) => {
2035
+ try {
2036
+ const plans = await listStoredPlans(ctx);
2037
+ return ctx.json({ plans });
2038
+ } catch (error) {
2039
+ ctx.context.logger.error("Failed to list plans", error);
2040
+ throw new APIError("BAD_REQUEST", { message: error instanceof Error ? error.message : "Failed to list plans" });
2041
+ }
2042
+ });
2043
+ };
2044
+ const getConfig = (options, path = "/get-config") => {
2045
+ return createAuthEndpoint(path, {
2046
+ method: "GET",
2047
+ metadata: { openapi: { operationId: "getPaystackConfig" } }
2048
+ }, async (ctx) => {
2049
+ return ctx.json(await getConfiguredCatalog(options));
2050
+ });
2051
+ };
2052
+ const transactions = { paystackTransaction: { fields: {
2053
+ reference: {
2054
+ type: "string",
2055
+ required: true,
2056
+ unique: true
2057
+ },
2058
+ paystackId: {
2059
+ type: "string",
2060
+ required: false
2061
+ },
2062
+ referenceId: {
2063
+ type: "string",
2064
+ required: true,
2065
+ index: true
2066
+ },
2067
+ userId: {
2068
+ type: "string",
2069
+ required: true,
2070
+ index: true
2071
+ },
2072
+ amount: {
2073
+ type: "number",
2074
+ required: true
2075
+ },
2076
+ currency: {
2077
+ type: "string",
2078
+ required: true
2079
+ },
2080
+ status: {
2081
+ type: "string",
2082
+ required: true
2083
+ },
2084
+ plan: {
2085
+ type: "string",
2086
+ required: false
2087
+ },
2088
+ product: {
2089
+ type: "string",
2090
+ required: false
2091
+ },
2092
+ metadata: {
2093
+ type: "string",
2094
+ required: false
2095
+ },
2096
+ createdAt: {
2097
+ type: "date",
2098
+ required: true
2099
+ },
2100
+ updatedAt: {
2101
+ type: "date",
2102
+ required: true
2103
+ }
2104
+ } } };
2105
+ const subscriptions = { subscription: { fields: {
2106
+ plan: {
2107
+ type: "string",
2108
+ required: true,
2109
+ index: true
2110
+ },
2111
+ referenceId: {
2112
+ type: "string",
2113
+ required: true,
2114
+ index: true
2115
+ },
2116
+ paystackCustomerCode: {
2117
+ type: "string",
2118
+ required: false,
2119
+ index: true
2120
+ },
2121
+ paystackSubscriptionCode: {
2122
+ type: "string",
2123
+ required: false,
2124
+ unique: true
2125
+ },
2126
+ paystackTransactionReference: {
2127
+ type: "string",
2128
+ required: false,
2129
+ index: true
2130
+ },
2131
+ paystackAuthorizationCode: {
2132
+ type: "string",
2133
+ required: false
2134
+ },
2135
+ paystackEmailToken: {
2136
+ type: "string",
2137
+ required: false
2138
+ },
2139
+ status: {
2140
+ type: "string",
2141
+ defaultValue: "incomplete"
2142
+ },
2143
+ periodStart: {
2144
+ type: "date",
2145
+ required: false
2146
+ },
2147
+ periodEnd: {
2148
+ type: "date",
2149
+ required: false
2150
+ },
2151
+ trialStart: {
2152
+ type: "date",
2153
+ required: false
2154
+ },
2155
+ trialEnd: {
2156
+ type: "date",
2157
+ required: false
2158
+ },
2159
+ cancelAtPeriodEnd: {
2160
+ type: "boolean",
2161
+ required: false,
2162
+ defaultValue: false
2163
+ },
2164
+ cancelAt: {
2165
+ type: "date",
2166
+ required: false
2167
+ },
2168
+ canceledAt: {
2169
+ type: "date",
2170
+ required: false
2171
+ },
2172
+ endedAt: {
2173
+ type: "date",
2174
+ required: false
2175
+ },
2176
+ billingInterval: {
2177
+ type: "string",
2178
+ required: false
2179
+ },
2180
+ groupId: {
2181
+ type: "string",
2182
+ required: false
2183
+ },
2184
+ seats: {
2185
+ type: "number",
2186
+ required: false
2187
+ },
2188
+ pendingPlan: {
2189
+ type: "string",
2190
+ required: false
2191
+ }
2192
+ } } };
2193
+ const user = { user: { fields: { paystackCustomerCode: {
2194
+ type: "string",
2195
+ required: false,
2196
+ index: true
2197
+ } } } };
2198
+ const organization = { organization: { fields: {
2199
+ paystackCustomerCode: {
2200
+ type: "string",
2201
+ required: false,
2202
+ index: true
2203
+ },
2204
+ email: {
2205
+ type: "string",
2206
+ required: false
2207
+ }
2208
+ } } };
2209
+ const products = { paystackProduct: { fields: {
2210
+ name: {
2211
+ type: "string",
2212
+ required: true
2213
+ },
2214
+ description: {
2215
+ type: "string",
2216
+ required: false
2217
+ },
2218
+ price: {
2219
+ type: "number",
2220
+ required: true
2221
+ },
2222
+ currency: {
2223
+ type: "string",
2224
+ required: true
2225
+ },
2226
+ quantity: {
2227
+ type: "number",
2228
+ required: false,
2229
+ defaultValue: 0
2230
+ },
2231
+ unlimited: {
2232
+ type: "boolean",
2233
+ required: false,
2234
+ defaultValue: true
2235
+ },
2236
+ paystackId: {
2237
+ type: "string",
2238
+ required: false,
2239
+ unique: true
2240
+ },
2241
+ slug: {
2242
+ type: "string",
2243
+ required: true,
2244
+ unique: true
2245
+ },
2246
+ metadata: {
2247
+ type: "string",
2248
+ required: false
2249
+ },
2250
+ createdAt: {
2251
+ type: "date",
2252
+ required: true
2253
+ },
2254
+ updatedAt: {
2255
+ type: "date",
2256
+ required: true
2257
+ }
2258
+ } } };
2259
+ const plans = { paystackPlan: { fields: {
2260
+ name: {
2261
+ type: "string",
2262
+ required: true
2263
+ },
2264
+ description: {
2265
+ type: "string",
2266
+ required: false
2267
+ },
2268
+ amount: {
2269
+ type: "number",
2270
+ required: true
2271
+ },
2272
+ currency: {
2273
+ type: "string",
2274
+ required: true
2275
+ },
2276
+ interval: {
2277
+ type: "string",
2278
+ required: true
2279
+ },
2280
+ group: {
2281
+ type: "string",
2282
+ required: false
2283
+ },
2284
+ planCode: {
2285
+ type: "string",
2286
+ required: true,
2287
+ unique: true
2288
+ },
2289
+ paystackId: {
2290
+ type: "string",
2291
+ required: true,
2292
+ unique: true
2293
+ },
2294
+ metadata: {
2295
+ type: "string",
2296
+ required: false
2297
+ },
2298
+ createdAt: {
2299
+ type: "date",
2300
+ required: true
2301
+ },
2302
+ updatedAt: {
2303
+ type: "date",
2304
+ required: true
2305
+ }
2306
+ } } };
2307
+ ({
2308
+ ...subscriptions,
2309
+ ...transactions,
2310
+ ...user,
2311
+ ...organization,
2312
+ ...products,
2313
+ ...plans
2314
+ });
2315
+ const getSchema = (options) => {
2316
+ let baseSchema;
2317
+ const optionSchema = options.schema;
2318
+ if (options.subscription?.enabled === true) baseSchema = {
2319
+ ...subscriptions,
2320
+ ...transactions,
2321
+ ...user,
2322
+ ...products,
2323
+ ...plans
2324
+ };
2325
+ else baseSchema = {
2326
+ ...user,
2327
+ ...transactions,
2328
+ ...products,
2329
+ ...plans
2330
+ };
2331
+ if (options.organization?.enabled === true) baseSchema = {
2332
+ ...baseSchema,
2333
+ ...organization
2334
+ };
2335
+ if (options.schema !== void 0 && options.subscription?.enabled !== true && "subscription" in options.schema) {
2336
+ const { subscription: _subscription, ...restSchema } = optionSchema ?? {};
2337
+ return mergeSchema(baseSchema, restSchema);
2338
+ }
2339
+ return mergeSchema(baseSchema, optionSchema);
2340
+ };
2341
+ //#endregion
2342
+ //#region src/customer.ts
2343
+ function isNotFound(error) {
2344
+ if (error === null || typeof error !== "object") return false;
2345
+ const candidate = error;
2346
+ return candidate.status === 404 || candidate.statusCode === 404;
2347
+ }
2348
+ function customerCode(customer) {
2349
+ if (customer === null || typeof customer !== "object") return void 0;
2350
+ const code = customer.customer_code;
2351
+ return typeof code === "string" && code !== "" ? code : void 0;
2352
+ }
2353
+ function ownsCustomer(customer, reference) {
2354
+ if (customer === null || typeof customer !== "object") return false;
2355
+ const metadata = parsePaystackMetadata(customer.metadata);
2356
+ const expectedIdKey = reference.type === "user" ? "userId" : "organizationId";
2357
+ const otherIdKey = reference.type === "user" ? "organizationId" : "userId";
2358
+ return metadata[expectedIdKey] === reference.id && metadata[otherIdKey] === void 0 && (metadata.customerType === void 0 || metadata.customerType === reference.type);
2359
+ }
2360
+ function hasOwner(customer) {
2361
+ if (customer === null || typeof customer !== "object") return false;
2362
+ const metadata = parsePaystackMetadata(customer.metadata);
2363
+ return typeof metadata.userId === "string" || typeof metadata.organizationId === "string" || typeof metadata.customerType === "string";
2364
+ }
2365
+ function ownershipMetadata(reference, existing) {
2366
+ return stringifyPaystackMetadata({
2367
+ ...parsePaystackMetadata(existing),
2368
+ customerType: reference.type,
2369
+ ...reference.type === "user" ? { userId: reference.id } : { organizationId: reference.id }
2370
+ });
2371
+ }
2372
+ async function resolvePaystackCustomer(input) {
2373
+ const { adapter, client, logger, reference } = input;
2374
+ const store = createBillingStoreFromAdapter(adapter);
2375
+ const persisted = reference.type === "user" ? await store.findUser(reference.id) : await store.findOrganization(reference.id);
2376
+ const existingCode = reference.paystackCustomerCode ?? persisted?.paystackCustomerCode;
2377
+ if (typeof existingCode === "string" && existingCode !== "") return null;
2378
+ const sdk = createPaystackAdapter(client);
2379
+ let existing = null;
2380
+ if (typeof client.customer?.fetch === "function") try {
2381
+ existing = await sdk.fetchCustomer(reference.email) ?? null;
2382
+ } catch (error) {
2383
+ if (!isNotFound(error)) {
2384
+ logger.error("Failed to look up Paystack customer; customer creation was skipped", error);
2385
+ return null;
2386
+ }
2387
+ }
2388
+ if (existing !== null) {
2389
+ const code = customerCode(existing);
2390
+ if (code === void 0) {
2391
+ logger.error("Paystack customer lookup returned no customer code");
2392
+ return null;
2393
+ }
2394
+ const owned = ownsCustomer(existing, reference);
2395
+ const canClaimLegacy = reference.type === "user" && reference.emailVerified === true && !hasOwner(existing);
2396
+ if (!owned && !canClaimLegacy) {
2397
+ logger.error("Paystack customer belongs to another billing reference");
2398
+ return null;
2399
+ }
2400
+ const existingMetadata = existing.metadata;
2401
+ if (canClaimLegacy || parsePaystackMetadata(existingMetadata).customerType !== reference.type) await sdk.updateCustomer(code, { metadata: ownershipMetadata(reference, existingMetadata) });
2402
+ await store.saveCustomerCode(reference.id, code, reference.type === "organization");
2403
+ return {
2404
+ customer: existing,
2405
+ created: false
2406
+ };
2407
+ }
2408
+ const customer = await sdk.createCustomer({
2409
+ ...input.createParams,
2410
+ email: reference.email,
2411
+ first_name: reference.name ?? void 0,
2412
+ metadata: ownershipMetadata(reference)
2413
+ });
2414
+ const code = customerCode(customer);
2415
+ if (code === void 0) return null;
2416
+ await store.saveCustomerCode(reference.id, code, reference.type === "organization");
2417
+ return {
2418
+ customer,
2419
+ created: true
2420
+ };
2421
+ }
2422
+ //#endregion
2423
+ //#region src/operations.ts
2424
+ async function syncPaystackProducts(ctx, options) {
2425
+ const paystack = createPaystackAdapter(options.paystackClient);
2426
+ const store = createBillingStore(ctx);
2427
+ try {
2428
+ const productsData = await paystack.listProducts();
2429
+ if (!Array.isArray(productsData)) return {
2430
+ status: "success",
2431
+ count: 0
2432
+ };
2433
+ for (const product of productsData) {
2434
+ const paystackId = String(product.id);
2435
+ const productFields = {
2436
+ name: product.name ?? "",
2437
+ description: product.description ?? "",
2438
+ price: product.price ?? 0,
2439
+ currency: product.currency ?? "",
2440
+ quantity: product.quantity ?? 0,
2441
+ unlimited: product.unlimited !== void 0 && product.unlimited !== null && product.unlimited !== false,
2442
+ paystackId,
2443
+ slug: product.slug ?? product.name?.toLowerCase().replace(/\s+/g, "-") ?? "",
2444
+ metadata: stringifyPaystackMetadata(product.metadata),
2445
+ updatedAt: /* @__PURE__ */ new Date()
2446
+ };
2447
+ await store.upsertProductByPaystackId(paystackId, {
2448
+ ...productFields,
2449
+ createdAt: /* @__PURE__ */ new Date()
2450
+ });
2451
+ }
2452
+ return {
2453
+ status: "success",
2454
+ count: productsData.length
2455
+ };
2456
+ } catch (error) {
2457
+ ctx.context.logger.error("Failed to sync products", error);
2458
+ throw new APIError("BAD_REQUEST", { message: error instanceof Error ? error.message : "Failed to sync products" });
2459
+ }
2460
+ }
2461
+ async function syncPaystackPlans(ctx, options) {
2462
+ const paystack = createPaystackAdapter(options.paystackClient);
2463
+ const store = createBillingStore(ctx);
2464
+ try {
2465
+ const plansData = await paystack.listPlans();
2466
+ if (!Array.isArray(plansData)) return {
2467
+ status: "success",
2468
+ count: 0
2469
+ };
2470
+ for (const plan of plansData) {
2471
+ const paystackId = String(plan.id);
2472
+ const planData = {
2473
+ name: plan.name ?? "",
2474
+ description: typeof plan.description === "string" ? plan.description : "",
2475
+ amount: plan.amount ?? 0,
2476
+ currency: plan.currency ?? "",
2477
+ interval: plan.interval ?? "",
2478
+ planCode: plan.plan_code ?? "",
2479
+ paystackId,
2480
+ metadata: stringifyPaystackMetadata(plan.metadata),
2481
+ updatedAt: /* @__PURE__ */ new Date()
2482
+ };
2483
+ await store.upsertPlanByPaystackId(paystackId, {
2484
+ ...planData,
2485
+ createdAt: /* @__PURE__ */ new Date()
2486
+ });
2487
+ }
2488
+ return {
2489
+ status: "success",
2490
+ count: plansData.length
2491
+ };
2492
+ } catch (error) {
2493
+ ctx.context.logger.error("Failed to sync plans", error);
2494
+ throw new APIError("BAD_REQUEST", { message: error instanceof Error ? error.message : "Failed to sync plans" });
2495
+ }
2496
+ }
2497
+ async function chargeSubscriptionRenewal(ctx, options, input) {
2498
+ const { subscriptionId, amount: bodyAmount } = input;
2499
+ const store = createBillingStore(ctx);
2500
+ const subscription = await store.findSubscriptionById(subscriptionId);
2501
+ if (subscription === void 0 || subscription === null) throw new APIError("NOT_FOUND", { message: "Subscription not found" });
2502
+ if (subscription.paystackAuthorizationCode === void 0 || subscription.paystackAuthorizationCode === null || subscription.paystackAuthorizationCode === "") throw new APIError("BAD_REQUEST", { message: "No authorization code found for this subscription" });
2503
+ const plan = (await getPlans(options.subscription)).find((candidate) => candidate.name.toLowerCase() === subscription.plan.toLowerCase());
2504
+ if (plan === void 0 || plan === null) throw new APIError("NOT_FOUND", { message: "Plan not found" });
2505
+ const amount = bodyAmount ?? plan.amount;
2506
+ if (amount === void 0 || amount === null) throw new APIError("BAD_REQUEST", { message: "Plan amount is not defined" });
2507
+ let email;
2508
+ let billingUserId = subscription.userId;
2509
+ const referenceId = subscription.referenceId;
2510
+ if (referenceId !== void 0 && referenceId !== null && referenceId !== "") {
2511
+ const user = await store.findUser(referenceId);
2512
+ if (user !== void 0 && user !== null) {
2513
+ email = user.email;
2514
+ billingUserId = user.id;
2515
+ } else if (options.organization?.enabled === true) {
2516
+ const ownerMember = await store.findOrganizationOwner(referenceId);
2517
+ if (ownerMember !== void 0 && ownerMember !== null) {
2518
+ const ownerUser = await store.findUser(ownerMember.userId);
2519
+ email = ownerUser?.email;
2520
+ billingUserId = ownerUser?.id ?? ownerMember.userId;
2521
+ }
2522
+ }
2523
+ }
2524
+ if (email === void 0 || email === null || email === "") throw new APIError("NOT_FOUND", { message: "User email not found" });
2525
+ const finalCurrency = plan.currency ?? "NGN";
2526
+ if (!validateMinAmount(amount, finalCurrency)) throw new APIError("BAD_REQUEST", {
2527
+ message: `Amount ${amount} is less than the minimum required for ${finalCurrency}.`,
2528
+ status: 400
2529
+ });
2530
+ const paystack = createPaystackAdapter(options.paystackClient);
2531
+ const serializedRenewalMetadata = stringifyPaystackMetadata(createRenewalMetadata({
2532
+ subscriptionId,
2533
+ referenceId
2534
+ }));
2535
+ const typedChargeData = await paystack.chargeAuthorization({
2536
+ email,
2537
+ amount,
2538
+ authorization_code: subscription.paystackAuthorizationCode,
2539
+ reference: `rec_${subscription.id}_${Date.now()}`,
2540
+ metadata: serializedRenewalMetadata
2541
+ });
2542
+ if (typedChargeData?.status === "success" && typedChargeData.reference !== void 0) {
2543
+ const now = /* @__PURE__ */ new Date();
2544
+ const nextPeriodEnd = getNextPeriodEnd(now, plan.interval ?? "monthly");
2545
+ await store.createTransaction({
2546
+ reference: typedChargeData.reference,
2547
+ paystackId: typedChargeData.id !== void 0 && typedChargeData.id !== null ? String(typedChargeData.id) : void 0,
2548
+ referenceId,
2549
+ userId: billingUserId,
2550
+ amount: typedChargeData.amount,
2551
+ currency: typedChargeData.currency,
2552
+ status: "success",
2553
+ plan: plan.name.toLowerCase(),
2554
+ metadata: serializedRenewalMetadata,
2555
+ createdAt: now,
2556
+ updatedAt: now
2557
+ });
2558
+ await store.updateSubscription(subscription.id, {
2559
+ periodStart: now,
2560
+ periodEnd: nextPeriodEnd,
2561
+ updatedAt: now,
2562
+ paystackTransactionReference: typedChargeData.reference
2563
+ });
2564
+ return {
2565
+ status: "success",
2566
+ data: typedChargeData
2567
+ };
2568
+ }
2569
+ return {
2570
+ status: "failed",
2571
+ data: typedChargeData
2572
+ };
2573
+ }
2574
+ //#endregion
2575
+ //#region src/index.ts
2576
+ const INTERNAL_ERROR_CODES = defineErrorCodes(Object.fromEntries(Object.entries(PAYSTACK_ERROR_CODES).map(([key, value]) => [key, typeof value === "string" ? value : value.message])));
2577
+ const createPaystackPlugin = (options) => {
2578
+ const routeOptions = {
2579
+ ...options,
2580
+ webhook: options.webhook
2581
+ };
2582
+ return {
2583
+ id: "paystack",
2584
+ version: PACKAGE_VERSION,
2585
+ endpoints: {
2586
+ initializeTransaction: initializeTransaction(routeOptions, "/paystack/initialize-transaction"),
2587
+ verifyTransaction: verifyTransaction(routeOptions, "/paystack/verify-transaction"),
2588
+ listSubscriptions: listSubscriptions(routeOptions, "/paystack/list-subscriptions"),
2589
+ paystackWebhook: paystackWebhook(routeOptions, "/paystack/webhook"),
2590
+ listTransactions: listTransactions(routeOptions, "/paystack/list-transactions"),
2591
+ getConfig: getConfig(routeOptions, "/paystack/config"),
2592
+ disableSubscription: disablePaystackSubscription(routeOptions, "/paystack/disable-subscription"),
2593
+ enableSubscription: enablePaystackSubscription(routeOptions, "/paystack/enable-subscription"),
2594
+ getSubscriptionManageLink: getSubscriptionManageLink(routeOptions, "/paystack/subscription-manage-link"),
2595
+ subscriptionManageLink: getSubscriptionManageLink(routeOptions, "/paystack/subscription/manage-link"),
2596
+ createSubscription: createSubscription(routeOptions, "/paystack/create-subscription"),
2597
+ upgradeSubscription: upgradeSubscription(routeOptions, "/paystack/upgrade-subscription"),
2598
+ cancelSubscription: cancelSubscription(routeOptions, "/paystack/cancel-subscription"),
2599
+ restoreSubscription: restoreSubscription(routeOptions, "/paystack/restore-subscription"),
2600
+ listProducts: listProducts(routeOptions, "/paystack/list-products"),
2601
+ listPlans: listPlans(routeOptions, "/paystack/list-plans")
2602
+ },
2603
+ schema: getSchema(options),
2604
+ init: ((ctx) => {
2605
+ const organizationPluginAvailable = ctx.hasPlugin("organization");
2606
+ if (options.organization?.enabled === true && !organizationPluginAvailable) ctx.logger.error("Paystack organization billing is enabled, but the Better Auth organization plugin was not found. Organization billing hooks will be skipped.");
2607
+ return { options: { databaseHooks: {
2608
+ user: {
2609
+ create: { async after(user, hookCtx) {
2610
+ if (!hookCtx || options.createCustomerOnSignUp !== true || user.email === null || user.email === void 0 || user.email === "") return;
2611
+ try {
2612
+ const result = await resolvePaystackCustomer({
2613
+ adapter: ctx.adapter,
2614
+ client: options.paystackClient,
2615
+ logger: ctx.logger,
2616
+ reference: {
2617
+ id: user.id,
2618
+ type: "user",
2619
+ email: user.email,
2620
+ name: user.name,
2621
+ emailVerified: user.emailVerified,
2622
+ paystackCustomerCode: user.paystackCustomerCode
2623
+ }
2624
+ });
2625
+ const customerCode = result?.customer.customer_code;
2626
+ if (result?.created === true && typeof customerCode === "string" && typeof options.onCustomerCreate === "function") await options.onCustomerCreate({
2627
+ paystackCustomer: result.customer,
2628
+ user: {
2629
+ ...user,
2630
+ paystackCustomerCode: customerCode
2631
+ }
2632
+ }, hookCtx);
2633
+ } catch (error) {
2634
+ ctx.logger.error("Failed to create Paystack customer for user", error);
2635
+ }
2636
+ } },
2637
+ update: { async after(user) {
2638
+ const persisted = await createBillingStoreFromAdapter(ctx.adapter).findUser(user.id);
2639
+ const customerCode = user.paystackCustomerCode ?? persisted?.paystackCustomerCode;
2640
+ if (typeof customerCode !== "string" || customerCode === "" || typeof user.email !== "string" || user.email === "") return;
2641
+ try {
2642
+ await createPaystackAdapter(options.paystackClient).updateCustomer(customerCode, { email: user.email });
2643
+ } catch (error) {
2644
+ ctx.logger.error("Failed to synchronize Paystack customer email", error);
2645
+ }
2646
+ } }
2647
+ },
2648
+ organization: options.organization?.enabled === true && organizationPluginAvailable ? {
2649
+ create: { async after(org, hookCtx) {
2650
+ try {
2651
+ const extraCreateParams = typeof options.organization?.getCustomerCreateParams === "function" ? await options.organization.getCustomerCreateParams(org, hookCtx) : {};
2652
+ let targetEmail = org.email;
2653
+ if (targetEmail === void 0 || targetEmail === null) {
2654
+ const store = createBillingStoreFromAdapter(ctx.adapter);
2655
+ const ownerMember = await store.findOrganizationOwner(org.id);
2656
+ if (ownerMember !== null && ownerMember !== void 0) targetEmail = (await store.findUser(ownerMember.userId))?.email;
2657
+ }
2658
+ if (targetEmail === void 0 || targetEmail === null) return;
2659
+ const result = await resolvePaystackCustomer({
2660
+ adapter: ctx.adapter,
2661
+ client: options.paystackClient,
2662
+ logger: ctx.logger,
2663
+ reference: {
2664
+ id: org.id,
2665
+ type: "organization",
2666
+ email: targetEmail,
2667
+ name: org.name,
2668
+ paystackCustomerCode: org.paystackCustomerCode
2669
+ },
2670
+ createParams: defu({}, extraCreateParams)
2671
+ });
2672
+ const customerCode = result?.customer.customer_code;
2673
+ if (result?.created === true && typeof customerCode === "string" && typeof options.organization?.onCustomerCreate === "function") await options.organization.onCustomerCreate({
2674
+ paystackCustomer: result.customer,
2675
+ organization: {
2676
+ ...org,
2677
+ paystackCustomerCode: customerCode
2678
+ }
2679
+ }, hookCtx);
2680
+ } catch (error) {
2681
+ ctx.logger.error("Failed to create Paystack customer for organization", error);
2682
+ }
2683
+ } },
2684
+ update: { async after(org, hookCtx) {
2685
+ const persisted = await createBillingStoreFromAdapter(ctx.adapter).findOrganization(org.id);
2686
+ const customerCode = org.paystackCustomerCode ?? persisted?.paystackCustomerCode;
2687
+ if (typeof customerCode !== "string" || customerCode === "") return;
2688
+ try {
2689
+ const configured = typeof options.organization?.getCustomerCreateParams === "function" && hookCtx ? await options.organization.getCustomerCreateParams({
2690
+ id: org.id,
2691
+ name: org.name ?? persisted?.name ?? "",
2692
+ email: org.email ?? persisted?.email
2693
+ }, hookCtx) : {};
2694
+ const configuredEmail = typeof configured.email === "string" && configured.email !== "" ? configured.email : void 0;
2695
+ await createPaystackAdapter(options.paystackClient).updateCustomer(customerCode, {
2696
+ ...configuredEmail !== void 0 || typeof org.email === "string" && org.email !== "" ? { email: configuredEmail ?? org.email ?? void 0 } : {},
2697
+ ...typeof org.name === "string" && org.name !== "" ? { first_name: org.name } : {}
2698
+ });
2699
+ } catch (error) {
2700
+ ctx.logger.error("Failed to synchronize Paystack organization customer", error);
2701
+ }
2702
+ } },
2703
+ delete: { async before(org) {
2704
+ const store = createBillingStoreFromAdapter(ctx.adapter);
2705
+ if ((await store.findSubscriptionsByReference(org.id)).some((subscription) => subscription.status === "active" || subscription.status === "trialing")) throw new APIError("BAD_REQUEST", { message: "Organization cannot be deleted while it has an active subscription" });
2706
+ const persisted = await store.findOrganization(org.id);
2707
+ const customerCode = org.paystackCustomerCode ?? persisted?.paystackCustomerCode;
2708
+ if (typeof customerCode !== "string" || customerCode === "") return;
2709
+ try {
2710
+ if ((await createPaystackAdapter(options.paystackClient).fetchCustomer(customerCode)).subscriptions?.some((subscription) => subscription.status === "active" || subscription.status === "trialing") === true) throw new APIError("BAD_REQUEST", { message: "Organization cannot be deleted while it has an active subscription" });
2711
+ } catch (error) {
2712
+ if (error instanceof APIError) throw error;
2713
+ ctx.logger.error("Failed to check Paystack subscriptions before organization deletion", error);
2714
+ throw new APIError("BAD_REQUEST", { message: "Organization deletion could not verify its Paystack subscriptions" });
2715
+ }
2716
+ } }
2717
+ } : void 0,
2718
+ member: organizationPluginAvailable ? {
2719
+ create: {
2720
+ before: async (member, ctx) => {
2721
+ if (options.subscription?.enabled === true && member.organizationId && ctx !== null && ctx !== void 0) await checkSeatLimit(ctx, member.organizationId);
2722
+ },
2723
+ after: async (member, ctx) => {
2724
+ if (options.subscription?.enabled === true && typeof member?.organizationId === "string" && ctx) await syncSubscriptionSeats(ctx, member.organizationId, routeOptions);
2725
+ }
2726
+ },
2727
+ delete: { after: async (member, ctx) => {
2728
+ if (options.subscription?.enabled === true && typeof member?.organizationId === "string" && ctx) await syncSubscriptionSeats(ctx, member.organizationId, routeOptions);
2729
+ } }
2730
+ } : void 0,
2731
+ invitation: organizationPluginAvailable ? {
2732
+ create: {
2733
+ before: async (invitation, ctx) => {
2734
+ if (options.subscription?.enabled === true && invitation.organizationId && ctx !== null && ctx !== void 0) await checkSeatLimit(ctx, invitation.organizationId);
2735
+ },
2736
+ after: async (invitation, ctx) => {
2737
+ if (options.subscription?.enabled === true && typeof invitation?.organizationId === "string" && ctx) await syncSubscriptionSeats(ctx, invitation.organizationId, routeOptions);
2738
+ }
2739
+ },
2740
+ delete: { after: async (invitation, ctx) => {
2741
+ if (options.subscription?.enabled === true && typeof invitation?.organizationId === "string" && ctx) await syncSubscriptionSeats(ctx, invitation.organizationId, routeOptions);
2742
+ } }
2743
+ } : void 0,
2744
+ team: organizationPluginAvailable ? { create: { before: async (team, ctx) => {
2745
+ if (options.subscription?.enabled === true && team.organizationId && ctx) {
2746
+ const maxTeams = (await getOrganizationEntitlements(ctx, team.organizationId, routeOptions)).limits.teams;
2747
+ if (typeof maxTeams === "number") await checkTeamLimit(ctx, team.organizationId, maxTeams);
2748
+ }
2749
+ } } } : void 0
2750
+ } } };
2751
+ }),
2752
+ $ERROR_CODES: INTERNAL_ERROR_CODES,
2753
+ options
2754
+ };
2755
+ };
2756
+ const paystack = createPaystackPlugin;
2757
+ //#endregion
2758
+ export { chargeSubscriptionRenewal, createCheckoutMetadata, createProrationMetadata, createRenewalMetadata, getMetadataBoolean, getMetadataNumber, getMetadataString, getOrganizationEntitlements, hasPaystackMetadata, parsePaystackMetadata, paystack, reconcilePaystackTransaction, stringifyPaystackMetadata, syncPaystackPlans, syncPaystackProducts };
2759
+
2760
+ //# sourceMappingURL=index.mjs.map