better-auth-flutterwave 0.1.10 → 0.2.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +41 -0
- package/dist/client.d.mts +7 -6
- package/dist/client.d.mts.map +1 -1
- package/dist/client.mjs +1 -1
- package/dist/client.mjs.map +1 -1
- package/dist/{index-C1tdrA3c.d.mts → index-XrxY-MVF.d.mts} +21 -5
- package/dist/index-XrxY-MVF.d.mts.map +1 -0
- package/dist/index.d.mts +2 -2
- package/dist/index.mjs +378 -172
- package/dist/index.mjs.map +1 -1
- package/dist/{version-BKseik7h.mjs → version-UDe8miQm.mjs} +2 -2
- package/dist/{version-BKseik7h.mjs.map → version-UDe8miQm.mjs.map} +1 -1
- package/package.json +6 -5
- package/skills/better-auth-flutterwave-setup/SKILL.md +1 -1
- package/skills/flutterwave-billing-flows/SKILL.md +1 -1
- package/skills/flutterwave-catalog-limits/SKILL.md +1 -1
- package/skills/flutterwave-client-api/SKILL.md +1 -1
- package/skills/flutterwave-local-subscriptions/SKILL.md +10 -1
- package/skills/flutterwave-organization-billing/SKILL.md +1 -1
- package/skills/flutterwave-schema-migrations/SKILL.md +7 -1
- package/skills/flutterwave-tanstack-start/SKILL.md +7 -1
- package/skills/flutterwave-testing-fixtures/SKILL.md +1 -1
- package/skills/flutterwave-webhooks-events/SKILL.md +6 -1
- package/dist/index-C1tdrA3c.d.mts.map +0 -1
package/dist/index.mjs
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { a as getMetadataBoolean, c as hasFlutterwaveMetadata, i as createRenewalMetadata, l as parseFlutterwaveMetadata, n as createCheckoutMetadata, o as getMetadataNumber, r as createProrationMetadata, s as getMetadataString, t as PACKAGE_VERSION, u as stringifyFlutterwaveMetadata } from "./version-
|
|
1
|
+
import { a as getMetadataBoolean, c as hasFlutterwaveMetadata, i as createRenewalMetadata, l as parseFlutterwaveMetadata, n as createCheckoutMetadata, o as getMetadataNumber, r as createProrationMetadata, s as getMetadataString, t as PACKAGE_VERSION, u as stringifyFlutterwaveMetadata } from "./version-UDe8miQm.mjs";
|
|
2
2
|
import { createRequire } from "node:module";
|
|
3
3
|
import { HIDE_METADATA, defineErrorCodes } from "better-auth";
|
|
4
4
|
import { createHash, timingSafeEqual } from "node:crypto";
|
|
@@ -51,10 +51,17 @@ function createBillingStoreFromAdapter(adapter) {
|
|
|
51
51
|
},
|
|
52
52
|
async retireCompetingSubscriptions(referenceId, groupId, exceptId) {
|
|
53
53
|
const candidates = await this.findSubscriptionsByReference(referenceId);
|
|
54
|
+
const current = candidates.find(({ id }) => id === exceptId);
|
|
55
|
+
if (!current) return;
|
|
54
56
|
const now = /* @__PURE__ */ new Date();
|
|
55
57
|
for (const candidate of candidates) {
|
|
56
58
|
const sameGroup = groupId === null ? candidate.groupId === void 0 || candidate.groupId === null || candidate.groupId === "" : candidate.groupId === groupId;
|
|
57
|
-
if (candidate.id !== exceptId &&
|
|
59
|
+
if (candidate.id !== exceptId && new Date(candidate.createdAt).getTime() <= new Date(current.createdAt).getTime() && sameGroup && [
|
|
60
|
+
"active",
|
|
61
|
+
"trialing",
|
|
62
|
+
"incomplete",
|
|
63
|
+
"past_due"
|
|
64
|
+
].includes(candidate.status)) await this.updateSubscription(candidate.id, {
|
|
58
65
|
status: "canceled",
|
|
59
66
|
cancelAtPeriodEnd: false,
|
|
60
67
|
canceledAt: now,
|
|
@@ -67,6 +74,48 @@ function createBillingStoreFromAdapter(adapter) {
|
|
|
67
74
|
field: "txRef",
|
|
68
75
|
value: txRef
|
|
69
76
|
}]),
|
|
77
|
+
listDueCancellations: (now, limit) => adapter.findMany({
|
|
78
|
+
model: "flutterwaveSubscription",
|
|
79
|
+
where: [{
|
|
80
|
+
field: "cancelAtPeriodEnd",
|
|
81
|
+
value: true
|
|
82
|
+
}, {
|
|
83
|
+
field: "cancelAt",
|
|
84
|
+
value: now,
|
|
85
|
+
operator: "lte"
|
|
86
|
+
}],
|
|
87
|
+
sortBy: {
|
|
88
|
+
field: "cancelAt",
|
|
89
|
+
direction: "asc"
|
|
90
|
+
},
|
|
91
|
+
limit
|
|
92
|
+
}),
|
|
93
|
+
async completeScheduledCancellation(subscription, now) {
|
|
94
|
+
return await adapter.updateMany({
|
|
95
|
+
model: "flutterwaveSubscription",
|
|
96
|
+
where: [
|
|
97
|
+
{
|
|
98
|
+
field: "id",
|
|
99
|
+
value: subscription.id
|
|
100
|
+
},
|
|
101
|
+
{
|
|
102
|
+
field: "cancelAtPeriodEnd",
|
|
103
|
+
value: true
|
|
104
|
+
},
|
|
105
|
+
{
|
|
106
|
+
field: "cancelAt",
|
|
107
|
+
value: subscription.cancelAt == null ? null : new Date(subscription.cancelAt)
|
|
108
|
+
}
|
|
109
|
+
],
|
|
110
|
+
update: {
|
|
111
|
+
status: "canceled",
|
|
112
|
+
cancelAtPeriodEnd: false,
|
|
113
|
+
canceledAt: subscription.canceledAt ?? now,
|
|
114
|
+
endedAt: subscription.cancelAt ?? now,
|
|
115
|
+
updatedAt: now
|
|
116
|
+
}
|
|
117
|
+
}) === 1;
|
|
118
|
+
},
|
|
70
119
|
createSubscription: (data) => adapter.create({
|
|
71
120
|
model: "flutterwaveSubscription",
|
|
72
121
|
data
|
|
@@ -79,6 +128,26 @@ function createBillingStoreFromAdapter(adapter) {
|
|
|
79
128
|
value: id
|
|
80
129
|
}]
|
|
81
130
|
}),
|
|
131
|
+
async updateCurrentSubscription(subscription, update) {
|
|
132
|
+
return await adapter.updateMany({
|
|
133
|
+
model: "flutterwaveSubscription",
|
|
134
|
+
where: [
|
|
135
|
+
{
|
|
136
|
+
field: "id",
|
|
137
|
+
value: subscription.id
|
|
138
|
+
},
|
|
139
|
+
{
|
|
140
|
+
field: "status",
|
|
141
|
+
value: subscription.status
|
|
142
|
+
},
|
|
143
|
+
{
|
|
144
|
+
field: "txRef",
|
|
145
|
+
value: subscription.txRef ?? null
|
|
146
|
+
}
|
|
147
|
+
],
|
|
148
|
+
update
|
|
149
|
+
}) === 1;
|
|
150
|
+
},
|
|
82
151
|
updateSubscriptionByProviderId: (subscriptionId, update) => adapter.update({
|
|
83
152
|
model: "flutterwaveSubscription",
|
|
84
153
|
update,
|
|
@@ -192,6 +261,29 @@ function createBillingStoreFromAdapter(adapter) {
|
|
|
192
261
|
value: eventId
|
|
193
262
|
}]
|
|
194
263
|
}),
|
|
264
|
+
async claimWebhookEvent(event, now) {
|
|
265
|
+
return await adapter.updateMany({
|
|
266
|
+
model: "flutterwaveWebhookEvent",
|
|
267
|
+
where: [
|
|
268
|
+
{
|
|
269
|
+
field: "eventId",
|
|
270
|
+
value: event.eventId
|
|
271
|
+
},
|
|
272
|
+
{
|
|
273
|
+
field: "status",
|
|
274
|
+
value: event.status
|
|
275
|
+
},
|
|
276
|
+
{
|
|
277
|
+
field: "updatedAt",
|
|
278
|
+
value: new Date(event.updatedAt)
|
|
279
|
+
}
|
|
280
|
+
],
|
|
281
|
+
update: {
|
|
282
|
+
status: "processing",
|
|
283
|
+
updatedAt: now
|
|
284
|
+
}
|
|
285
|
+
}) === 1;
|
|
286
|
+
},
|
|
195
287
|
createRefund: (data) => adapter.create({
|
|
196
288
|
model: "flutterwaveRefund",
|
|
197
289
|
data
|
|
@@ -380,7 +472,10 @@ function createFlutterwaveAdapter(options) {
|
|
|
380
472
|
if (!options.secretKey) throw new FlutterwaveAdapterError("configuration", "secretKey is required");
|
|
381
473
|
const client = options.flutterwaveClient ?? createSdkClient(options.publicKey, options.secretKey);
|
|
382
474
|
const fetchImpl = options.fetch ?? globalThis.fetch;
|
|
383
|
-
const
|
|
475
|
+
const configuredApiBaseUrl = options.apiBaseUrl ?? "https://api.flutterwave.com";
|
|
476
|
+
let end = configuredApiBaseUrl.length;
|
|
477
|
+
while (end > 0 && configuredApiBaseUrl.charCodeAt(end - 1) === 47) end--;
|
|
478
|
+
const apiBaseUrl = configuredApiBaseUrl.slice(0, end);
|
|
384
479
|
return {
|
|
385
480
|
async initializePayment(input) {
|
|
386
481
|
const body = standardCheckoutInputSchema.parse(input);
|
|
@@ -438,6 +533,182 @@ function createFlutterwaveAdapter(options) {
|
|
|
438
533
|
};
|
|
439
534
|
}
|
|
440
535
|
//#endregion
|
|
536
|
+
//#region src/token-crypto.ts
|
|
537
|
+
const encoder = new TextEncoder();
|
|
538
|
+
const decoder = new TextDecoder();
|
|
539
|
+
function toBase64(value) {
|
|
540
|
+
return Buffer.from(value).toString("base64url");
|
|
541
|
+
}
|
|
542
|
+
function fromBase64(value) {
|
|
543
|
+
return new Uint8Array(Buffer.from(value, "base64url"));
|
|
544
|
+
}
|
|
545
|
+
async function deriveKey(secret) {
|
|
546
|
+
const digest = await crypto.subtle.digest("SHA-256", encoder.encode(secret));
|
|
547
|
+
return crypto.subtle.importKey("raw", digest, "AES-GCM", false, ["encrypt", "decrypt"]);
|
|
548
|
+
}
|
|
549
|
+
async function encryptPaymentToken(token, secret) {
|
|
550
|
+
const iv = crypto.getRandomValues(/* @__PURE__ */ new Uint8Array(12));
|
|
551
|
+
const encrypted = await crypto.subtle.encrypt({
|
|
552
|
+
name: "AES-GCM",
|
|
553
|
+
iv
|
|
554
|
+
}, await deriveKey(secret), encoder.encode(token));
|
|
555
|
+
return `v1.${toBase64(iv)}.${toBase64(new Uint8Array(encrypted))}`;
|
|
556
|
+
}
|
|
557
|
+
async function decryptPaymentToken(value, secret) {
|
|
558
|
+
const [version, encodedIv, encodedCiphertext] = value.split(".");
|
|
559
|
+
if (version !== "v1" || !encodedIv || !encodedCiphertext) throw new Error("Unsupported encrypted payment token");
|
|
560
|
+
const iv = Uint8Array.from(fromBase64(encodedIv));
|
|
561
|
+
const ciphertext = Uint8Array.from(fromBase64(encodedCiphertext));
|
|
562
|
+
const decrypted = await crypto.subtle.decrypt({
|
|
563
|
+
name: "AES-GCM",
|
|
564
|
+
iv
|
|
565
|
+
}, await deriveKey(secret), ciphertext);
|
|
566
|
+
return decoder.decode(decrypted);
|
|
567
|
+
}
|
|
568
|
+
//#endregion
|
|
569
|
+
//#region src/utils.ts
|
|
570
|
+
function getPlanSeatAmount(plan) {
|
|
571
|
+
if (plan.seatAmount !== void 0) {
|
|
572
|
+
if (typeof plan.seatAmount === "number" && Number.isFinite(plan.seatAmount) && plan.seatAmount >= 0) return plan.seatAmount;
|
|
573
|
+
throw new Error(`Invalid seatAmount for plan '${plan.name}'. Expected a finite number.`);
|
|
574
|
+
}
|
|
575
|
+
if (plan.seatPriceId === void 0 || plan.seatPriceId === null || plan.seatPriceId === "") return;
|
|
576
|
+
const parsed = typeof plan.seatPriceId === "string" ? Number(plan.seatPriceId) : plan.seatPriceId;
|
|
577
|
+
if (typeof parsed === "number" && Number.isFinite(parsed) && parsed >= 0) return parsed;
|
|
578
|
+
throw new Error(`Invalid seatPriceId for plan '${plan.name}'. Expected a numeric amount in the smallest currency unit.`);
|
|
579
|
+
}
|
|
580
|
+
function calculatePlanAmount(plan, quantity) {
|
|
581
|
+
return (plan.amount ?? 0) + Math.max(0, quantity - 1) * (getPlanSeatAmount(plan) ?? 0);
|
|
582
|
+
}
|
|
583
|
+
function normalizeSubscriptionGroup(group) {
|
|
584
|
+
const normalized = group?.trim().toLowerCase();
|
|
585
|
+
return normalized === void 0 || normalized === "" ? null : normalized;
|
|
586
|
+
}
|
|
587
|
+
async function getPlans(subscriptionOptions) {
|
|
588
|
+
if (subscriptionOptions?.enabled === true) return typeof subscriptionOptions.plans === "function" ? subscriptionOptions.plans() : subscriptionOptions.plans;
|
|
589
|
+
return [];
|
|
590
|
+
}
|
|
591
|
+
async function getPlanByName(options, name) {
|
|
592
|
+
if (typeof name !== "string" || name.trim() === "") return null;
|
|
593
|
+
if (options.subscription?.enabled === true) {
|
|
594
|
+
const plans = await getPlans(options.subscription);
|
|
595
|
+
const normalizedName = name.toLowerCase();
|
|
596
|
+
return plans.find((plan) => typeof plan.name === "string" && plan.name.toLowerCase() === normalizedName) ?? null;
|
|
597
|
+
}
|
|
598
|
+
return null;
|
|
599
|
+
}
|
|
600
|
+
function getNextPeriodEnd(startDate, interval) {
|
|
601
|
+
const date = new Date(startDate);
|
|
602
|
+
const day = date.getUTCDate();
|
|
603
|
+
const addMonths = (months) => {
|
|
604
|
+
date.setUTCDate(1);
|
|
605
|
+
date.setUTCMonth(date.getUTCMonth() + months);
|
|
606
|
+
const lastDay = new Date(Date.UTC(date.getUTCFullYear(), date.getUTCMonth() + 1, 0)).getUTCDate();
|
|
607
|
+
date.setUTCDate(Math.min(day, lastDay));
|
|
608
|
+
};
|
|
609
|
+
switch (interval) {
|
|
610
|
+
case "hourly":
|
|
611
|
+
date.setUTCHours(date.getUTCHours() + 1);
|
|
612
|
+
break;
|
|
613
|
+
case "daily":
|
|
614
|
+
date.setUTCDate(date.getUTCDate() + 1);
|
|
615
|
+
break;
|
|
616
|
+
case "weekly":
|
|
617
|
+
date.setUTCDate(date.getUTCDate() + 7);
|
|
618
|
+
break;
|
|
619
|
+
case "monthly":
|
|
620
|
+
addMonths(1);
|
|
621
|
+
break;
|
|
622
|
+
case "quarterly":
|
|
623
|
+
addMonths(3);
|
|
624
|
+
break;
|
|
625
|
+
case "biannually":
|
|
626
|
+
case "bi-annually":
|
|
627
|
+
addMonths(6);
|
|
628
|
+
break;
|
|
629
|
+
case "annually":
|
|
630
|
+
case "yearly":
|
|
631
|
+
addMonths(12);
|
|
632
|
+
break;
|
|
633
|
+
default: {
|
|
634
|
+
const recurring = /^every (\d+) (hours?|days?|weeks?|months?|years?)$/.exec(interval);
|
|
635
|
+
if (!recurring) return null;
|
|
636
|
+
const count = Number(recurring[1]);
|
|
637
|
+
if (!Number.isSafeInteger(count) || count < 1) return null;
|
|
638
|
+
const unit = recurring[2];
|
|
639
|
+
if (unit?.startsWith("hour")) date.setUTCHours(date.getUTCHours() + count);
|
|
640
|
+
else if (unit?.startsWith("day")) date.setUTCDate(date.getUTCDate() + count);
|
|
641
|
+
else if (unit?.startsWith("week")) date.setUTCDate(date.getUTCDate() + count * 7);
|
|
642
|
+
else addMonths(count * (unit?.startsWith("year") ? 12 : 1));
|
|
643
|
+
if (!Number.isFinite(date.getTime())) return null;
|
|
644
|
+
}
|
|
645
|
+
}
|
|
646
|
+
return date;
|
|
647
|
+
}
|
|
648
|
+
//#endregion
|
|
649
|
+
//#region src/billing-lifecycle.ts
|
|
650
|
+
function paymentMatches(expected, verified) {
|
|
651
|
+
return verified.tx_ref === expected.txRef && verified.amount === expected.amount && verified.currency === expected.currency;
|
|
652
|
+
}
|
|
653
|
+
/** Shared fulfillment for browser verification, webhooks, and trusted reconciliation. */
|
|
654
|
+
async function recordVerifiedPayment(ctx, options, expected, verified) {
|
|
655
|
+
if (!paymentMatches(expected, verified)) throw new APIError("BAD_REQUEST", { message: "Verified transaction does not match the expected payment" });
|
|
656
|
+
const store = createBillingStore(ctx);
|
|
657
|
+
const now = /* @__PURE__ */ new Date();
|
|
658
|
+
if (expected.status === "successful" && verified.status !== "successful") return;
|
|
659
|
+
await store.updateTransactionByTxRef(expected.txRef, {
|
|
660
|
+
transactionId: verified.id,
|
|
661
|
+
flwRef: verified.flw_ref,
|
|
662
|
+
chargedAmount: verified.charged_amount,
|
|
663
|
+
paymentType: verified.payment_type,
|
|
664
|
+
status: verified.status,
|
|
665
|
+
verifiedAt: expected.verifiedAt ?? now,
|
|
666
|
+
reconciledAt: now,
|
|
667
|
+
updatedAt: now
|
|
668
|
+
});
|
|
669
|
+
if (verified.status !== "successful" || options.subscription?.enabled !== true) return;
|
|
670
|
+
for (const subscription of await store.findSubscriptionsByTxRef(expected.txRef)) {
|
|
671
|
+
if (subscription.status === "canceled" || subscription.endedAt != null) continue;
|
|
672
|
+
const group = normalizeSubscriptionGroup(subscription.groupId);
|
|
673
|
+
if ((await store.findSubscriptionsByReference(subscription.referenceId)).some((candidate) => candidate.id !== subscription.id && normalizeSubscriptionGroup(candidate.groupId) === group && (candidate.status === "active" || candidate.status === "trialing" || candidate.status === "canceled" && candidate.periodStart != null) && new Date(candidate.createdAt).getTime() > new Date(subscription.createdAt).getTime())) {
|
|
674
|
+
await store.updateSubscription(subscription.id, {
|
|
675
|
+
status: "canceled",
|
|
676
|
+
canceledAt: now,
|
|
677
|
+
endedAt: now,
|
|
678
|
+
updatedAt: now
|
|
679
|
+
});
|
|
680
|
+
continue;
|
|
681
|
+
}
|
|
682
|
+
let subscriptionId = subscription.subscriptionId;
|
|
683
|
+
if (subscription.paymentPlanId != null && subscriptionId == null && subscription.billingEmail != null && subscription.billingEmail !== "") {
|
|
684
|
+
const candidates = (await createFlutterwaveAdapter(options).listSubscriptions({
|
|
685
|
+
email: subscription.billingEmail,
|
|
686
|
+
plan: subscription.paymentPlanId,
|
|
687
|
+
transactionId: verified.id
|
|
688
|
+
})).filter((candidate) => candidate.status !== "cancelled");
|
|
689
|
+
subscriptionId = candidates.length === 1 ? candidates[0]?.id : void 0;
|
|
690
|
+
}
|
|
691
|
+
const identified = subscription.paymentPlanId == null || subscriptionId != null;
|
|
692
|
+
const paidAt = verified.created_at != null && verified.created_at !== "" ? new Date(verified.created_at) : now;
|
|
693
|
+
const paymentTime = Number.isFinite(paidAt.getTime()) ? paidAt : now;
|
|
694
|
+
const renewal = parseFlutterwaveMetadata(expected.metadata).type === "renewal";
|
|
695
|
+
const priorEnd = subscription.periodEnd ? new Date(subscription.periodEnd) : null;
|
|
696
|
+
const periodStart = renewal && priorEnd !== null && priorEnd > paymentTime ? priorEnd : paymentTime;
|
|
697
|
+
const advancePeriod = subscription.periodEnd == null || (renewal ? subscription.status === "past_due" : expected.status !== "successful");
|
|
698
|
+
if (await store.updateCurrentSubscription(subscription, {
|
|
699
|
+
subscriptionId,
|
|
700
|
+
status: identified ? "active" : "incomplete",
|
|
701
|
+
encryptedPaymentToken: verified.card?.token !== void 0 ? await encryptPaymentToken(verified.card.token, ctx.context.secret) : subscription.encryptedPaymentToken,
|
|
702
|
+
...advancePeriod ? {
|
|
703
|
+
periodStart,
|
|
704
|
+
periodEnd: getNextPeriodEnd(periodStart, subscription.billingInterval ?? "monthly")
|
|
705
|
+
} : {},
|
|
706
|
+
reconciledAt: now,
|
|
707
|
+
updatedAt: now
|
|
708
|
+
}) && identified) await store.retireCompetingSubscriptions(subscription.referenceId, group, subscription.id);
|
|
709
|
+
}
|
|
710
|
+
}
|
|
711
|
+
//#endregion
|
|
441
712
|
//#region src/reference-access.ts
|
|
442
713
|
const DEFAULT_BILLING_ORG_ROLES = ["owner", "admin"];
|
|
443
714
|
function normalizeBillingRoles(roles) {
|
|
@@ -528,58 +799,6 @@ function timingSafeEqualString(left, right) {
|
|
|
528
799
|
return timingSafeEqual(leftBytes, rightBytes);
|
|
529
800
|
}
|
|
530
801
|
//#endregion
|
|
531
|
-
//#region src/token-crypto.ts
|
|
532
|
-
const encoder = new TextEncoder();
|
|
533
|
-
const decoder = new TextDecoder();
|
|
534
|
-
function toBase64(value) {
|
|
535
|
-
return Buffer.from(value).toString("base64url");
|
|
536
|
-
}
|
|
537
|
-
function fromBase64(value) {
|
|
538
|
-
return new Uint8Array(Buffer.from(value, "base64url"));
|
|
539
|
-
}
|
|
540
|
-
async function deriveKey(secret) {
|
|
541
|
-
const digest = await crypto.subtle.digest("SHA-256", encoder.encode(secret));
|
|
542
|
-
return crypto.subtle.importKey("raw", digest, "AES-GCM", false, ["encrypt", "decrypt"]);
|
|
543
|
-
}
|
|
544
|
-
async function encryptPaymentToken(token, secret) {
|
|
545
|
-
const iv = crypto.getRandomValues(/* @__PURE__ */ new Uint8Array(12));
|
|
546
|
-
const encrypted = await crypto.subtle.encrypt({
|
|
547
|
-
name: "AES-GCM",
|
|
548
|
-
iv
|
|
549
|
-
}, await deriveKey(secret), encoder.encode(token));
|
|
550
|
-
return `v1.${toBase64(iv)}.${toBase64(new Uint8Array(encrypted))}`;
|
|
551
|
-
}
|
|
552
|
-
async function decryptPaymentToken(value, secret) {
|
|
553
|
-
const [version, encodedIv, encodedCiphertext] = value.split(".");
|
|
554
|
-
if (version !== "v1" || !encodedIv || !encodedCiphertext) throw new Error("Unsupported encrypted payment token");
|
|
555
|
-
const iv = Uint8Array.from(fromBase64(encodedIv));
|
|
556
|
-
const ciphertext = Uint8Array.from(fromBase64(encodedCiphertext));
|
|
557
|
-
const decrypted = await crypto.subtle.decrypt({
|
|
558
|
-
name: "AES-GCM",
|
|
559
|
-
iv
|
|
560
|
-
}, await deriveKey(secret), ciphertext);
|
|
561
|
-
return decoder.decode(decrypted);
|
|
562
|
-
}
|
|
563
|
-
//#endregion
|
|
564
|
-
//#region src/utils.ts
|
|
565
|
-
function normalizeSubscriptionGroup(group) {
|
|
566
|
-
const normalized = group?.trim().toLowerCase();
|
|
567
|
-
return normalized === void 0 || normalized === "" ? null : normalized;
|
|
568
|
-
}
|
|
569
|
-
async function getPlans(subscriptionOptions) {
|
|
570
|
-
if (subscriptionOptions?.enabled === true) return typeof subscriptionOptions.plans === "function" ? subscriptionOptions.plans() : subscriptionOptions.plans;
|
|
571
|
-
throw new Error("Subscriptions are not enabled in the Flutterwave options.");
|
|
572
|
-
}
|
|
573
|
-
async function getPlanByName(options, name) {
|
|
574
|
-
if (typeof name !== "string" || name.trim() === "") return null;
|
|
575
|
-
if (options.subscription?.enabled === true) {
|
|
576
|
-
const plans = await getPlans(options.subscription);
|
|
577
|
-
const normalizedName = name.toLowerCase();
|
|
578
|
-
return plans.find((plan) => typeof plan.name === "string" && plan.name.toLowerCase() === normalizedName) ?? null;
|
|
579
|
-
}
|
|
580
|
-
return null;
|
|
581
|
-
}
|
|
582
|
-
//#endregion
|
|
583
802
|
//#region src/routes.ts
|
|
584
803
|
const subaccountSchema = z.object({
|
|
585
804
|
id: z.string().min(1),
|
|
@@ -694,8 +913,13 @@ const initializeTransaction = (options, path) => createAuthEndpoint(path, {
|
|
|
694
913
|
const products = await configuredProducts(options);
|
|
695
914
|
const product = ctx.body.product ? products.find((candidate) => candidate.name.toLowerCase() === ctx.body.product?.toLowerCase() || candidate.slug === ctx.body.product) : void 0;
|
|
696
915
|
if (ctx.body.product && !product) throw new APIError("NOT_FOUND", { message: "Product not found" });
|
|
697
|
-
|
|
698
|
-
|
|
916
|
+
if (plan && product) throw new APIError("BAD_REQUEST", { message: "Select a plan or a product, not both" });
|
|
917
|
+
if (plan) {
|
|
918
|
+
if (plan.amount === void 0 || !Number.isFinite(plan.amount) || plan.amount <= 0) throw new APIError("BAD_REQUEST", { message: "The plan requires a configured positive amount" });
|
|
919
|
+
if (ctx.body.quantity > 1 && (plan.paymentPlanId != null || getPlanSeatAmount(plan) === void 0)) throw new APIError("BAD_REQUEST", { message: "Additional seats require a locally billed per-seat price" });
|
|
920
|
+
}
|
|
921
|
+
const amount = plan ? calculatePlanAmount(plan, ctx.body.quantity) : product ? product.price * ctx.body.quantity : ctx.body.amount;
|
|
922
|
+
const currency = plan ? plan.currency : product ? product.currency : ctx.body.currency;
|
|
699
923
|
if (!amount || !currency) throw new APIError("BAD_REQUEST", { message: "amount and currency are required" });
|
|
700
924
|
const requestedSplits = ctx.body.subaccounts ?? options.marketplace?.defaultSplit;
|
|
701
925
|
const allowed = new Set(options.marketplace?.allowedSubaccountIds ?? []);
|
|
@@ -778,47 +1002,16 @@ const verifyTransaction = (options, path) => createAuthEndpoint(path, {
|
|
|
778
1002
|
use: [sessionMiddleware, originCheck]
|
|
779
1003
|
}, async (ctx) => {
|
|
780
1004
|
const store = createBillingStore(ctx);
|
|
781
|
-
const expected = ctx.body.txRef ? await store.findTransactionByTxRef(ctx.body.txRef) : await store.findTransactionById(Number(ctx.body.transactionId));
|
|
782
|
-
if (!expected) throw new APIError("NOT_FOUND", { message: "Transaction not found" });
|
|
783
|
-
if (ctx.body.referenceId !== void 0 && ctx.body.referenceId !== expected.referenceId) throw new APIError("UNAUTHORIZED");
|
|
784
|
-
await authenticatedReference(ctx, options, "verify-transaction", expected.referenceId);
|
|
785
1005
|
const verified = await adapter$1(options).verifyTransaction({
|
|
786
1006
|
transactionId: ctx.body.transactionId === void 0 ? void 0 : Number(ctx.body.transactionId),
|
|
787
1007
|
txRef: ctx.body.txRef
|
|
788
1008
|
});
|
|
789
|
-
|
|
790
|
-
|
|
791
|
-
|
|
792
|
-
|
|
793
|
-
|
|
794
|
-
|
|
795
|
-
paymentType: verified.payment_type,
|
|
796
|
-
status: verified.status,
|
|
797
|
-
verifiedAt: now,
|
|
798
|
-
reconciledAt: now,
|
|
799
|
-
updatedAt: now
|
|
800
|
-
});
|
|
801
|
-
const linked = await store.findSubscriptionsByTxRef(expected.txRef);
|
|
802
|
-
for (const subscription of linked) {
|
|
803
|
-
let subscriptionId = subscription.subscriptionId;
|
|
804
|
-
if (subscription.paymentPlanId && subscription.billingEmail) {
|
|
805
|
-
const matches = (await adapter$1(options).listSubscriptions({
|
|
806
|
-
email: subscription.billingEmail,
|
|
807
|
-
plan: subscription.paymentPlanId,
|
|
808
|
-
transactionId: verified.id
|
|
809
|
-
})).filter((candidate) => candidate.status !== "cancelled");
|
|
810
|
-
subscriptionId = matches.length === 1 ? matches[0]?.id : void 0;
|
|
811
|
-
}
|
|
812
|
-
await store.updateSubscription(subscription.id, {
|
|
813
|
-
subscriptionId,
|
|
814
|
-
status: subscription.paymentPlanId !== void 0 && subscription.paymentPlanId !== null && subscriptionId === void 0 ? "incomplete" : "active",
|
|
815
|
-
encryptedPaymentToken: verified.card?.token ? await encryptPaymentToken(verified.card.token, ctx.context.secret) : subscription.encryptedPaymentToken,
|
|
816
|
-
periodStart: now,
|
|
817
|
-
reconciledAt: now,
|
|
818
|
-
updatedAt: now
|
|
819
|
-
});
|
|
820
|
-
await store.retireCompetingSubscriptions(subscription.referenceId, subscription.groupId ?? null, subscription.id);
|
|
821
|
-
}
|
|
1009
|
+
const expected = await store.findTransactionByTxRef(verified.tx_ref);
|
|
1010
|
+
if (!expected) throw new APIError("NOT_FOUND", { message: "Transaction not found" });
|
|
1011
|
+
if (ctx.body.referenceId !== void 0 && ctx.body.referenceId !== expected.referenceId) throw new APIError("UNAUTHORIZED");
|
|
1012
|
+
await authenticatedReference(ctx, options, "verify-transaction", expected.referenceId);
|
|
1013
|
+
if (ctx.body.txRef !== void 0 && verified.tx_ref !== ctx.body.txRef || !paymentMatches(expected, verified) || verified.status !== "successful") throw new APIError("BAD_REQUEST", { message: "Verified transaction does not match the expected payment" });
|
|
1014
|
+
await recordVerifiedPayment(ctx, options, expected, verified);
|
|
822
1015
|
return {
|
|
823
1016
|
status: verified.status,
|
|
824
1017
|
txRef: verified.tx_ref,
|
|
@@ -857,28 +1050,42 @@ const listSubscriptions = (options, path) => createAuthEndpoint(path, {
|
|
|
857
1050
|
return { subscriptions: await createBillingStore(ctx).findSubscriptionsByReference(referenceId) };
|
|
858
1051
|
});
|
|
859
1052
|
const subscriptionBodySchema = z.object({
|
|
860
|
-
subscriptionId: z.
|
|
1053
|
+
subscriptionId: z.union([z.number().int().positive(), z.string().min(1)]),
|
|
861
1054
|
atPeriodEnd: z.boolean().optional()
|
|
862
1055
|
});
|
|
1056
|
+
async function findSubscription(ctx, id) {
|
|
1057
|
+
const store = createBillingStore(ctx);
|
|
1058
|
+
if (typeof id === "string") {
|
|
1059
|
+
const local = await store.findSubscriptionById(id);
|
|
1060
|
+
if (local) return local;
|
|
1061
|
+
}
|
|
1062
|
+
const providerId = Number(id);
|
|
1063
|
+
return Number.isInteger(providerId) && providerId > 0 ? store.findSubscriptionByProviderId(providerId) : null;
|
|
1064
|
+
}
|
|
863
1065
|
const cancelSubscription = (options, path) => createAuthEndpoint(path, {
|
|
864
1066
|
method: "POST",
|
|
865
1067
|
body: subscriptionBodySchema,
|
|
866
1068
|
use: [sessionMiddleware, originCheck]
|
|
867
1069
|
}, async (ctx) => {
|
|
868
1070
|
const store = createBillingStore(ctx);
|
|
869
|
-
const local = await
|
|
1071
|
+
const local = await findSubscription(ctx, ctx.body.subscriptionId);
|
|
870
1072
|
if (!local) throw new APIError("NOT_FOUND", { message: "Subscription not found" });
|
|
871
1073
|
await authenticatedReference(ctx, options, "disable-subscription", local.referenceId);
|
|
872
1074
|
const now = /* @__PURE__ */ new Date();
|
|
873
1075
|
if (ctx.body.atPeriodEnd === true || options.subscription?.cancelBehavior === "at_period_end") {
|
|
1076
|
+
if (!local.periodEnd || !Number.isFinite(new Date(local.periodEnd).getTime())) throw new APIError("BAD_REQUEST", { message: "The paid subscription period is unknown; cancel immediately instead" });
|
|
1077
|
+
if (local.paymentPlanId != null && local.subscriptionId == null) throw new APIError("BAD_REQUEST", { message: "The native subscription has not been identified yet; reconcile its payment first" });
|
|
1078
|
+
if (local.subscriptionId != null && local.cancelAtPeriodEnd !== true) await adapter$1(options).cancelSubscription(local.subscriptionId);
|
|
874
1079
|
await store.updateSubscription(local.id, {
|
|
875
1080
|
cancelAtPeriodEnd: true,
|
|
876
|
-
cancelAt: local.periodEnd
|
|
1081
|
+
cancelAt: local.periodEnd,
|
|
1082
|
+
...local.subscriptionId != null ? { canceledAt: local.canceledAt ?? now } : {},
|
|
877
1083
|
updatedAt: now
|
|
878
1084
|
});
|
|
879
1085
|
return { status: "scheduled" };
|
|
880
1086
|
}
|
|
881
|
-
|
|
1087
|
+
if (local.paymentPlanId != null && local.subscriptionId == null) throw new APIError("BAD_REQUEST", { message: "The native subscription has not been identified yet; reconcile its payment first" });
|
|
1088
|
+
if (local.subscriptionId != null) await adapter$1(options).cancelSubscription(local.subscriptionId);
|
|
882
1089
|
await store.updateSubscription(local.id, {
|
|
883
1090
|
status: "canceled",
|
|
884
1091
|
cancelAtPeriodEnd: false,
|
|
@@ -894,19 +1101,26 @@ const restoreSubscription = (options, path) => createAuthEndpoint(path, {
|
|
|
894
1101
|
use: [sessionMiddleware, originCheck]
|
|
895
1102
|
}, async (ctx) => {
|
|
896
1103
|
const store = createBillingStore(ctx);
|
|
897
|
-
const local = await
|
|
1104
|
+
const local = await findSubscription(ctx, ctx.body.subscriptionId);
|
|
898
1105
|
if (!local) throw new APIError("NOT_FOUND", { message: "Subscription not found" });
|
|
899
1106
|
await authenticatedReference(ctx, options, "enable-subscription", local.referenceId);
|
|
900
|
-
|
|
1107
|
+
if (local.subscriptionId == null && local.periodEnd != null && new Date(local.periodEnd) <= /* @__PURE__ */ new Date()) throw new APIError("BAD_REQUEST", { message: "The paid period has ended; renew through checkout instead" });
|
|
1108
|
+
if (local.cancelAtPeriodEnd !== true || local.canceledAt != null) {
|
|
1109
|
+
if (local.subscriptionId == null) {
|
|
1110
|
+
if (local.status === "active" && local.endedAt == null) return { status: "active" };
|
|
1111
|
+
throw new APIError("BAD_REQUEST", { message: "A canceled local subscription requires a new checkout" });
|
|
1112
|
+
}
|
|
1113
|
+
await adapter$1(options).activateSubscription(local.subscriptionId);
|
|
1114
|
+
}
|
|
901
1115
|
await store.updateSubscription(local.id, {
|
|
902
|
-
status: "active",
|
|
1116
|
+
status: local.cancelAtPeriodEnd === true ? local.status : "active",
|
|
903
1117
|
cancelAtPeriodEnd: false,
|
|
904
1118
|
cancelAt: null,
|
|
905
1119
|
canceledAt: null,
|
|
906
1120
|
endedAt: null,
|
|
907
1121
|
updatedAt: /* @__PURE__ */ new Date()
|
|
908
1122
|
});
|
|
909
|
-
return { status: "active" };
|
|
1123
|
+
return { status: local.cancelAtPeriodEnd === true ? local.status : "active" };
|
|
910
1124
|
});
|
|
911
1125
|
const createSubscription = initializeTransaction;
|
|
912
1126
|
const upgradeSubscription = initializeTransaction;
|
|
@@ -955,11 +1169,12 @@ const flutterwaveWebhook = (options, path) => createAuthEndpoint(path, {
|
|
|
955
1169
|
}
|
|
956
1170
|
const event = parsedEvent.data;
|
|
957
1171
|
const data = event.data;
|
|
958
|
-
const eventId = createHash("sha256").update(`${event.event}:${String(data.id
|
|
1172
|
+
const eventId = createHash("sha256").update(data.id === void 0 ? rawBody : `${event.event}:${String(data.id)}:${String(data.status ?? "")}`).digest("hex");
|
|
959
1173
|
const store = createBillingStore(ctx);
|
|
960
1174
|
const existingEvent = await store.findWebhookEvent(eventId);
|
|
961
1175
|
if (existingEvent?.status === "processed") return ctx.json({ received: true });
|
|
962
1176
|
const now = /* @__PURE__ */ new Date();
|
|
1177
|
+
const busy = () => new APIError("SERVICE_UNAVAILABLE", { message: "Webhook processing is still in progress; retry delivery" });
|
|
963
1178
|
if (existingEvent === null) try {
|
|
964
1179
|
await store.createWebhookEvent({
|
|
965
1180
|
eventId,
|
|
@@ -974,60 +1189,43 @@ const flutterwaveWebhook = (options, path) => createAuthEndpoint(path, {
|
|
|
974
1189
|
} catch (error) {
|
|
975
1190
|
const concurrent = await store.findWebhookEvent(eventId);
|
|
976
1191
|
if (concurrent === null) throw error;
|
|
977
|
-
if (concurrent.status === "processed"
|
|
1192
|
+
if (concurrent.status === "processed") return ctx.json({ received: true });
|
|
1193
|
+
throw busy();
|
|
978
1194
|
}
|
|
979
|
-
else
|
|
980
|
-
|
|
981
|
-
|
|
982
|
-
|
|
983
|
-
|
|
984
|
-
|
|
985
|
-
|
|
986
|
-
|
|
987
|
-
|
|
988
|
-
|
|
989
|
-
|
|
990
|
-
|
|
991
|
-
|
|
992
|
-
|
|
993
|
-
|
|
994
|
-
|
|
995
|
-
|
|
1195
|
+
else {
|
|
1196
|
+
const leaseExpiresAt = new Date(existingEvent.updatedAt).getTime() + 3e5;
|
|
1197
|
+
if (existingEvent.status === "processing" && leaseExpiresAt > now.getTime()) throw busy();
|
|
1198
|
+
if (!await store.claimWebhookEvent(existingEvent, now)) throw busy();
|
|
1199
|
+
}
|
|
1200
|
+
try {
|
|
1201
|
+
if (data.tx_ref && data.id !== void 0) {
|
|
1202
|
+
const local = await store.findTransactionByTxRef(data.tx_ref);
|
|
1203
|
+
if (!local) throw new Error("The webhook payment has not been recorded locally yet");
|
|
1204
|
+
const verified = await adapter$1(options).verifyTransaction({ transactionId: Number(data.id) });
|
|
1205
|
+
if (data.status === "successful" && verified.status !== "successful") throw new Error("The provider has not verified the successful payment yet");
|
|
1206
|
+
await recordVerifiedPayment(ctx, options, local, verified);
|
|
1207
|
+
Object.assign(data, {
|
|
1208
|
+
id: verified.id,
|
|
1209
|
+
tx_ref: verified.tx_ref,
|
|
1210
|
+
amount: verified.amount,
|
|
1211
|
+
currency: verified.currency,
|
|
1212
|
+
status: verified.status
|
|
996
1213
|
});
|
|
997
|
-
if (verified.status === "successful") for (const subscription of await store.findSubscriptionsByTxRef(local.txRef)) {
|
|
998
|
-
let subscriptionId = subscription.subscriptionId;
|
|
999
|
-
if (subscription.paymentPlanId !== void 0 && subscription.paymentPlanId !== null && subscription.billingEmail !== void 0 && subscription.billingEmail !== null && subscription.billingEmail !== "") {
|
|
1000
|
-
const matches = (await adapter$1(options).listSubscriptions({
|
|
1001
|
-
email: subscription.billingEmail,
|
|
1002
|
-
plan: subscription.paymentPlanId,
|
|
1003
|
-
transactionId: verified.id
|
|
1004
|
-
})).filter((candidate) => candidate.status !== "cancelled");
|
|
1005
|
-
subscriptionId = matches.length === 1 ? matches[0]?.id : void 0;
|
|
1006
|
-
}
|
|
1007
|
-
await store.updateSubscription(subscription.id, {
|
|
1008
|
-
subscriptionId,
|
|
1009
|
-
status: subscription.paymentPlanId !== void 0 && subscription.paymentPlanId !== null && subscriptionId === void 0 ? "incomplete" : "active",
|
|
1010
|
-
encryptedPaymentToken: verified.card?.token !== void 0 ? await encryptPaymentToken(verified.card.token, ctx.context.secret) : subscription.encryptedPaymentToken,
|
|
1011
|
-
reconciledAt: now,
|
|
1012
|
-
updatedAt: now
|
|
1013
|
-
});
|
|
1014
|
-
await store.retireCompetingSubscriptions(subscription.referenceId, subscription.groupId ?? null, subscription.id);
|
|
1015
|
-
}
|
|
1016
1214
|
}
|
|
1215
|
+
await options.onEvent?.(event);
|
|
1216
|
+
await store.updateWebhookEvent(eventId, {
|
|
1217
|
+
status: "processed",
|
|
1218
|
+
processedAt: /* @__PURE__ */ new Date(),
|
|
1219
|
+
updatedAt: /* @__PURE__ */ new Date()
|
|
1220
|
+
});
|
|
1017
1221
|
} catch (error) {
|
|
1018
|
-
ctx.context.logger.error("Flutterwave webhook
|
|
1222
|
+
ctx.context.logger.error("Flutterwave webhook processing failed", error);
|
|
1019
1223
|
await store.updateWebhookEvent(eventId, {
|
|
1020
1224
|
status: "failed",
|
|
1021
1225
|
updatedAt: /* @__PURE__ */ new Date()
|
|
1022
1226
|
});
|
|
1023
|
-
|
|
1227
|
+
throw new APIError("SERVICE_UNAVAILABLE", { message: "Webhook processing failed; retry delivery" });
|
|
1024
1228
|
}
|
|
1025
|
-
await store.updateWebhookEvent(eventId, {
|
|
1026
|
-
status: "processed",
|
|
1027
|
-
processedAt: /* @__PURE__ */ new Date(),
|
|
1028
|
-
updatedAt: /* @__PURE__ */ new Date()
|
|
1029
|
-
});
|
|
1030
|
-
await options.onEvent?.(event);
|
|
1031
1229
|
return ctx.json({ received: true });
|
|
1032
1230
|
});
|
|
1033
1231
|
//#endregion
|
|
@@ -1499,11 +1697,13 @@ async function chargeSubscriptionRenewal(ctx, options, input) {
|
|
|
1499
1697
|
const store = createBillingStore(ctx);
|
|
1500
1698
|
const subscription = await store.findSubscriptionById(input.subscriptionId);
|
|
1501
1699
|
if (!subscription) throw new APIError("NOT_FOUND", { message: "Subscription not found" });
|
|
1700
|
+
if (subscription.status === "canceled" || subscription.endedAt != null || subscription.cancelAtPeriodEnd && subscription.cancelAt && new Date(subscription.cancelAt) <= /* @__PURE__ */ new Date()) throw new APIError("BAD_REQUEST", { message: "Canceled subscriptions cannot be renewed" });
|
|
1701
|
+
if (subscription.paymentPlanId != null || subscription.subscriptionId != null) throw new APIError("BAD_REQUEST", { message: "Native subscription renewals are managed by Flutterwave" });
|
|
1502
1702
|
const plan = await store.findPlanByName(subscription.plan) ?? await (async () => {
|
|
1503
1703
|
const configured = options.subscription?.plans;
|
|
1504
1704
|
return (typeof configured === "function" ? await configured() : configured ?? []).find((candidate) => candidate.name === subscription.plan) ?? null;
|
|
1505
1705
|
})();
|
|
1506
|
-
const amount = input.amount ?? plan
|
|
1706
|
+
const amount = input.amount ?? (plan ? calculatePlanAmount(plan, subscription.seats) : void 0);
|
|
1507
1707
|
if (!amount || !plan?.currency || !subscription.billingEmail) throw new APIError("BAD_REQUEST", { message: "Subscription billing details are incomplete" });
|
|
1508
1708
|
const txRef = `flw_renewal_${crypto.randomUUID()}`;
|
|
1509
1709
|
const metadata = stringifyFlutterwaveMetadata(createRenewalMetadata({
|
|
@@ -1559,7 +1759,7 @@ async function chargeSubscriptionRenewal(ctx, options, input) {
|
|
|
1559
1759
|
const verified = await adapter(options).verifyTransaction({ transactionId: charged.id });
|
|
1560
1760
|
if (verified.tx_ref !== txRef || verified.amount !== amount || verified.currency !== plan.currency) throw new APIError("BAD_REQUEST", { message: "Tokenized renewal did not match the expected payment" });
|
|
1561
1761
|
const now = /* @__PURE__ */ new Date();
|
|
1562
|
-
await store.createTransaction({
|
|
1762
|
+
const transaction = await store.createTransaction({
|
|
1563
1763
|
txRef,
|
|
1564
1764
|
transactionId: verified.id,
|
|
1565
1765
|
flwRef: verified.flw_ref,
|
|
@@ -1568,21 +1768,20 @@ async function chargeSubscriptionRenewal(ctx, options, input) {
|
|
|
1568
1768
|
amount,
|
|
1569
1769
|
chargedAmount: verified.charged_amount,
|
|
1570
1770
|
currency: plan.currency,
|
|
1571
|
-
status:
|
|
1771
|
+
status: "pending",
|
|
1572
1772
|
plan: subscription.plan,
|
|
1573
1773
|
paymentType: verified.payment_type,
|
|
1574
1774
|
metadata,
|
|
1575
|
-
verifiedAt: now,
|
|
1576
|
-
reconciledAt: now,
|
|
1577
1775
|
createdAt: now,
|
|
1578
1776
|
updatedAt: now
|
|
1579
1777
|
});
|
|
1580
1778
|
await store.updateSubscription(subscription.id, {
|
|
1581
1779
|
txRef,
|
|
1582
|
-
status:
|
|
1780
|
+
status: "past_due",
|
|
1583
1781
|
reconciledAt: now,
|
|
1584
1782
|
updatedAt: now
|
|
1585
1783
|
});
|
|
1784
|
+
await recordVerifiedPayment(ctx, options, transaction, verified);
|
|
1586
1785
|
return {
|
|
1587
1786
|
status: verified.status === "successful" ? "success" : "failed",
|
|
1588
1787
|
data: {
|
|
@@ -1597,6 +1796,28 @@ async function chargeSubscriptionRenewal(ctx, options, input) {
|
|
|
1597
1796
|
}
|
|
1598
1797
|
};
|
|
1599
1798
|
}
|
|
1799
|
+
/** Call from an independently authorized scheduled job; no browser endpoint is exposed. */
|
|
1800
|
+
async function processScheduledFlutterwaveCancellations(ctx, options, input = {}) {
|
|
1801
|
+
const now = input.now ?? /* @__PURE__ */ new Date();
|
|
1802
|
+
const limit = input.limit ?? 100;
|
|
1803
|
+
if (!Number.isFinite(now.getTime()) || !Number.isInteger(limit) || limit < 1 || limit > 1e3) throw new APIError("BAD_REQUEST", { message: "A valid time and limit from 1 to 1000 are required" });
|
|
1804
|
+
const store = createBillingStore(ctx);
|
|
1805
|
+
const due = await store.listDueCancellations(now, limit);
|
|
1806
|
+
const failed = [];
|
|
1807
|
+
let canceled = 0;
|
|
1808
|
+
for (const subscription of due) try {
|
|
1809
|
+
if (subscription.paymentPlanId != null && subscription.subscriptionId == null) throw new Error("Native subscription has not been identified");
|
|
1810
|
+
if (subscription.subscriptionId != null && subscription.status !== "canceled" && subscription.canceledAt == null) await adapter(options).cancelSubscription(subscription.subscriptionId);
|
|
1811
|
+
if (await store.completeScheduledCancellation(subscription, now)) canceled++;
|
|
1812
|
+
} catch {
|
|
1813
|
+
failed.push(subscription.id);
|
|
1814
|
+
}
|
|
1815
|
+
return {
|
|
1816
|
+
canceled,
|
|
1817
|
+
failed,
|
|
1818
|
+
hasMore: due.length === limit
|
|
1819
|
+
};
|
|
1820
|
+
}
|
|
1600
1821
|
function parseMetadata(value) {
|
|
1601
1822
|
if (!value) return void 0;
|
|
1602
1823
|
return JSON.parse(value);
|
|
@@ -1636,7 +1857,7 @@ async function reconcileFlutterwaveTransaction(ctx, options, input) {
|
|
|
1636
1857
|
txRef: input.txRef,
|
|
1637
1858
|
transactionId: input.transactionId
|
|
1638
1859
|
});
|
|
1639
|
-
if (!(
|
|
1860
|
+
if (!paymentMatches(local, verified)) {
|
|
1640
1861
|
if (input.throwOnError === false) return {
|
|
1641
1862
|
ok: false,
|
|
1642
1863
|
source: input.source ?? "server",
|
|
@@ -1648,22 +1869,7 @@ async function reconcileFlutterwaveTransaction(ctx, options, input) {
|
|
|
1648
1869
|
};
|
|
1649
1870
|
throw new APIError("BAD_REQUEST", { message: "Transaction details do not match" });
|
|
1650
1871
|
}
|
|
1651
|
-
|
|
1652
|
-
await store.updateTransactionByTxRef(local.txRef, {
|
|
1653
|
-
transactionId: verified.id,
|
|
1654
|
-
flwRef: verified.flw_ref,
|
|
1655
|
-
chargedAmount: verified.charged_amount,
|
|
1656
|
-
paymentType: verified.payment_type,
|
|
1657
|
-
status: verified.status,
|
|
1658
|
-
verifiedAt: now,
|
|
1659
|
-
reconciledAt: now,
|
|
1660
|
-
updatedAt: now
|
|
1661
|
-
});
|
|
1662
|
-
for (const subscription of await store.findSubscriptionsByTxRef(local.txRef)) await store.updateSubscription(subscription.id, {
|
|
1663
|
-
status: verified.status === "successful" ? "active" : subscription.status,
|
|
1664
|
-
reconciledAt: now,
|
|
1665
|
-
updatedAt: now
|
|
1666
|
-
});
|
|
1872
|
+
await recordVerifiedPayment(ctx, options, local, verified);
|
|
1667
1873
|
const data = {
|
|
1668
1874
|
id: verified.id,
|
|
1669
1875
|
txRef: verified.tx_ref,
|
|
@@ -1747,6 +1953,6 @@ const flutterwave = (options) => {
|
|
|
1747
1953
|
};
|
|
1748
1954
|
};
|
|
1749
1955
|
//#endregion
|
|
1750
|
-
export { FlutterwaveAdapterError, chargeSubscriptionRenewal, checkSeatLimit, checkTeamLimit, createCheckoutMetadata, createFlutterwaveAdapter, createProrationMetadata, createRenewalMetadata, decryptPaymentToken, encryptPaymentToken, flutterwave, getMetadataBoolean, getMetadataNumber, getMetadataString, getOrganizationEntitlements, hasFlutterwaveMetadata, parseFlutterwaveMetadata, reconcileFlutterwaveRefunds, reconcileFlutterwaveTransaction, refundFlutterwaveTransaction, stringifyFlutterwaveMetadata, syncFlutterwavePlans };
|
|
1956
|
+
export { FlutterwaveAdapterError, chargeSubscriptionRenewal, checkSeatLimit, checkTeamLimit, createCheckoutMetadata, createFlutterwaveAdapter, createProrationMetadata, createRenewalMetadata, decryptPaymentToken, encryptPaymentToken, flutterwave, getMetadataBoolean, getMetadataNumber, getMetadataString, getOrganizationEntitlements, hasFlutterwaveMetadata, parseFlutterwaveMetadata, processScheduledFlutterwaveCancellations, reconcileFlutterwaveRefunds, reconcileFlutterwaveTransaction, refundFlutterwaveTransaction, stringifyFlutterwaveMetadata, syncFlutterwavePlans };
|
|
1751
1957
|
|
|
1752
1958
|
//# sourceMappingURL=index.mjs.map
|