better-auth-flutterwave 0.1.10 → 0.3.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +53 -16
- 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-zC8Dbzqo.d.mts} +57 -40
- package/dist/index-zC8Dbzqo.d.mts.map +1 -0
- package/dist/index.d.mts +2 -2
- package/dist/index.mjs +429 -185
- package/dist/index.mjs.map +1 -1
- package/dist/{version-BKseik7h.mjs → version-mllGPygP.mjs} +2 -2
- package/dist/{version-BKseik7h.mjs.map → version-mllGPygP.mjs.map} +1 -1
- package/package.json +16 -32
- 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,8 +1,7 @@
|
|
|
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-
|
|
2
|
-
import { createRequire } from "node:module";
|
|
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-mllGPygP.mjs";
|
|
3
2
|
import { HIDE_METADATA, defineErrorCodes } from "better-auth";
|
|
4
3
|
import { createHash, timingSafeEqual } from "node:crypto";
|
|
5
|
-
import { APIError, createAuthEndpoint, getSessionFromCtx,
|
|
4
|
+
import { APIError, createAuthEndpoint, getSessionFromCtx, originCheckMiddleware, sessionMiddleware } from "better-auth/api";
|
|
6
5
|
import * as z from "zod";
|
|
7
6
|
import { Buffer } from "node:buffer";
|
|
8
7
|
import { mergeSchema } from "better-auth/db";
|
|
@@ -51,10 +50,17 @@ function createBillingStoreFromAdapter(adapter) {
|
|
|
51
50
|
},
|
|
52
51
|
async retireCompetingSubscriptions(referenceId, groupId, exceptId) {
|
|
53
52
|
const candidates = await this.findSubscriptionsByReference(referenceId);
|
|
53
|
+
const current = candidates.find(({ id }) => id === exceptId);
|
|
54
|
+
if (!current) return;
|
|
54
55
|
const now = /* @__PURE__ */ new Date();
|
|
55
56
|
for (const candidate of candidates) {
|
|
56
57
|
const sameGroup = groupId === null ? candidate.groupId === void 0 || candidate.groupId === null || candidate.groupId === "" : candidate.groupId === groupId;
|
|
57
|
-
if (candidate.id !== exceptId &&
|
|
58
|
+
if (candidate.id !== exceptId && new Date(candidate.createdAt).getTime() <= new Date(current.createdAt).getTime() && sameGroup && [
|
|
59
|
+
"active",
|
|
60
|
+
"trialing",
|
|
61
|
+
"incomplete",
|
|
62
|
+
"past_due"
|
|
63
|
+
].includes(candidate.status)) await this.updateSubscription(candidate.id, {
|
|
58
64
|
status: "canceled",
|
|
59
65
|
cancelAtPeriodEnd: false,
|
|
60
66
|
canceledAt: now,
|
|
@@ -67,6 +73,48 @@ function createBillingStoreFromAdapter(adapter) {
|
|
|
67
73
|
field: "txRef",
|
|
68
74
|
value: txRef
|
|
69
75
|
}]),
|
|
76
|
+
listDueCancellations: (now, limit) => adapter.findMany({
|
|
77
|
+
model: "flutterwaveSubscription",
|
|
78
|
+
where: [{
|
|
79
|
+
field: "cancelAtPeriodEnd",
|
|
80
|
+
value: true
|
|
81
|
+
}, {
|
|
82
|
+
field: "cancelAt",
|
|
83
|
+
value: now,
|
|
84
|
+
operator: "lte"
|
|
85
|
+
}],
|
|
86
|
+
sortBy: {
|
|
87
|
+
field: "cancelAt",
|
|
88
|
+
direction: "asc"
|
|
89
|
+
},
|
|
90
|
+
limit
|
|
91
|
+
}),
|
|
92
|
+
async completeScheduledCancellation(subscription, now) {
|
|
93
|
+
return await adapter.updateMany({
|
|
94
|
+
model: "flutterwaveSubscription",
|
|
95
|
+
where: [
|
|
96
|
+
{
|
|
97
|
+
field: "id",
|
|
98
|
+
value: subscription.id
|
|
99
|
+
},
|
|
100
|
+
{
|
|
101
|
+
field: "cancelAtPeriodEnd",
|
|
102
|
+
value: true
|
|
103
|
+
},
|
|
104
|
+
{
|
|
105
|
+
field: "cancelAt",
|
|
106
|
+
value: subscription.cancelAt == null ? null : new Date(subscription.cancelAt)
|
|
107
|
+
}
|
|
108
|
+
],
|
|
109
|
+
update: {
|
|
110
|
+
status: "canceled",
|
|
111
|
+
cancelAtPeriodEnd: false,
|
|
112
|
+
canceledAt: subscription.canceledAt ?? now,
|
|
113
|
+
endedAt: subscription.cancelAt ?? now,
|
|
114
|
+
updatedAt: now
|
|
115
|
+
}
|
|
116
|
+
}) === 1;
|
|
117
|
+
},
|
|
70
118
|
createSubscription: (data) => adapter.create({
|
|
71
119
|
model: "flutterwaveSubscription",
|
|
72
120
|
data
|
|
@@ -79,6 +127,26 @@ function createBillingStoreFromAdapter(adapter) {
|
|
|
79
127
|
value: id
|
|
80
128
|
}]
|
|
81
129
|
}),
|
|
130
|
+
async updateCurrentSubscription(subscription, update) {
|
|
131
|
+
return await adapter.updateMany({
|
|
132
|
+
model: "flutterwaveSubscription",
|
|
133
|
+
where: [
|
|
134
|
+
{
|
|
135
|
+
field: "id",
|
|
136
|
+
value: subscription.id
|
|
137
|
+
},
|
|
138
|
+
{
|
|
139
|
+
field: "status",
|
|
140
|
+
value: subscription.status
|
|
141
|
+
},
|
|
142
|
+
{
|
|
143
|
+
field: "txRef",
|
|
144
|
+
value: subscription.txRef ?? null
|
|
145
|
+
}
|
|
146
|
+
],
|
|
147
|
+
update
|
|
148
|
+
}) === 1;
|
|
149
|
+
},
|
|
82
150
|
updateSubscriptionByProviderId: (subscriptionId, update) => adapter.update({
|
|
83
151
|
model: "flutterwaveSubscription",
|
|
84
152
|
update,
|
|
@@ -192,6 +260,29 @@ function createBillingStoreFromAdapter(adapter) {
|
|
|
192
260
|
value: eventId
|
|
193
261
|
}]
|
|
194
262
|
}),
|
|
263
|
+
async claimWebhookEvent(event, now) {
|
|
264
|
+
return await adapter.updateMany({
|
|
265
|
+
model: "flutterwaveWebhookEvent",
|
|
266
|
+
where: [
|
|
267
|
+
{
|
|
268
|
+
field: "eventId",
|
|
269
|
+
value: event.eventId
|
|
270
|
+
},
|
|
271
|
+
{
|
|
272
|
+
field: "status",
|
|
273
|
+
value: event.status
|
|
274
|
+
},
|
|
275
|
+
{
|
|
276
|
+
field: "updatedAt",
|
|
277
|
+
value: new Date(event.updatedAt)
|
|
278
|
+
}
|
|
279
|
+
],
|
|
280
|
+
update: {
|
|
281
|
+
status: "processing",
|
|
282
|
+
updatedAt: now
|
|
283
|
+
}
|
|
284
|
+
}) === 1;
|
|
285
|
+
},
|
|
195
286
|
createRefund: (data) => adapter.create({
|
|
196
287
|
model: "flutterwaveRefund",
|
|
197
288
|
data
|
|
@@ -342,8 +433,48 @@ var FlutterwaveAdapterError = class extends Error {
|
|
|
342
433
|
this.cause = options?.cause;
|
|
343
434
|
}
|
|
344
435
|
};
|
|
345
|
-
function
|
|
346
|
-
|
|
436
|
+
function queryString(input) {
|
|
437
|
+
const query = new URLSearchParams();
|
|
438
|
+
for (const [key, value] of Object.entries(input)) if (typeof value === "string" || typeof value === "number" || typeof value === "boolean") query.set(key, String(value));
|
|
439
|
+
const serialized = query.toString();
|
|
440
|
+
return serialized.length === 0 ? "" : `?${serialized}`;
|
|
441
|
+
}
|
|
442
|
+
function createHttpClient(fetchImpl, apiBaseUrl, secretKey) {
|
|
443
|
+
const request = async (path, method = "GET", body) => {
|
|
444
|
+
if (typeof fetchImpl !== "function") throw new Error("Fetch is not available");
|
|
445
|
+
const response = await fetchImpl(`${apiBaseUrl}${path}`, {
|
|
446
|
+
method,
|
|
447
|
+
headers: {
|
|
448
|
+
accept: "application/json",
|
|
449
|
+
authorization: `Bearer ${secretKey}`,
|
|
450
|
+
"content-type": "application/json"
|
|
451
|
+
},
|
|
452
|
+
...body === void 0 ? {} : { body: JSON.stringify(body) }
|
|
453
|
+
});
|
|
454
|
+
let raw;
|
|
455
|
+
try {
|
|
456
|
+
raw = await response.json();
|
|
457
|
+
} catch {
|
|
458
|
+
throw new Error(`Flutterwave returned a non-JSON response (HTTP ${response.status})`);
|
|
459
|
+
}
|
|
460
|
+
if (!response.ok) throw new Error(messageFromUnknown(raw) ?? `Flutterwave request failed with HTTP ${response.status}`);
|
|
461
|
+
return raw;
|
|
462
|
+
};
|
|
463
|
+
const post = (path, body) => request(path, "POST", body);
|
|
464
|
+
return {
|
|
465
|
+
Transaction: {
|
|
466
|
+
verify: ({ id }) => request(`/v3/transactions/${id}/verify`),
|
|
467
|
+
verify_by_tx: ({ tx_ref }) => request(`/v3/transactions/verify_by_reference${queryString({ tx_ref })}`),
|
|
468
|
+
refund: ({ id, amount }) => post(`/v3/transactions/${id}/refund`, amount === void 0 ? {} : { amount })
|
|
469
|
+
},
|
|
470
|
+
PaymentPlan: { get_all: (query) => request(`/v3/payment-plans${queryString(query)}`) },
|
|
471
|
+
Subscription: {
|
|
472
|
+
fetch_all: (query) => request(`/v3/subscriptions${queryString(query)}`),
|
|
473
|
+
cancel: ({ id }) => request(`/v3/subscriptions/${id}/cancel`, "PUT"),
|
|
474
|
+
activate: ({ id }) => request(`/v3/subscriptions/${id}/activate`, "PUT")
|
|
475
|
+
},
|
|
476
|
+
Tokenized: { charge: (input) => post("/v3/tokenized-charges", input) }
|
|
477
|
+
};
|
|
347
478
|
}
|
|
348
479
|
function messageFromUnknown(value) {
|
|
349
480
|
if (typeof value === "string") return value;
|
|
@@ -370,17 +501,19 @@ const optionalPositiveAmountSchema = z.number().positive().optional();
|
|
|
370
501
|
/**
|
|
371
502
|
* Creates the provider boundary used by the plugin.
|
|
372
503
|
*
|
|
373
|
-
*
|
|
374
|
-
*
|
|
375
|
-
*
|
|
376
|
-
* required. This adapter intentionally uses only the SDK's Promise API.
|
|
504
|
+
* Uses Flutterwave's v3 HTTP API directly so applications do not need a separate
|
|
505
|
+
* SDK dependency. Inject `flutterwaveClient` for a custom provider boundary or
|
|
506
|
+
* `fetch` for controlled transport and tests.
|
|
377
507
|
*/
|
|
378
508
|
function createFlutterwaveAdapter(options) {
|
|
379
509
|
if (!options.publicKey) throw new FlutterwaveAdapterError("configuration", "publicKey is required");
|
|
380
510
|
if (!options.secretKey) throw new FlutterwaveAdapterError("configuration", "secretKey is required");
|
|
381
|
-
const client = options.flutterwaveClient ?? createSdkClient(options.publicKey, options.secretKey);
|
|
382
511
|
const fetchImpl = options.fetch ?? globalThis.fetch;
|
|
383
|
-
const
|
|
512
|
+
const configuredApiBaseUrl = options.apiBaseUrl ?? "https://api.flutterwave.com";
|
|
513
|
+
let end = configuredApiBaseUrl.length;
|
|
514
|
+
while (end > 0 && configuredApiBaseUrl.charCodeAt(end - 1) === 47) end--;
|
|
515
|
+
const apiBaseUrl = configuredApiBaseUrl.slice(0, end);
|
|
516
|
+
const client = options.flutterwaveClient ?? createHttpClient(fetchImpl, apiBaseUrl, options.secretKey);
|
|
384
517
|
return {
|
|
385
518
|
async initializePayment(input) {
|
|
386
519
|
const body = standardCheckoutInputSchema.parse(input);
|
|
@@ -438,6 +571,182 @@ function createFlutterwaveAdapter(options) {
|
|
|
438
571
|
};
|
|
439
572
|
}
|
|
440
573
|
//#endregion
|
|
574
|
+
//#region src/token-crypto.ts
|
|
575
|
+
const encoder = new TextEncoder();
|
|
576
|
+
const decoder = new TextDecoder();
|
|
577
|
+
function toBase64(value) {
|
|
578
|
+
return Buffer.from(value).toString("base64url");
|
|
579
|
+
}
|
|
580
|
+
function fromBase64(value) {
|
|
581
|
+
return new Uint8Array(Buffer.from(value, "base64url"));
|
|
582
|
+
}
|
|
583
|
+
async function deriveKey(secret) {
|
|
584
|
+
const digest = await crypto.subtle.digest("SHA-256", encoder.encode(secret));
|
|
585
|
+
return crypto.subtle.importKey("raw", digest, "AES-GCM", false, ["encrypt", "decrypt"]);
|
|
586
|
+
}
|
|
587
|
+
async function encryptPaymentToken(token, secret) {
|
|
588
|
+
const iv = crypto.getRandomValues(/* @__PURE__ */ new Uint8Array(12));
|
|
589
|
+
const encrypted = await crypto.subtle.encrypt({
|
|
590
|
+
name: "AES-GCM",
|
|
591
|
+
iv
|
|
592
|
+
}, await deriveKey(secret), encoder.encode(token));
|
|
593
|
+
return `v1.${toBase64(iv)}.${toBase64(new Uint8Array(encrypted))}`;
|
|
594
|
+
}
|
|
595
|
+
async function decryptPaymentToken(value, secret) {
|
|
596
|
+
const [version, encodedIv, encodedCiphertext] = value.split(".");
|
|
597
|
+
if (version !== "v1" || !encodedIv || !encodedCiphertext) throw new Error("Unsupported encrypted payment token");
|
|
598
|
+
const iv = Uint8Array.from(fromBase64(encodedIv));
|
|
599
|
+
const ciphertext = Uint8Array.from(fromBase64(encodedCiphertext));
|
|
600
|
+
const decrypted = await crypto.subtle.decrypt({
|
|
601
|
+
name: "AES-GCM",
|
|
602
|
+
iv
|
|
603
|
+
}, await deriveKey(secret), ciphertext);
|
|
604
|
+
return decoder.decode(decrypted);
|
|
605
|
+
}
|
|
606
|
+
//#endregion
|
|
607
|
+
//#region src/utils.ts
|
|
608
|
+
function getPlanSeatAmount(plan) {
|
|
609
|
+
if (plan.seatAmount !== void 0) {
|
|
610
|
+
if (typeof plan.seatAmount === "number" && Number.isFinite(plan.seatAmount) && plan.seatAmount >= 0) return plan.seatAmount;
|
|
611
|
+
throw new Error(`Invalid seatAmount for plan '${plan.name}'. Expected a finite number.`);
|
|
612
|
+
}
|
|
613
|
+
if (plan.seatPriceId === void 0 || plan.seatPriceId === null || plan.seatPriceId === "") return;
|
|
614
|
+
const parsed = typeof plan.seatPriceId === "string" ? Number(plan.seatPriceId) : plan.seatPriceId;
|
|
615
|
+
if (typeof parsed === "number" && Number.isFinite(parsed) && parsed >= 0) return parsed;
|
|
616
|
+
throw new Error(`Invalid seatPriceId for plan '${plan.name}'. Expected a numeric amount in the smallest currency unit.`);
|
|
617
|
+
}
|
|
618
|
+
function calculatePlanAmount(plan, quantity) {
|
|
619
|
+
return (plan.amount ?? 0) + Math.max(0, quantity - 1) * (getPlanSeatAmount(plan) ?? 0);
|
|
620
|
+
}
|
|
621
|
+
function normalizeSubscriptionGroup(group) {
|
|
622
|
+
const normalized = group?.trim().toLowerCase();
|
|
623
|
+
return normalized === void 0 || normalized === "" ? null : normalized;
|
|
624
|
+
}
|
|
625
|
+
async function getPlans(subscriptionOptions) {
|
|
626
|
+
if (subscriptionOptions?.enabled === true) return typeof subscriptionOptions.plans === "function" ? subscriptionOptions.plans() : subscriptionOptions.plans;
|
|
627
|
+
return [];
|
|
628
|
+
}
|
|
629
|
+
async function getPlanByName(options, name) {
|
|
630
|
+
if (typeof name !== "string" || name.trim() === "") return null;
|
|
631
|
+
if (options.subscription?.enabled === true) {
|
|
632
|
+
const plans = await getPlans(options.subscription);
|
|
633
|
+
const normalizedName = name.toLowerCase();
|
|
634
|
+
return plans.find((plan) => typeof plan.name === "string" && plan.name.toLowerCase() === normalizedName) ?? null;
|
|
635
|
+
}
|
|
636
|
+
return null;
|
|
637
|
+
}
|
|
638
|
+
function getNextPeriodEnd(startDate, interval) {
|
|
639
|
+
const date = new Date(startDate);
|
|
640
|
+
const day = date.getUTCDate();
|
|
641
|
+
const addMonths = (months) => {
|
|
642
|
+
date.setUTCDate(1);
|
|
643
|
+
date.setUTCMonth(date.getUTCMonth() + months);
|
|
644
|
+
const lastDay = new Date(Date.UTC(date.getUTCFullYear(), date.getUTCMonth() + 1, 0)).getUTCDate();
|
|
645
|
+
date.setUTCDate(Math.min(day, lastDay));
|
|
646
|
+
};
|
|
647
|
+
switch (interval) {
|
|
648
|
+
case "hourly":
|
|
649
|
+
date.setUTCHours(date.getUTCHours() + 1);
|
|
650
|
+
break;
|
|
651
|
+
case "daily":
|
|
652
|
+
date.setUTCDate(date.getUTCDate() + 1);
|
|
653
|
+
break;
|
|
654
|
+
case "weekly":
|
|
655
|
+
date.setUTCDate(date.getUTCDate() + 7);
|
|
656
|
+
break;
|
|
657
|
+
case "monthly":
|
|
658
|
+
addMonths(1);
|
|
659
|
+
break;
|
|
660
|
+
case "quarterly":
|
|
661
|
+
addMonths(3);
|
|
662
|
+
break;
|
|
663
|
+
case "biannually":
|
|
664
|
+
case "bi-annually":
|
|
665
|
+
addMonths(6);
|
|
666
|
+
break;
|
|
667
|
+
case "annually":
|
|
668
|
+
case "yearly":
|
|
669
|
+
addMonths(12);
|
|
670
|
+
break;
|
|
671
|
+
default: {
|
|
672
|
+
const recurring = /^every (\d+) (hours?|days?|weeks?|months?|years?)$/.exec(interval);
|
|
673
|
+
if (!recurring) return null;
|
|
674
|
+
const count = Number(recurring[1]);
|
|
675
|
+
if (!Number.isSafeInteger(count) || count < 1) return null;
|
|
676
|
+
const unit = recurring[2];
|
|
677
|
+
if (unit?.startsWith("hour")) date.setUTCHours(date.getUTCHours() + count);
|
|
678
|
+
else if (unit?.startsWith("day")) date.setUTCDate(date.getUTCDate() + count);
|
|
679
|
+
else if (unit?.startsWith("week")) date.setUTCDate(date.getUTCDate() + count * 7);
|
|
680
|
+
else addMonths(count * (unit?.startsWith("year") ? 12 : 1));
|
|
681
|
+
if (!Number.isFinite(date.getTime())) return null;
|
|
682
|
+
}
|
|
683
|
+
}
|
|
684
|
+
return date;
|
|
685
|
+
}
|
|
686
|
+
//#endregion
|
|
687
|
+
//#region src/billing-lifecycle.ts
|
|
688
|
+
function paymentMatches(expected, verified) {
|
|
689
|
+
return verified.tx_ref === expected.txRef && verified.amount === expected.amount && verified.currency === expected.currency;
|
|
690
|
+
}
|
|
691
|
+
/** Shared fulfillment for browser verification, webhooks, and trusted reconciliation. */
|
|
692
|
+
async function recordVerifiedPayment(ctx, options, expected, verified) {
|
|
693
|
+
if (!paymentMatches(expected, verified)) throw new APIError("BAD_REQUEST", { message: "Verified transaction does not match the expected payment" });
|
|
694
|
+
const store = createBillingStore(ctx);
|
|
695
|
+
const now = /* @__PURE__ */ new Date();
|
|
696
|
+
if (expected.status === "successful" && verified.status !== "successful") return;
|
|
697
|
+
await store.updateTransactionByTxRef(expected.txRef, {
|
|
698
|
+
transactionId: verified.id,
|
|
699
|
+
flwRef: verified.flw_ref,
|
|
700
|
+
chargedAmount: verified.charged_amount,
|
|
701
|
+
paymentType: verified.payment_type,
|
|
702
|
+
status: verified.status,
|
|
703
|
+
verifiedAt: expected.verifiedAt ?? now,
|
|
704
|
+
reconciledAt: now,
|
|
705
|
+
updatedAt: now
|
|
706
|
+
});
|
|
707
|
+
if (verified.status !== "successful" || options.subscription?.enabled !== true) return;
|
|
708
|
+
for (const subscription of await store.findSubscriptionsByTxRef(expected.txRef)) {
|
|
709
|
+
if (subscription.status === "canceled" || subscription.endedAt != null) continue;
|
|
710
|
+
const group = normalizeSubscriptionGroup(subscription.groupId);
|
|
711
|
+
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())) {
|
|
712
|
+
await store.updateSubscription(subscription.id, {
|
|
713
|
+
status: "canceled",
|
|
714
|
+
canceledAt: now,
|
|
715
|
+
endedAt: now,
|
|
716
|
+
updatedAt: now
|
|
717
|
+
});
|
|
718
|
+
continue;
|
|
719
|
+
}
|
|
720
|
+
let subscriptionId = subscription.subscriptionId;
|
|
721
|
+
if (subscription.paymentPlanId != null && subscriptionId == null && subscription.billingEmail != null && subscription.billingEmail !== "") {
|
|
722
|
+
const candidates = (await createFlutterwaveAdapter(options).listSubscriptions({
|
|
723
|
+
email: subscription.billingEmail,
|
|
724
|
+
plan: subscription.paymentPlanId,
|
|
725
|
+
transactionId: verified.id
|
|
726
|
+
})).filter((candidate) => candidate.status !== "cancelled");
|
|
727
|
+
subscriptionId = candidates.length === 1 ? candidates[0]?.id : void 0;
|
|
728
|
+
}
|
|
729
|
+
const identified = subscription.paymentPlanId == null || subscriptionId != null;
|
|
730
|
+
const paidAt = verified.created_at != null && verified.created_at !== "" ? new Date(verified.created_at) : now;
|
|
731
|
+
const paymentTime = Number.isFinite(paidAt.getTime()) ? paidAt : now;
|
|
732
|
+
const renewal = parseFlutterwaveMetadata(expected.metadata).type === "renewal";
|
|
733
|
+
const priorEnd = subscription.periodEnd ? new Date(subscription.periodEnd) : null;
|
|
734
|
+
const periodStart = renewal && priorEnd !== null && priorEnd > paymentTime ? priorEnd : paymentTime;
|
|
735
|
+
const advancePeriod = subscription.periodEnd == null || (renewal ? subscription.status === "past_due" : expected.status !== "successful");
|
|
736
|
+
if (await store.updateCurrentSubscription(subscription, {
|
|
737
|
+
subscriptionId,
|
|
738
|
+
status: identified ? "active" : "incomplete",
|
|
739
|
+
encryptedPaymentToken: verified.card?.token !== void 0 ? await encryptPaymentToken(verified.card.token, ctx.context.secret) : subscription.encryptedPaymentToken,
|
|
740
|
+
...advancePeriod ? {
|
|
741
|
+
periodStart,
|
|
742
|
+
periodEnd: getNextPeriodEnd(periodStart, subscription.billingInterval ?? "monthly")
|
|
743
|
+
} : {},
|
|
744
|
+
reconciledAt: now,
|
|
745
|
+
updatedAt: now
|
|
746
|
+
}) && identified) await store.retireCompetingSubscriptions(subscription.referenceId, group, subscription.id);
|
|
747
|
+
}
|
|
748
|
+
}
|
|
749
|
+
//#endregion
|
|
441
750
|
//#region src/reference-access.ts
|
|
442
751
|
const DEFAULT_BILLING_ORG_ROLES = ["owner", "admin"];
|
|
443
752
|
function normalizeBillingRoles(roles) {
|
|
@@ -528,58 +837,6 @@ function timingSafeEqualString(left, right) {
|
|
|
528
837
|
return timingSafeEqual(leftBytes, rightBytes);
|
|
529
838
|
}
|
|
530
839
|
//#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
840
|
//#region src/routes.ts
|
|
584
841
|
const subaccountSchema = z.object({
|
|
585
842
|
id: z.string().min(1),
|
|
@@ -683,7 +940,7 @@ async function configuredProducts(options) {
|
|
|
683
940
|
const initializeTransaction = (options, path) => createAuthEndpoint(path, {
|
|
684
941
|
method: "POST",
|
|
685
942
|
body: initializeBodySchema,
|
|
686
|
-
use: [sessionMiddleware,
|
|
943
|
+
use: [sessionMiddleware, originCheckMiddleware]
|
|
687
944
|
}, async (ctx) => {
|
|
688
945
|
const { user, referenceId } = await authenticatedReference(ctx, options, "initialize-transaction", ctx.body.referenceId);
|
|
689
946
|
if (options.subscription?.requireEmailVerification === true && ctx.body.plan && user.emailVerified !== true) throw new APIError("BAD_REQUEST", FLUTTERWAVE_ERROR_CODES.EMAIL_VERIFICATION_REQUIRED);
|
|
@@ -694,8 +951,13 @@ const initializeTransaction = (options, path) => createAuthEndpoint(path, {
|
|
|
694
951
|
const products = await configuredProducts(options);
|
|
695
952
|
const product = ctx.body.product ? products.find((candidate) => candidate.name.toLowerCase() === ctx.body.product?.toLowerCase() || candidate.slug === ctx.body.product) : void 0;
|
|
696
953
|
if (ctx.body.product && !product) throw new APIError("NOT_FOUND", { message: "Product not found" });
|
|
697
|
-
|
|
698
|
-
|
|
954
|
+
if (plan && product) throw new APIError("BAD_REQUEST", { message: "Select a plan or a product, not both" });
|
|
955
|
+
if (plan) {
|
|
956
|
+
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" });
|
|
957
|
+
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" });
|
|
958
|
+
}
|
|
959
|
+
const amount = plan ? calculatePlanAmount(plan, ctx.body.quantity) : product ? product.price * ctx.body.quantity : ctx.body.amount;
|
|
960
|
+
const currency = plan ? plan.currency : product ? product.currency : ctx.body.currency;
|
|
699
961
|
if (!amount || !currency) throw new APIError("BAD_REQUEST", { message: "amount and currency are required" });
|
|
700
962
|
const requestedSplits = ctx.body.subaccounts ?? options.marketplace?.defaultSplit;
|
|
701
963
|
const allowed = new Set(options.marketplace?.allowedSubaccountIds ?? []);
|
|
@@ -775,50 +1037,19 @@ const initializeTransaction = (options, path) => createAuthEndpoint(path, {
|
|
|
775
1037
|
const verifyTransaction = (options, path) => createAuthEndpoint(path, {
|
|
776
1038
|
method: "POST",
|
|
777
1039
|
body: verifyBodySchema,
|
|
778
|
-
use: [sessionMiddleware,
|
|
1040
|
+
use: [sessionMiddleware, originCheckMiddleware]
|
|
779
1041
|
}, async (ctx) => {
|
|
780
1042
|
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
1043
|
const verified = await adapter$1(options).verifyTransaction({
|
|
786
1044
|
transactionId: ctx.body.transactionId === void 0 ? void 0 : Number(ctx.body.transactionId),
|
|
787
1045
|
txRef: ctx.body.txRef
|
|
788
1046
|
});
|
|
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
|
-
}
|
|
1047
|
+
const expected = await store.findTransactionByTxRef(verified.tx_ref);
|
|
1048
|
+
if (!expected) throw new APIError("NOT_FOUND", { message: "Transaction not found" });
|
|
1049
|
+
if (ctx.body.referenceId !== void 0 && ctx.body.referenceId !== expected.referenceId) throw new APIError("UNAUTHORIZED");
|
|
1050
|
+
await authenticatedReference(ctx, options, "verify-transaction", expected.referenceId);
|
|
1051
|
+
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" });
|
|
1052
|
+
await recordVerifiedPayment(ctx, options, expected, verified);
|
|
822
1053
|
return {
|
|
823
1054
|
status: verified.status,
|
|
824
1055
|
txRef: verified.tx_ref,
|
|
@@ -857,28 +1088,42 @@ const listSubscriptions = (options, path) => createAuthEndpoint(path, {
|
|
|
857
1088
|
return { subscriptions: await createBillingStore(ctx).findSubscriptionsByReference(referenceId) };
|
|
858
1089
|
});
|
|
859
1090
|
const subscriptionBodySchema = z.object({
|
|
860
|
-
subscriptionId: z.
|
|
1091
|
+
subscriptionId: z.union([z.number().int().positive(), z.string().min(1)]),
|
|
861
1092
|
atPeriodEnd: z.boolean().optional()
|
|
862
1093
|
});
|
|
1094
|
+
async function findSubscription(ctx, id) {
|
|
1095
|
+
const store = createBillingStore(ctx);
|
|
1096
|
+
if (typeof id === "string") {
|
|
1097
|
+
const local = await store.findSubscriptionById(id);
|
|
1098
|
+
if (local) return local;
|
|
1099
|
+
}
|
|
1100
|
+
const providerId = Number(id);
|
|
1101
|
+
return Number.isInteger(providerId) && providerId > 0 ? store.findSubscriptionByProviderId(providerId) : null;
|
|
1102
|
+
}
|
|
863
1103
|
const cancelSubscription = (options, path) => createAuthEndpoint(path, {
|
|
864
1104
|
method: "POST",
|
|
865
1105
|
body: subscriptionBodySchema,
|
|
866
|
-
use: [sessionMiddleware,
|
|
1106
|
+
use: [sessionMiddleware, originCheckMiddleware]
|
|
867
1107
|
}, async (ctx) => {
|
|
868
1108
|
const store = createBillingStore(ctx);
|
|
869
|
-
const local = await
|
|
1109
|
+
const local = await findSubscription(ctx, ctx.body.subscriptionId);
|
|
870
1110
|
if (!local) throw new APIError("NOT_FOUND", { message: "Subscription not found" });
|
|
871
1111
|
await authenticatedReference(ctx, options, "disable-subscription", local.referenceId);
|
|
872
1112
|
const now = /* @__PURE__ */ new Date();
|
|
873
1113
|
if (ctx.body.atPeriodEnd === true || options.subscription?.cancelBehavior === "at_period_end") {
|
|
1114
|
+
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" });
|
|
1115
|
+
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" });
|
|
1116
|
+
if (local.subscriptionId != null && local.cancelAtPeriodEnd !== true) await adapter$1(options).cancelSubscription(local.subscriptionId);
|
|
874
1117
|
await store.updateSubscription(local.id, {
|
|
875
1118
|
cancelAtPeriodEnd: true,
|
|
876
|
-
cancelAt: local.periodEnd
|
|
1119
|
+
cancelAt: local.periodEnd,
|
|
1120
|
+
...local.subscriptionId != null ? { canceledAt: local.canceledAt ?? now } : {},
|
|
877
1121
|
updatedAt: now
|
|
878
1122
|
});
|
|
879
1123
|
return { status: "scheduled" };
|
|
880
1124
|
}
|
|
881
|
-
|
|
1125
|
+
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" });
|
|
1126
|
+
if (local.subscriptionId != null) await adapter$1(options).cancelSubscription(local.subscriptionId);
|
|
882
1127
|
await store.updateSubscription(local.id, {
|
|
883
1128
|
status: "canceled",
|
|
884
1129
|
cancelAtPeriodEnd: false,
|
|
@@ -891,22 +1136,29 @@ const cancelSubscription = (options, path) => createAuthEndpoint(path, {
|
|
|
891
1136
|
const restoreSubscription = (options, path) => createAuthEndpoint(path, {
|
|
892
1137
|
method: "POST",
|
|
893
1138
|
body: subscriptionBodySchema.omit({ atPeriodEnd: true }),
|
|
894
|
-
use: [sessionMiddleware,
|
|
1139
|
+
use: [sessionMiddleware, originCheckMiddleware]
|
|
895
1140
|
}, async (ctx) => {
|
|
896
1141
|
const store = createBillingStore(ctx);
|
|
897
|
-
const local = await
|
|
1142
|
+
const local = await findSubscription(ctx, ctx.body.subscriptionId);
|
|
898
1143
|
if (!local) throw new APIError("NOT_FOUND", { message: "Subscription not found" });
|
|
899
1144
|
await authenticatedReference(ctx, options, "enable-subscription", local.referenceId);
|
|
900
|
-
|
|
1145
|
+
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" });
|
|
1146
|
+
if (local.cancelAtPeriodEnd !== true || local.canceledAt != null) {
|
|
1147
|
+
if (local.subscriptionId == null) {
|
|
1148
|
+
if (local.status === "active" && local.endedAt == null) return { status: "active" };
|
|
1149
|
+
throw new APIError("BAD_REQUEST", { message: "A canceled local subscription requires a new checkout" });
|
|
1150
|
+
}
|
|
1151
|
+
await adapter$1(options).activateSubscription(local.subscriptionId);
|
|
1152
|
+
}
|
|
901
1153
|
await store.updateSubscription(local.id, {
|
|
902
|
-
status: "active",
|
|
1154
|
+
status: local.cancelAtPeriodEnd === true ? local.status : "active",
|
|
903
1155
|
cancelAtPeriodEnd: false,
|
|
904
1156
|
cancelAt: null,
|
|
905
1157
|
canceledAt: null,
|
|
906
1158
|
endedAt: null,
|
|
907
1159
|
updatedAt: /* @__PURE__ */ new Date()
|
|
908
1160
|
});
|
|
909
|
-
return { status: "active" };
|
|
1161
|
+
return { status: local.cancelAtPeriodEnd === true ? local.status : "active" };
|
|
910
1162
|
});
|
|
911
1163
|
const createSubscription = initializeTransaction;
|
|
912
1164
|
const upgradeSubscription = initializeTransaction;
|
|
@@ -955,11 +1207,12 @@ const flutterwaveWebhook = (options, path) => createAuthEndpoint(path, {
|
|
|
955
1207
|
}
|
|
956
1208
|
const event = parsedEvent.data;
|
|
957
1209
|
const data = event.data;
|
|
958
|
-
const eventId = createHash("sha256").update(`${event.event}:${String(data.id
|
|
1210
|
+
const eventId = createHash("sha256").update(data.id === void 0 ? rawBody : `${event.event}:${String(data.id)}:${String(data.status ?? "")}`).digest("hex");
|
|
959
1211
|
const store = createBillingStore(ctx);
|
|
960
1212
|
const existingEvent = await store.findWebhookEvent(eventId);
|
|
961
1213
|
if (existingEvent?.status === "processed") return ctx.json({ received: true });
|
|
962
1214
|
const now = /* @__PURE__ */ new Date();
|
|
1215
|
+
const busy = () => new APIError("SERVICE_UNAVAILABLE", { message: "Webhook processing is still in progress; retry delivery" });
|
|
963
1216
|
if (existingEvent === null) try {
|
|
964
1217
|
await store.createWebhookEvent({
|
|
965
1218
|
eventId,
|
|
@@ -974,60 +1227,43 @@ const flutterwaveWebhook = (options, path) => createAuthEndpoint(path, {
|
|
|
974
1227
|
} catch (error) {
|
|
975
1228
|
const concurrent = await store.findWebhookEvent(eventId);
|
|
976
1229
|
if (concurrent === null) throw error;
|
|
977
|
-
if (concurrent.status === "processed"
|
|
1230
|
+
if (concurrent.status === "processed") return ctx.json({ received: true });
|
|
1231
|
+
throw busy();
|
|
978
1232
|
}
|
|
979
|
-
else
|
|
980
|
-
|
|
981
|
-
|
|
982
|
-
|
|
983
|
-
|
|
984
|
-
|
|
985
|
-
|
|
986
|
-
|
|
987
|
-
|
|
988
|
-
|
|
989
|
-
|
|
990
|
-
|
|
991
|
-
|
|
992
|
-
|
|
993
|
-
|
|
994
|
-
|
|
995
|
-
|
|
1233
|
+
else {
|
|
1234
|
+
const leaseExpiresAt = new Date(existingEvent.updatedAt).getTime() + 3e5;
|
|
1235
|
+
if (existingEvent.status === "processing" && leaseExpiresAt > now.getTime()) throw busy();
|
|
1236
|
+
if (!await store.claimWebhookEvent(existingEvent, now)) throw busy();
|
|
1237
|
+
}
|
|
1238
|
+
try {
|
|
1239
|
+
if (data.tx_ref && data.id !== void 0) {
|
|
1240
|
+
const local = await store.findTransactionByTxRef(data.tx_ref);
|
|
1241
|
+
if (!local) throw new Error("The webhook payment has not been recorded locally yet");
|
|
1242
|
+
const verified = await adapter$1(options).verifyTransaction({ transactionId: Number(data.id) });
|
|
1243
|
+
if (data.status === "successful" && verified.status !== "successful") throw new Error("The provider has not verified the successful payment yet");
|
|
1244
|
+
await recordVerifiedPayment(ctx, options, local, verified);
|
|
1245
|
+
Object.assign(data, {
|
|
1246
|
+
id: verified.id,
|
|
1247
|
+
tx_ref: verified.tx_ref,
|
|
1248
|
+
amount: verified.amount,
|
|
1249
|
+
currency: verified.currency,
|
|
1250
|
+
status: verified.status
|
|
996
1251
|
});
|
|
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
1252
|
}
|
|
1253
|
+
await options.onEvent?.(event);
|
|
1254
|
+
await store.updateWebhookEvent(eventId, {
|
|
1255
|
+
status: "processed",
|
|
1256
|
+
processedAt: /* @__PURE__ */ new Date(),
|
|
1257
|
+
updatedAt: /* @__PURE__ */ new Date()
|
|
1258
|
+
});
|
|
1017
1259
|
} catch (error) {
|
|
1018
|
-
ctx.context.logger.error("Flutterwave webhook
|
|
1260
|
+
ctx.context.logger.error("Flutterwave webhook processing failed", error);
|
|
1019
1261
|
await store.updateWebhookEvent(eventId, {
|
|
1020
1262
|
status: "failed",
|
|
1021
1263
|
updatedAt: /* @__PURE__ */ new Date()
|
|
1022
1264
|
});
|
|
1023
|
-
|
|
1265
|
+
throw new APIError("SERVICE_UNAVAILABLE", { message: "Webhook processing failed; retry delivery" });
|
|
1024
1266
|
}
|
|
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
1267
|
return ctx.json({ received: true });
|
|
1032
1268
|
});
|
|
1033
1269
|
//#endregion
|
|
@@ -1499,11 +1735,13 @@ async function chargeSubscriptionRenewal(ctx, options, input) {
|
|
|
1499
1735
|
const store = createBillingStore(ctx);
|
|
1500
1736
|
const subscription = await store.findSubscriptionById(input.subscriptionId);
|
|
1501
1737
|
if (!subscription) throw new APIError("NOT_FOUND", { message: "Subscription not found" });
|
|
1738
|
+
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" });
|
|
1739
|
+
if (subscription.paymentPlanId != null || subscription.subscriptionId != null) throw new APIError("BAD_REQUEST", { message: "Native subscription renewals are managed by Flutterwave" });
|
|
1502
1740
|
const plan = await store.findPlanByName(subscription.plan) ?? await (async () => {
|
|
1503
1741
|
const configured = options.subscription?.plans;
|
|
1504
1742
|
return (typeof configured === "function" ? await configured() : configured ?? []).find((candidate) => candidate.name === subscription.plan) ?? null;
|
|
1505
1743
|
})();
|
|
1506
|
-
const amount = input.amount ?? plan
|
|
1744
|
+
const amount = input.amount ?? (plan ? calculatePlanAmount(plan, subscription.seats) : void 0);
|
|
1507
1745
|
if (!amount || !plan?.currency || !subscription.billingEmail) throw new APIError("BAD_REQUEST", { message: "Subscription billing details are incomplete" });
|
|
1508
1746
|
const txRef = `flw_renewal_${crypto.randomUUID()}`;
|
|
1509
1747
|
const metadata = stringifyFlutterwaveMetadata(createRenewalMetadata({
|
|
@@ -1559,7 +1797,7 @@ async function chargeSubscriptionRenewal(ctx, options, input) {
|
|
|
1559
1797
|
const verified = await adapter(options).verifyTransaction({ transactionId: charged.id });
|
|
1560
1798
|
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
1799
|
const now = /* @__PURE__ */ new Date();
|
|
1562
|
-
await store.createTransaction({
|
|
1800
|
+
const transaction = await store.createTransaction({
|
|
1563
1801
|
txRef,
|
|
1564
1802
|
transactionId: verified.id,
|
|
1565
1803
|
flwRef: verified.flw_ref,
|
|
@@ -1568,21 +1806,20 @@ async function chargeSubscriptionRenewal(ctx, options, input) {
|
|
|
1568
1806
|
amount,
|
|
1569
1807
|
chargedAmount: verified.charged_amount,
|
|
1570
1808
|
currency: plan.currency,
|
|
1571
|
-
status:
|
|
1809
|
+
status: "pending",
|
|
1572
1810
|
plan: subscription.plan,
|
|
1573
1811
|
paymentType: verified.payment_type,
|
|
1574
1812
|
metadata,
|
|
1575
|
-
verifiedAt: now,
|
|
1576
|
-
reconciledAt: now,
|
|
1577
1813
|
createdAt: now,
|
|
1578
1814
|
updatedAt: now
|
|
1579
1815
|
});
|
|
1580
1816
|
await store.updateSubscription(subscription.id, {
|
|
1581
1817
|
txRef,
|
|
1582
|
-
status:
|
|
1818
|
+
status: "past_due",
|
|
1583
1819
|
reconciledAt: now,
|
|
1584
1820
|
updatedAt: now
|
|
1585
1821
|
});
|
|
1822
|
+
await recordVerifiedPayment(ctx, options, transaction, verified);
|
|
1586
1823
|
return {
|
|
1587
1824
|
status: verified.status === "successful" ? "success" : "failed",
|
|
1588
1825
|
data: {
|
|
@@ -1597,6 +1834,28 @@ async function chargeSubscriptionRenewal(ctx, options, input) {
|
|
|
1597
1834
|
}
|
|
1598
1835
|
};
|
|
1599
1836
|
}
|
|
1837
|
+
/** Call from an independently authorized scheduled job; no browser endpoint is exposed. */
|
|
1838
|
+
async function processScheduledFlutterwaveCancellations(ctx, options, input = {}) {
|
|
1839
|
+
const now = input.now ?? /* @__PURE__ */ new Date();
|
|
1840
|
+
const limit = input.limit ?? 100;
|
|
1841
|
+
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" });
|
|
1842
|
+
const store = createBillingStore(ctx);
|
|
1843
|
+
const due = await store.listDueCancellations(now, limit);
|
|
1844
|
+
const failed = [];
|
|
1845
|
+
let canceled = 0;
|
|
1846
|
+
for (const subscription of due) try {
|
|
1847
|
+
if (subscription.paymentPlanId != null && subscription.subscriptionId == null) throw new Error("Native subscription has not been identified");
|
|
1848
|
+
if (subscription.subscriptionId != null && subscription.status !== "canceled" && subscription.canceledAt == null) await adapter(options).cancelSubscription(subscription.subscriptionId);
|
|
1849
|
+
if (await store.completeScheduledCancellation(subscription, now)) canceled++;
|
|
1850
|
+
} catch {
|
|
1851
|
+
failed.push(subscription.id);
|
|
1852
|
+
}
|
|
1853
|
+
return {
|
|
1854
|
+
canceled,
|
|
1855
|
+
failed,
|
|
1856
|
+
hasMore: due.length === limit
|
|
1857
|
+
};
|
|
1858
|
+
}
|
|
1600
1859
|
function parseMetadata(value) {
|
|
1601
1860
|
if (!value) return void 0;
|
|
1602
1861
|
return JSON.parse(value);
|
|
@@ -1636,7 +1895,7 @@ async function reconcileFlutterwaveTransaction(ctx, options, input) {
|
|
|
1636
1895
|
txRef: input.txRef,
|
|
1637
1896
|
transactionId: input.transactionId
|
|
1638
1897
|
});
|
|
1639
|
-
if (!(
|
|
1898
|
+
if (!paymentMatches(local, verified)) {
|
|
1640
1899
|
if (input.throwOnError === false) return {
|
|
1641
1900
|
ok: false,
|
|
1642
1901
|
source: input.source ?? "server",
|
|
@@ -1648,22 +1907,7 @@ async function reconcileFlutterwaveTransaction(ctx, options, input) {
|
|
|
1648
1907
|
};
|
|
1649
1908
|
throw new APIError("BAD_REQUEST", { message: "Transaction details do not match" });
|
|
1650
1909
|
}
|
|
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
|
-
});
|
|
1910
|
+
await recordVerifiedPayment(ctx, options, local, verified);
|
|
1667
1911
|
const data = {
|
|
1668
1912
|
id: verified.id,
|
|
1669
1913
|
txRef: verified.tx_ref,
|
|
@@ -1747,6 +1991,6 @@ const flutterwave = (options) => {
|
|
|
1747
1991
|
};
|
|
1748
1992
|
};
|
|
1749
1993
|
//#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 };
|
|
1994
|
+
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
1995
|
|
|
1752
1996
|
//# sourceMappingURL=index.mjs.map
|