better-auth-paystack 0.0.0 → 3.2.0

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