better-auth-flutterwave 0.3.2 → 0.4.1
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 +71 -9
- package/dist/client.d.mts +1 -1
- package/dist/client.mjs +1 -1
- package/dist/{index-CaJVMbgJ.d.mts → index-D_d9XPR3.d.mts} +126 -5
- package/dist/index-D_d9XPR3.d.mts.map +1 -0
- package/dist/index.d.mts +2 -2
- package/dist/index.mjs +607 -102
- package/dist/index.mjs.map +1 -1
- package/dist/{version-BxJE-Ge2.mjs → version-DdOSzXn4.mjs} +2 -2
- package/dist/{version-BxJE-Ge2.mjs.map → version-DdOSzXn4.mjs.map} +1 -1
- package/package.json +1 -1
- 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 +1 -1
- package/skills/flutterwave-organization-billing/SKILL.md +1 -1
- package/skills/flutterwave-schema-migrations/SKILL.md +1 -1
- package/skills/flutterwave-tanstack-start/SKILL.md +1 -1
- package/skills/flutterwave-testing-fixtures/SKILL.md +1 -1
- package/skills/flutterwave-webhooks-events/SKILL.md +1 -1
- package/dist/index-CaJVMbgJ.d.mts.map +0 -1
package/dist/index.mjs
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
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-DdOSzXn4.mjs";
|
|
2
2
|
import { HIDE_METADATA, defineErrorCodes } from "better-auth";
|
|
3
|
-
import { createHash, timingSafeEqual } from "node:crypto";
|
|
3
|
+
import { createHash, randomBytes, timingSafeEqual } from "node:crypto";
|
|
4
4
|
import { APIError, createAuthEndpoint, getSessionFromCtx, originCheckMiddleware, sessionMiddleware } from "better-auth/api";
|
|
5
5
|
import * as z from "zod";
|
|
6
6
|
import { Buffer } from "node:buffer";
|
|
@@ -73,6 +73,13 @@ function createBillingStoreFromAdapter(adapter) {
|
|
|
73
73
|
field: "txRef",
|
|
74
74
|
value: txRef
|
|
75
75
|
}]),
|
|
76
|
+
findSubscriptionsByBillingEmailAndPlanId: (email, paymentPlanId) => findMany("flutterwaveSubscription", [{
|
|
77
|
+
field: "billingEmail",
|
|
78
|
+
value: email
|
|
79
|
+
}, {
|
|
80
|
+
field: "paymentPlanId",
|
|
81
|
+
value: paymentPlanId
|
|
82
|
+
}]),
|
|
76
83
|
listDueCancellations: (now, limit) => adapter.findMany({
|
|
77
84
|
model: "flutterwaveSubscription",
|
|
78
85
|
where: [{
|
|
@@ -283,6 +290,26 @@ function createBillingStoreFromAdapter(adapter) {
|
|
|
283
290
|
}
|
|
284
291
|
}) === 1;
|
|
285
292
|
},
|
|
293
|
+
async updateOwnedWebhookEvent(event, update) {
|
|
294
|
+
return await adapter.updateMany({
|
|
295
|
+
model: "flutterwaveWebhookEvent",
|
|
296
|
+
where: [
|
|
297
|
+
{
|
|
298
|
+
field: "eventId",
|
|
299
|
+
value: event.eventId
|
|
300
|
+
},
|
|
301
|
+
{
|
|
302
|
+
field: "status",
|
|
303
|
+
value: "processing"
|
|
304
|
+
},
|
|
305
|
+
{
|
|
306
|
+
field: "updatedAt",
|
|
307
|
+
value: new Date(event.updatedAt)
|
|
308
|
+
}
|
|
309
|
+
],
|
|
310
|
+
update
|
|
311
|
+
}) === 1;
|
|
312
|
+
},
|
|
286
313
|
createRefund: (data) => adapter.create({
|
|
287
314
|
model: "flutterwaveRefund",
|
|
288
315
|
data
|
|
@@ -291,10 +318,19 @@ function createBillingStoreFromAdapter(adapter) {
|
|
|
291
318
|
field: "refundId",
|
|
292
319
|
value: refundId
|
|
293
320
|
}]),
|
|
294
|
-
listPendingRefunds: () => findMany(
|
|
295
|
-
|
|
296
|
-
|
|
297
|
-
|
|
321
|
+
listPendingRefunds: () => adapter.findMany({
|
|
322
|
+
model: "flutterwaveRefund",
|
|
323
|
+
where: [{
|
|
324
|
+
field: "status",
|
|
325
|
+
operator: "in",
|
|
326
|
+
value: [
|
|
327
|
+
"pending",
|
|
328
|
+
"completed",
|
|
329
|
+
"processing",
|
|
330
|
+
"pending-momo"
|
|
331
|
+
]
|
|
332
|
+
}]
|
|
333
|
+
}),
|
|
298
334
|
updateRefund: (id, update) => adapter.update({
|
|
299
335
|
model: "flutterwaveRefund",
|
|
300
336
|
update,
|
|
@@ -465,7 +501,10 @@ function createHttpClient(fetchImpl, apiBaseUrl, secretKey) {
|
|
|
465
501
|
Transaction: {
|
|
466
502
|
verify: ({ id }) => request(`/v3/transactions/${id}/verify`),
|
|
467
503
|
verify_by_tx: ({ tx_ref }) => request(`/v3/transactions/verify_by_reference${queryString({ tx_ref })}`),
|
|
468
|
-
refund: ({ id, amount }) => post(`/v3/transactions/${id}/refund`,
|
|
504
|
+
refund: ({ id, amount, comments }) => post(`/v3/transactions/${id}/refund`, {
|
|
505
|
+
...amount === void 0 ? {} : { amount },
|
|
506
|
+
...comments === void 0 ? {} : { comments }
|
|
507
|
+
})
|
|
469
508
|
},
|
|
470
509
|
PaymentPlan: { get_all: (query) => request(`/v3/payment-plans${queryString(query)}`) },
|
|
471
510
|
Subscription: {
|
|
@@ -564,13 +603,63 @@ function createFlutterwaveAdapter(options) {
|
|
|
564
603
|
const body = tokenChargeInputSchema.parse(input);
|
|
565
604
|
return sdkCall("charge token", () => client.Tokenized.charge(body), transactionSchema);
|
|
566
605
|
},
|
|
567
|
-
refundTransaction: (transactionId, amount) => sdkCall("refund transaction", () => client.Transaction.refund({
|
|
606
|
+
refundTransaction: (transactionId, amount, reason) => sdkCall("refund transaction", () => client.Transaction.refund({
|
|
568
607
|
id: positiveIdSchema.parse(transactionId),
|
|
569
|
-
amount: optionalPositiveAmountSchema.parse(amount)
|
|
608
|
+
amount: optionalPositiveAmountSchema.parse(amount),
|
|
609
|
+
...reason === void 0 ? {} : { comments: z.string().min(1).parse(reason) }
|
|
570
610
|
}), refundSchema)
|
|
571
611
|
};
|
|
572
612
|
}
|
|
573
613
|
//#endregion
|
|
614
|
+
//#region src/operation-ledger.ts
|
|
615
|
+
const LEASE_MS = 3e5;
|
|
616
|
+
function busy() {
|
|
617
|
+
return new APIError("SERVICE_UNAVAILABLE", { message: "Billing operation is in progress; retry later" });
|
|
618
|
+
}
|
|
619
|
+
/** Internal operations share the existing unique event ledger; no new database schema is needed. */
|
|
620
|
+
async function acquireOperation(store, input) {
|
|
621
|
+
let existing = await store.findWebhookEvent(input.eventId);
|
|
622
|
+
const now = /* @__PURE__ */ new Date();
|
|
623
|
+
if (existing === null) try {
|
|
624
|
+
return await store.createWebhookEvent({
|
|
625
|
+
...input,
|
|
626
|
+
status: "processing",
|
|
627
|
+
createdAt: now,
|
|
628
|
+
updatedAt: now
|
|
629
|
+
});
|
|
630
|
+
} catch (error) {
|
|
631
|
+
existing = await store.findWebhookEvent(input.eventId);
|
|
632
|
+
if (existing === null) throw error;
|
|
633
|
+
}
|
|
634
|
+
if (existing.status === "processed") return existing;
|
|
635
|
+
if (existing.status === "processing" && new Date(existing.updatedAt).getTime() + LEASE_MS > now.getTime()) throw busy();
|
|
636
|
+
const claimedAt = new Date(Math.max(now.getTime(), new Date(existing.updatedAt).getTime() + 1));
|
|
637
|
+
if (!await store.claimWebhookEvent(existing, claimedAt)) throw busy();
|
|
638
|
+
return {
|
|
639
|
+
...existing,
|
|
640
|
+
status: "processing",
|
|
641
|
+
updatedAt: claimedAt
|
|
642
|
+
};
|
|
643
|
+
}
|
|
644
|
+
async function checkpointOperation(store, operation, update) {
|
|
645
|
+
const updatedAt = new Date(Math.max(Date.now(), new Date(operation.updatedAt).getTime() + 1));
|
|
646
|
+
if (!await store.updateOwnedWebhookEvent(operation, {
|
|
647
|
+
...update,
|
|
648
|
+
updatedAt
|
|
649
|
+
})) throw busy();
|
|
650
|
+
return {
|
|
651
|
+
...operation,
|
|
652
|
+
...update,
|
|
653
|
+
updatedAt
|
|
654
|
+
};
|
|
655
|
+
}
|
|
656
|
+
async function failOperation(store, operation) {
|
|
657
|
+
await store.updateOwnedWebhookEvent(operation, {
|
|
658
|
+
status: "failed",
|
|
659
|
+
updatedAt: /* @__PURE__ */ new Date()
|
|
660
|
+
});
|
|
661
|
+
}
|
|
662
|
+
//#endregion
|
|
574
663
|
//#region src/token-crypto.ts
|
|
575
664
|
const encoder = new TextEncoder();
|
|
576
665
|
const decoder = new TextDecoder();
|
|
@@ -685,11 +774,19 @@ function getNextPeriodEnd(startDate, interval) {
|
|
|
685
774
|
}
|
|
686
775
|
//#endregion
|
|
687
776
|
//#region src/billing-lifecycle.ts
|
|
777
|
+
const fulfillmentSchema = z.object({
|
|
778
|
+
initialCompletion: z.boolean(),
|
|
779
|
+
completed: z.array(z.enum([
|
|
780
|
+
"complete",
|
|
781
|
+
"created",
|
|
782
|
+
"update"
|
|
783
|
+
]))
|
|
784
|
+
});
|
|
688
785
|
function paymentMatches(expected, verified) {
|
|
689
786
|
return verified.tx_ref === expected.txRef && verified.amount === expected.amount && verified.currency === expected.currency;
|
|
690
787
|
}
|
|
691
788
|
/** Shared fulfillment for browser verification, webhooks, and trusted reconciliation. */
|
|
692
|
-
async function recordVerifiedPayment(ctx, options, expected, verified) {
|
|
789
|
+
async function recordVerifiedPayment(ctx, options, expected, verified, webhookEvent) {
|
|
693
790
|
if (!paymentMatches(expected, verified)) throw new APIError("BAD_REQUEST", { message: "Verified transaction does not match the expected payment" });
|
|
694
791
|
const store = createBillingStore(ctx);
|
|
695
792
|
const now = /* @__PURE__ */ new Date();
|
|
@@ -733,7 +830,7 @@ async function recordVerifiedPayment(ctx, options, expected, verified) {
|
|
|
733
830
|
const priorEnd = subscription.periodEnd ? new Date(subscription.periodEnd) : null;
|
|
734
831
|
const periodStart = renewal && priorEnd !== null && priorEnd > paymentTime ? priorEnd : paymentTime;
|
|
735
832
|
const advancePeriod = subscription.periodEnd == null || (renewal ? subscription.status === "past_due" : expected.status !== "successful");
|
|
736
|
-
|
|
833
|
+
const update = {
|
|
737
834
|
subscriptionId,
|
|
738
835
|
status: identified ? "active" : "incomplete",
|
|
739
836
|
encryptedPaymentToken: verified.card?.token !== void 0 ? await encryptPaymentToken(verified.card.token, ctx.context.secret) : subscription.encryptedPaymentToken,
|
|
@@ -743,7 +840,81 @@ async function recordVerifiedPayment(ctx, options, expected, verified) {
|
|
|
743
840
|
} : {},
|
|
744
841
|
reconciledAt: now,
|
|
745
842
|
updatedAt: now
|
|
746
|
-
}
|
|
843
|
+
};
|
|
844
|
+
if (!identified) {
|
|
845
|
+
await store.updateCurrentSubscription(subscription, update);
|
|
846
|
+
continue;
|
|
847
|
+
}
|
|
848
|
+
let operation = await acquireOperation(store, {
|
|
849
|
+
eventId: `internal:payment:${verified.id}:${subscription.id}`,
|
|
850
|
+
eventType: "internal.payment.fulfillment",
|
|
851
|
+
txRef: expected.txRef,
|
|
852
|
+
payload: JSON.stringify({
|
|
853
|
+
initialCompletion: subscription.status === "incomplete",
|
|
854
|
+
completed: []
|
|
855
|
+
})
|
|
856
|
+
});
|
|
857
|
+
if (operation.status === "processed") continue;
|
|
858
|
+
try {
|
|
859
|
+
const progress = fulfillmentSchema.parse(JSON.parse(operation.payload));
|
|
860
|
+
if (!await store.updateCurrentSubscription(subscription, update)) {
|
|
861
|
+
operation = await checkpointOperation(store, operation, {
|
|
862
|
+
status: "processed",
|
|
863
|
+
processedAt: /* @__PURE__ */ new Date()
|
|
864
|
+
});
|
|
865
|
+
continue;
|
|
866
|
+
}
|
|
867
|
+
const plan = (await getPlans(options.subscription)).find((candidate) => candidate.name.toLowerCase() === subscription.plan.toLowerCase());
|
|
868
|
+
if (plan) {
|
|
869
|
+
const callbackData = {
|
|
870
|
+
event: webhookEvent ?? {
|
|
871
|
+
event: "charge.completed",
|
|
872
|
+
data: {
|
|
873
|
+
id: verified.id,
|
|
874
|
+
tx_ref: verified.tx_ref,
|
|
875
|
+
...verified.flw_ref !== void 0 && verified.flw_ref !== null && verified.flw_ref !== "" ? { flw_ref: verified.flw_ref } : {},
|
|
876
|
+
status: verified.status,
|
|
877
|
+
amount: verified.amount,
|
|
878
|
+
currency: verified.currency
|
|
879
|
+
}
|
|
880
|
+
},
|
|
881
|
+
subscription: {
|
|
882
|
+
...subscription,
|
|
883
|
+
...update
|
|
884
|
+
},
|
|
885
|
+
plan
|
|
886
|
+
};
|
|
887
|
+
const callbacks = [
|
|
888
|
+
{
|
|
889
|
+
key: "complete",
|
|
890
|
+
callback: progress.initialCompletion ? options.subscription?.onSubscriptionComplete : void 0
|
|
891
|
+
},
|
|
892
|
+
{
|
|
893
|
+
key: "created",
|
|
894
|
+
callback: progress.initialCompletion ? options.subscription?.onSubscriptionCreated : void 0
|
|
895
|
+
},
|
|
896
|
+
{
|
|
897
|
+
key: "update",
|
|
898
|
+
callback: options.subscription?.onSubscriptionUpdate
|
|
899
|
+
}
|
|
900
|
+
];
|
|
901
|
+
for (const { key, callback } of callbacks) {
|
|
902
|
+
if (progress.completed.includes(key)) continue;
|
|
903
|
+
operation = await checkpointOperation(store, operation, {});
|
|
904
|
+
await callback?.(callbackData, ctx);
|
|
905
|
+
progress.completed.push(key);
|
|
906
|
+
operation = await checkpointOperation(store, operation, { payload: JSON.stringify(progress) });
|
|
907
|
+
}
|
|
908
|
+
}
|
|
909
|
+
await store.retireCompetingSubscriptions(subscription.referenceId, group, subscription.id);
|
|
910
|
+
operation = await checkpointOperation(store, operation, {
|
|
911
|
+
status: "processed",
|
|
912
|
+
processedAt: /* @__PURE__ */ new Date()
|
|
913
|
+
});
|
|
914
|
+
} catch (error) {
|
|
915
|
+
await failOperation(store, operation);
|
|
916
|
+
throw error;
|
|
917
|
+
}
|
|
747
918
|
}
|
|
748
919
|
}
|
|
749
920
|
//#endregion
|
|
@@ -866,7 +1037,7 @@ const verifyBodySchema = z.object({
|
|
|
866
1037
|
txRef: z.string().optional(),
|
|
867
1038
|
referenceId: z.string().optional()
|
|
868
1039
|
}).refine((body) => body.transactionId === void 0 !== (body.txRef === void 0), { message: "Provide exactly one of transactionId or txRef" });
|
|
869
|
-
const
|
|
1040
|
+
const v3WebhookPayloadSchema = z.object({
|
|
870
1041
|
event: z.string().min(1),
|
|
871
1042
|
data: z.object({
|
|
872
1043
|
id: z.union([z.string(), z.number()]).optional(),
|
|
@@ -877,7 +1048,25 @@ const webhookPayloadSchema = z.object({
|
|
|
877
1048
|
charged_amount: z.coerce.number().optional(),
|
|
878
1049
|
currency: z.string().optional(),
|
|
879
1050
|
payment_type: z.string().optional(),
|
|
880
|
-
customer: z.object({ email: z.string().optional() }).passthrough().optional()
|
|
1051
|
+
customer: z.object({ email: z.string().optional() }).passthrough().optional(),
|
|
1052
|
+
plan: z.object({ id: z.union([z.string(), z.number()]).optional() }).passthrough().optional()
|
|
1053
|
+
}).passthrough()
|
|
1054
|
+
});
|
|
1055
|
+
const v4WebhookPayloadSchema = z.object({
|
|
1056
|
+
type: z.string().min(1),
|
|
1057
|
+
id: z.string().optional(),
|
|
1058
|
+
webhook_id: z.string().optional(),
|
|
1059
|
+
timestamp: z.union([z.string(), z.number()]).optional(),
|
|
1060
|
+
data: z.object({
|
|
1061
|
+
id: z.string().optional(),
|
|
1062
|
+
reference: z.string().optional(),
|
|
1063
|
+
status: z.string().optional(),
|
|
1064
|
+
amount: z.coerce.number().optional(),
|
|
1065
|
+
currency: z.string().optional(),
|
|
1066
|
+
customer: z.object({
|
|
1067
|
+
id: z.string().optional(),
|
|
1068
|
+
email: z.string().optional()
|
|
1069
|
+
}).passthrough().optional()
|
|
881
1070
|
}).passthrough()
|
|
882
1071
|
});
|
|
883
1072
|
function adapter$1(options) {
|
|
@@ -953,6 +1142,7 @@ const initializeTransaction = (options, path) => createAuthEndpoint(path, {
|
|
|
953
1142
|
if (ctx.body.product && !product) throw new APIError("NOT_FOUND", { message: "Product not found" });
|
|
954
1143
|
if (plan && product) throw new APIError("BAD_REQUEST", { message: "Select a plan or a product, not both" });
|
|
955
1144
|
if (plan) {
|
|
1145
|
+
if (plan.freeTrial?.days !== void 0 && plan.freeTrial.days > 0) throw new APIError("BAD_REQUEST", { message: "Flutterwave v3 checkout cannot start a no-charge trial. Do not configure freeTrial until a customer-visible tokenization charge and local trial lifecycle are implemented." });
|
|
956
1146
|
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
1147
|
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
1148
|
}
|
|
@@ -1124,13 +1314,30 @@ const cancelSubscription = (options, path) => createAuthEndpoint(path, {
|
|
|
1124
1314
|
}
|
|
1125
1315
|
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
1316
|
if (local.subscriptionId != null) await adapter$1(options).cancelSubscription(local.subscriptionId);
|
|
1127
|
-
await store.updateSubscription(local.id, {
|
|
1317
|
+
const canceled = await store.updateSubscription(local.id, {
|
|
1128
1318
|
status: "canceled",
|
|
1129
1319
|
cancelAtPeriodEnd: false,
|
|
1130
1320
|
canceledAt: now,
|
|
1131
1321
|
endedAt: now,
|
|
1132
1322
|
updatedAt: now
|
|
1133
1323
|
});
|
|
1324
|
+
if (canceled) {
|
|
1325
|
+
const plan = await getPlans(options.subscription).then((plans) => plans.find((candidate) => candidate.name.toLowerCase() === local.plan.toLowerCase()));
|
|
1326
|
+
if (plan) {
|
|
1327
|
+
const callbackData = {
|
|
1328
|
+
event: {
|
|
1329
|
+
event: "subscription.cancelled",
|
|
1330
|
+
data: {}
|
|
1331
|
+
},
|
|
1332
|
+
subscription: canceled
|
|
1333
|
+
};
|
|
1334
|
+
await options.subscription?.onSubscriptionCancel?.(callbackData, ctx);
|
|
1335
|
+
await options.subscription?.onSubscriptionUpdate?.({
|
|
1336
|
+
...callbackData,
|
|
1337
|
+
plan
|
|
1338
|
+
}, ctx);
|
|
1339
|
+
}
|
|
1340
|
+
}
|
|
1134
1341
|
return { status: "canceled" };
|
|
1135
1342
|
});
|
|
1136
1343
|
const restoreSubscription = (options, path) => createAuthEndpoint(path, {
|
|
@@ -1190,9 +1397,14 @@ const flutterwaveWebhook = (options, path) => createAuthEndpoint(path, {
|
|
|
1190
1397
|
const request = getWebhookRequest(ctx);
|
|
1191
1398
|
if (!request) throw new APIError("BAD_REQUEST", { message: "Request is missing" });
|
|
1192
1399
|
const rawBody = await request.text();
|
|
1193
|
-
const
|
|
1194
|
-
|
|
1195
|
-
|
|
1400
|
+
const headers = getWebhookHeaders(ctx);
|
|
1401
|
+
const signature = headers?.get("flutterwave-signature");
|
|
1402
|
+
const legacyHash = headers?.get("verif-hash");
|
|
1403
|
+
const secretHash = options.webhook?.secretHash ?? options.secretHash;
|
|
1404
|
+
if (typeof signature !== "string" && typeof legacyHash !== "string") throw new APIError("UNAUTHORIZED", { message: "Missing signature" });
|
|
1405
|
+
const validV4Signature = typeof signature === "string" && timingSafeEqualString(signature, await hmacSha256Base64(secretHash, rawBody));
|
|
1406
|
+
const validV3Hash = typeof legacyHash === "string" && timingSafeEqualString(legacyHash, secretHash);
|
|
1407
|
+
if (!validV4Signature && !validV3Hash) throw new APIError("UNAUTHORIZED", { message: "Invalid signature" });
|
|
1196
1408
|
let webhookJson;
|
|
1197
1409
|
try {
|
|
1198
1410
|
webhookJson = JSON.parse(rawBody);
|
|
@@ -1200,14 +1412,20 @@ const flutterwaveWebhook = (options, path) => createAuthEndpoint(path, {
|
|
|
1200
1412
|
ctx.context.logger.warn("Ignoring non-JSON signed Flutterwave webhook");
|
|
1201
1413
|
return ctx.json({ received: true });
|
|
1202
1414
|
}
|
|
1203
|
-
const
|
|
1204
|
-
|
|
1415
|
+
const parsedV3 = v3WebhookPayloadSchema.safeParse(webhookJson);
|
|
1416
|
+
const parsedV4 = parsedV3.success ? void 0 : v4WebhookPayloadSchema.safeParse(webhookJson);
|
|
1417
|
+
if (!parsedV3.success && !parsedV4?.success) {
|
|
1205
1418
|
ctx.context.logger.warn("Ignoring malformed signed Flutterwave webhook");
|
|
1206
1419
|
return ctx.json({ received: true });
|
|
1207
1420
|
}
|
|
1208
|
-
|
|
1209
|
-
|
|
1210
|
-
|
|
1421
|
+
let event;
|
|
1422
|
+
if (parsedV3.success) event = parsedV3.data;
|
|
1423
|
+
else if (parsedV4?.success) event = parsedV4.data;
|
|
1424
|
+
else throw new APIError("BAD_REQUEST", { message: "Malformed webhook" });
|
|
1425
|
+
const eventId = ("type" in event ? event.webhook_id ?? event.id : void 0) ?? createHash("sha256").update("type" in event ? rawBody : event.data.id === void 0 ? rawBody : `${event.event}:${String(event.data.id)}:${String(event.data.status ?? "")}`).digest("hex");
|
|
1426
|
+
const eventType = "type" in event ? event.type : event.event;
|
|
1427
|
+
const txRef = "type" in event ? event.data.reference : event.data.tx_ref;
|
|
1428
|
+
const providerTransactionId = "type" in event ? void 0 : event.data.id;
|
|
1211
1429
|
const store = createBillingStore(ctx);
|
|
1212
1430
|
const existingEvent = await store.findWebhookEvent(eventId);
|
|
1213
1431
|
if (existingEvent?.status === "processed") return ctx.json({ received: true });
|
|
@@ -1216,9 +1434,9 @@ const flutterwaveWebhook = (options, path) => createAuthEndpoint(path, {
|
|
|
1216
1434
|
if (existingEvent === null) try {
|
|
1217
1435
|
await store.createWebhookEvent({
|
|
1218
1436
|
eventId,
|
|
1219
|
-
eventType
|
|
1220
|
-
transactionId:
|
|
1221
|
-
txRef
|
|
1437
|
+
eventType,
|
|
1438
|
+
transactionId: providerTransactionId !== void 0 && Number.isSafeInteger(Number(providerTransactionId)) ? Number(providerTransactionId) : void 0,
|
|
1439
|
+
txRef,
|
|
1222
1440
|
payload: rawBody,
|
|
1223
1441
|
status: "processing",
|
|
1224
1442
|
createdAt: now,
|
|
@@ -1236,12 +1454,14 @@ const flutterwaveWebhook = (options, path) => createAuthEndpoint(path, {
|
|
|
1236
1454
|
if (!await store.claimWebhookEvent(existingEvent, now)) throw busy();
|
|
1237
1455
|
}
|
|
1238
1456
|
try {
|
|
1239
|
-
|
|
1240
|
-
|
|
1457
|
+
const v3TransactionRef = "event" in event ? event.data.tx_ref : void 0;
|
|
1458
|
+
if (v3TransactionRef && "event" in event && event.data.id !== void 0) {
|
|
1459
|
+
const data = event.data;
|
|
1460
|
+
const local = await store.findTransactionByTxRef(v3TransactionRef);
|
|
1241
1461
|
if (!local) throw new Error("The webhook payment has not been recorded locally yet");
|
|
1242
1462
|
const verified = await adapter$1(options).verifyTransaction({ transactionId: Number(data.id) });
|
|
1243
1463
|
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);
|
|
1464
|
+
await recordVerifiedPayment(ctx, options, local, verified, event);
|
|
1245
1465
|
Object.assign(data, {
|
|
1246
1466
|
id: verified.id,
|
|
1247
1467
|
tx_ref: verified.tx_ref,
|
|
@@ -1250,6 +1470,38 @@ const flutterwaveWebhook = (options, path) => createAuthEndpoint(path, {
|
|
|
1250
1470
|
status: verified.status
|
|
1251
1471
|
});
|
|
1252
1472
|
}
|
|
1473
|
+
if ("event" in event && event.event === "subscription.cancelled") {
|
|
1474
|
+
const customerEmail = event.data.customer?.email;
|
|
1475
|
+
const planId = Number(event.data.plan?.id);
|
|
1476
|
+
if (customerEmail && Number.isInteger(planId) && planId > 0) {
|
|
1477
|
+
const matches = await store.findSubscriptionsByBillingEmailAndPlanId(customerEmail, planId);
|
|
1478
|
+
if (matches.length === 1) {
|
|
1479
|
+
const match = matches[0];
|
|
1480
|
+
const now = /* @__PURE__ */ new Date();
|
|
1481
|
+
const scheduledEnd = match.cancelAt ?? match.periodEnd;
|
|
1482
|
+
const keepPaidAccess = match.status !== "canceled" && match.endedAt == null && match.cancelAtPeriodEnd && scheduledEnd != null && new Date(scheduledEnd).getTime() > now.getTime();
|
|
1483
|
+
const subscription = await store.updateSubscription(match.id, {
|
|
1484
|
+
status: keepPaidAccess ? match.status : "canceled",
|
|
1485
|
+
cancelAtPeriodEnd: keepPaidAccess,
|
|
1486
|
+
cancelAt: keepPaidAccess ? scheduledEnd : null,
|
|
1487
|
+
canceledAt: match.canceledAt ?? now,
|
|
1488
|
+
endedAt: keepPaidAccess ? null : match.endedAt ?? now,
|
|
1489
|
+
updatedAt: now
|
|
1490
|
+
}) ?? match;
|
|
1491
|
+
const callbackData = {
|
|
1492
|
+
event,
|
|
1493
|
+
subscription
|
|
1494
|
+
};
|
|
1495
|
+
await options.subscription?.onSubscriptionCancel?.(callbackData, ctx);
|
|
1496
|
+
const plan = await getPlans(options.subscription).then((plans) => plans.find((candidate) => candidate.name.toLowerCase() === match.plan.toLowerCase()));
|
|
1497
|
+
if (plan) await options.subscription?.onSubscriptionUpdate?.({
|
|
1498
|
+
...callbackData,
|
|
1499
|
+
subscription,
|
|
1500
|
+
plan
|
|
1501
|
+
}, ctx);
|
|
1502
|
+
} else if (matches.length > 1) ctx.context.logger.warn("Flutterwave cancellation event matched multiple local subscriptions; manual reconciliation is required");
|
|
1503
|
+
}
|
|
1504
|
+
}
|
|
1253
1505
|
await options.onEvent?.(event);
|
|
1254
1506
|
await store.updateWebhookEvent(eventId, {
|
|
1255
1507
|
status: "processed",
|
|
@@ -1674,6 +1926,182 @@ const getSchema = (options) => {
|
|
|
1674
1926
|
return mergeSchema(baseSchema, optionSchema);
|
|
1675
1927
|
};
|
|
1676
1928
|
//#endregion
|
|
1929
|
+
//#region src/flutterwave-v4.ts
|
|
1930
|
+
const DEFAULT_IDENTITY_URL = "https://idp.flutterwave.com/realms/flutterwave/protocol/openid-connect/token";
|
|
1931
|
+
const DEFAULT_API_URL = "https://f4bexperience.flutterwave.com";
|
|
1932
|
+
/**
|
|
1933
|
+
* Create a server-only Flutterwave v4 transport. It accepts encrypted card
|
|
1934
|
+
* fields only; raw PAN/CVV handling belongs in a PCI-compliant client flow.
|
|
1935
|
+
*/
|
|
1936
|
+
function createFlutterwaveV4Adapter(options) {
|
|
1937
|
+
if (!options.clientId || !options.clientSecret) throw new Error("Flutterwave v4 clientId and clientSecret are required");
|
|
1938
|
+
const fetchImpl = options.fetch ?? globalThis.fetch;
|
|
1939
|
+
if (typeof fetchImpl !== "function") throw new Error("Fetch is not available");
|
|
1940
|
+
const baseUrl = (options.apiBaseUrl ?? DEFAULT_API_URL).replace(/\/+$/, "");
|
|
1941
|
+
const identityUrl = options.identityUrl ?? DEFAULT_IDENTITY_URL;
|
|
1942
|
+
const now = options.now ?? Date.now;
|
|
1943
|
+
let token;
|
|
1944
|
+
let refreshAt = 0;
|
|
1945
|
+
let tokenRequest;
|
|
1946
|
+
const getToken = async () => {
|
|
1947
|
+
if (token !== void 0 && token.length > 0 && now() < refreshAt) return token;
|
|
1948
|
+
if (tokenRequest) return tokenRequest;
|
|
1949
|
+
tokenRequest = (async () => {
|
|
1950
|
+
const response = await fetchImpl(identityUrl, {
|
|
1951
|
+
method: "POST",
|
|
1952
|
+
headers: { "content-type": "application/x-www-form-urlencoded" },
|
|
1953
|
+
body: new URLSearchParams({
|
|
1954
|
+
client_id: options.clientId,
|
|
1955
|
+
client_secret: options.clientSecret,
|
|
1956
|
+
grant_type: "client_credentials"
|
|
1957
|
+
})
|
|
1958
|
+
});
|
|
1959
|
+
const raw = await parseJson(response, "authenticate");
|
|
1960
|
+
const accessToken = field(raw, "access_token");
|
|
1961
|
+
const expiresIn = Number(field(raw, "expires_in"));
|
|
1962
|
+
if (!response.ok || typeof accessToken !== "string" || !Number.isFinite(expiresIn)) throw v4Error("authenticate", response.status, raw);
|
|
1963
|
+
token = accessToken;
|
|
1964
|
+
refreshAt = now() + Math.max(0, expiresIn - 60) * 1e3;
|
|
1965
|
+
return accessToken;
|
|
1966
|
+
})().finally(() => {
|
|
1967
|
+
tokenRequest = void 0;
|
|
1968
|
+
});
|
|
1969
|
+
return tokenRequest;
|
|
1970
|
+
};
|
|
1971
|
+
const request = async (operation, path, input = {}, allowAuthRetry = true) => {
|
|
1972
|
+
const method = input.method ?? "GET";
|
|
1973
|
+
if (method !== "GET") validateIdempotencyKey(input.idempotencyKey);
|
|
1974
|
+
if (input.traceId !== void 0) validateTraceId(input.traceId);
|
|
1975
|
+
const headers = new Headers({
|
|
1976
|
+
accept: "application/json",
|
|
1977
|
+
authorization: `Bearer ${await getToken()}`,
|
|
1978
|
+
"content-type": "application/json"
|
|
1979
|
+
});
|
|
1980
|
+
if (input.idempotencyKey !== void 0) headers.set("x-idempotency-key", input.idempotencyKey);
|
|
1981
|
+
if (input.traceId !== void 0) headers.set("x-trace-id", input.traceId);
|
|
1982
|
+
const response = await fetchImpl(`${baseUrl}${path}`, {
|
|
1983
|
+
method,
|
|
1984
|
+
headers,
|
|
1985
|
+
...input.body === void 0 ? {} : { body: JSON.stringify(input.body) }
|
|
1986
|
+
});
|
|
1987
|
+
const raw = await parseJson(response, operation);
|
|
1988
|
+
if (response.status === 401 && allowAuthRetry) {
|
|
1989
|
+
token = void 0;
|
|
1990
|
+
refreshAt = 0;
|
|
1991
|
+
return request(operation, path, input, false);
|
|
1992
|
+
}
|
|
1993
|
+
if (!response.ok) throw v4Error(operation, response.status, raw);
|
|
1994
|
+
const status = field(raw, "status");
|
|
1995
|
+
const data = field(raw, "data");
|
|
1996
|
+
if (status !== "success" || !isObject(data) || typeof data.id !== "string") throw new Error(`Flutterwave v4 ${operation} returned an invalid response`);
|
|
1997
|
+
return data;
|
|
1998
|
+
};
|
|
1999
|
+
const withTraceId = (value) => value ?? randomBytes(16).toString("hex");
|
|
2000
|
+
return {
|
|
2001
|
+
createCustomer: async (input) => {
|
|
2002
|
+
const { idempotencyKey, traceId, ...body } = input;
|
|
2003
|
+
if (!input.email.includes("@")) throw new Error("A valid customer email is required");
|
|
2004
|
+
return request("create customer", "/customers", {
|
|
2005
|
+
method: "POST",
|
|
2006
|
+
body,
|
|
2007
|
+
idempotencyKey,
|
|
2008
|
+
traceId: withTraceId(traceId)
|
|
2009
|
+
});
|
|
2010
|
+
},
|
|
2011
|
+
createCardPaymentMethod: async (input) => {
|
|
2012
|
+
const { idempotencyKey, traceId, customerId, ...card } = input;
|
|
2013
|
+
if (Object.values(card).some((value) => typeof value !== "string" || value.length === 0)) throw new Error("Flutterwave v4 requires encrypted card fields and a nonce");
|
|
2014
|
+
return request("create payment method", "/payment-methods", {
|
|
2015
|
+
method: "POST",
|
|
2016
|
+
body: {
|
|
2017
|
+
type: "card",
|
|
2018
|
+
card,
|
|
2019
|
+
...customerId !== void 0 ? { customer_id: customerId } : {}
|
|
2020
|
+
},
|
|
2021
|
+
idempotencyKey,
|
|
2022
|
+
traceId: withTraceId(traceId)
|
|
2023
|
+
});
|
|
2024
|
+
},
|
|
2025
|
+
createCharge: async (input) => {
|
|
2026
|
+
validateReference(input.reference);
|
|
2027
|
+
if (!Number.isFinite(input.amount) || input.amount < .01) throw new Error("Flutterwave v4 charge amount must be at least 0.01");
|
|
2028
|
+
const { idempotencyKey, traceId, customerId, paymentMethodId, redirectUrl, ...charge } = input;
|
|
2029
|
+
return request("create charge", "/charges", {
|
|
2030
|
+
method: "POST",
|
|
2031
|
+
body: {
|
|
2032
|
+
...charge,
|
|
2033
|
+
customer_id: customerId,
|
|
2034
|
+
payment_method_id: paymentMethodId,
|
|
2035
|
+
...redirectUrl !== void 0 ? { redirect_url: redirectUrl } : {}
|
|
2036
|
+
},
|
|
2037
|
+
idempotencyKey,
|
|
2038
|
+
traceId: withTraceId(traceId)
|
|
2039
|
+
});
|
|
2040
|
+
},
|
|
2041
|
+
retrieveCharge: async (chargeId) => {
|
|
2042
|
+
if (!chargeId) throw new Error("Flutterwave v4 charge id is required");
|
|
2043
|
+
return request("retrieve charge", `/charges/${encodeURIComponent(chargeId)}`);
|
|
2044
|
+
},
|
|
2045
|
+
updateChargeAuthorization: async (input) => {
|
|
2046
|
+
if (!input.chargeId) throw new Error("Flutterwave v4 charge id is required");
|
|
2047
|
+
return request("update charge authorization", `/charges/${encodeURIComponent(input.chargeId)}`, {
|
|
2048
|
+
method: "PUT",
|
|
2049
|
+
body: { authorization: input.authorization },
|
|
2050
|
+
idempotencyKey: input.idempotencyKey,
|
|
2051
|
+
traceId: withTraceId(input.traceId)
|
|
2052
|
+
});
|
|
2053
|
+
},
|
|
2054
|
+
createRefund: async (input) => {
|
|
2055
|
+
if (!input.chargeId || !isV4RefundReason(input.reason)) throw new Error("Flutterwave v4 refund chargeId and reason are required");
|
|
2056
|
+
if (!Number.isFinite(input.amount) || input.amount < .01) throw new Error("Flutterwave v4 refund amount must be at least 0.01");
|
|
2057
|
+
const { idempotencyKey, traceId, chargeId, ...refund } = input;
|
|
2058
|
+
return request("create refund", "/refunds", {
|
|
2059
|
+
method: "POST",
|
|
2060
|
+
body: {
|
|
2061
|
+
charge_id: chargeId,
|
|
2062
|
+
...refund
|
|
2063
|
+
},
|
|
2064
|
+
idempotencyKey,
|
|
2065
|
+
traceId: withTraceId(traceId)
|
|
2066
|
+
});
|
|
2067
|
+
}
|
|
2068
|
+
};
|
|
2069
|
+
}
|
|
2070
|
+
async function parseJson(response, operation) {
|
|
2071
|
+
try {
|
|
2072
|
+
return await response.json();
|
|
2073
|
+
} catch (cause) {
|
|
2074
|
+
throw new Error(`Flutterwave v4 ${operation} returned non-JSON HTTP ${response.status}`, { cause });
|
|
2075
|
+
}
|
|
2076
|
+
}
|
|
2077
|
+
function isObject(value) {
|
|
2078
|
+
return typeof value === "object" && value !== null;
|
|
2079
|
+
}
|
|
2080
|
+
function field(value, key) {
|
|
2081
|
+
return isObject(value) ? value[key] : void 0;
|
|
2082
|
+
}
|
|
2083
|
+
function validateIdempotencyKey(value) {
|
|
2084
|
+
if (value === void 0 || value.length === 0 || !/^[\x21-\x7E]{12,255}$/.test(value)) throw new Error("Flutterwave v4 idempotency keys must be 12-255 printable ASCII characters");
|
|
2085
|
+
}
|
|
2086
|
+
function validateTraceId(value) {
|
|
2087
|
+
if (!/^[\x21-\x7E]{12,255}$/.test(value)) throw new Error("Flutterwave v4 trace ids must be 12-255 printable ASCII characters");
|
|
2088
|
+
}
|
|
2089
|
+
function validateReference(value) {
|
|
2090
|
+
if (!/^[A-Za-z0-9-]{6,42}$/.test(value)) throw new Error("Flutterwave v4 references must be 6-42 letters, digits, or hyphens");
|
|
2091
|
+
}
|
|
2092
|
+
function isV4RefundReason(value) {
|
|
2093
|
+
return value === "duplicate" || value === "fraudulent" || value === "requested_by_customer" || value === "expired_uncaptured_charge";
|
|
2094
|
+
}
|
|
2095
|
+
function v4Error(operation, status, raw) {
|
|
2096
|
+
const message = field(field(raw, "error"), "message") ?? field(raw, "message");
|
|
2097
|
+
const error = new Error(typeof message === "string" ? message : `Flutterwave v4 ${operation} failed with HTTP ${status}`);
|
|
2098
|
+
Object.assign(error, {
|
|
2099
|
+
status,
|
|
2100
|
+
retryable: status === 408 || status === 429 || status >= 500
|
|
2101
|
+
});
|
|
2102
|
+
return error;
|
|
2103
|
+
}
|
|
2104
|
+
//#endregion
|
|
1677
2105
|
//#region src/limits.ts
|
|
1678
2106
|
const checkSeatLimit = async (ctx, organizationId, seatsToAdd = 1) => {
|
|
1679
2107
|
const store = createBillingStore(ctx);
|
|
@@ -1742,86 +2170,167 @@ async function chargeSubscriptionRenewal(ctx, options, input) {
|
|
|
1742
2170
|
return (typeof configured === "function" ? await configured() : configured ?? []).find((candidate) => candidate.name === subscription.plan) ?? null;
|
|
1743
2171
|
})();
|
|
1744
2172
|
const amount = input.amount ?? (plan ? calculatePlanAmount(plan, subscription.seats) : void 0);
|
|
1745
|
-
if (!amount || !plan?.currency || !subscription.billingEmail) throw new APIError("BAD_REQUEST", { message: "Subscription billing details are incomplete" });
|
|
1746
|
-
|
|
1747
|
-
const
|
|
1748
|
-
|
|
1749
|
-
|
|
1750
|
-
|
|
1751
|
-
|
|
1752
|
-
|
|
1753
|
-
|
|
1754
|
-
|
|
2173
|
+
if (amount === void 0 || !Number.isFinite(amount) || amount <= 0 || !plan?.currency || !subscription.billingEmail) throw new APIError("BAD_REQUEST", { message: "Subscription billing details are incomplete" });
|
|
2174
|
+
if (input.renewalId !== void 0 && (input.renewalId.length === 0 || input.renewalId.length > 255)) throw new APIError("BAD_REQUEST", { message: "renewalId must contain 1-255 characters" });
|
|
2175
|
+
const priorTransaction = subscription.txRef ? await store.findTransactionByTxRef(subscription.txRef) : null;
|
|
2176
|
+
const priorMetadata = parseFlutterwaveMetadata(priorTransaction?.metadata);
|
|
2177
|
+
const priorOperationId = typeof priorMetadata.renewalOperationId === "string" ? priorMetadata.renewalOperationId : void 0;
|
|
2178
|
+
const priorOperation = priorOperationId ? await store.findWebhookEvent(priorOperationId) : null;
|
|
2179
|
+
const unfinishedPrior = priorOperation !== null && priorOperation.status !== "processed";
|
|
2180
|
+
const period = subscription.periodEnd == null ? "initial" : new Date(subscription.periodEnd).toISOString();
|
|
2181
|
+
const intent = input.renewalId ?? period;
|
|
2182
|
+
const digest = createHash("sha256").update(JSON.stringify([subscription.id, intent])).digest("hex");
|
|
2183
|
+
const operationId = input.renewalId === void 0 && unfinishedPrior ? priorOperationId : `internal:renewal:${digest}`;
|
|
2184
|
+
const txRef = input.renewalId === void 0 && unfinishedPrior && priorTransaction ? priorTransaction.txRef : `flw_renewal_${digest.slice(0, 40)}`;
|
|
2185
|
+
if (unfinishedPrior && operationId !== priorOperationId) throw new APIError("SERVICE_UNAVAILABLE", { message: "A previous renewal requires reconciliation before starting another intent" });
|
|
2186
|
+
const requestedOperation = await store.findWebhookEvent(operationId);
|
|
2187
|
+
if (!unfinishedPrior && requestedOperation === null && subscription.periodEnd != null && new Date(subscription.periodEnd) > /* @__PURE__ */ new Date()) throw new APIError("BAD_REQUEST", { message: "The subscription is not due for renewal" });
|
|
2188
|
+
let operation = await acquireOperation(store, {
|
|
2189
|
+
eventId: operationId,
|
|
2190
|
+
eventType: "internal.subscription.renewal",
|
|
2191
|
+
txRef,
|
|
2192
|
+
payload: JSON.stringify({
|
|
2193
|
+
phase: "reserved",
|
|
2194
|
+
txRef,
|
|
1755
2195
|
amount,
|
|
1756
2196
|
currency: plan.currency,
|
|
1757
|
-
|
|
1758
|
-
|
|
1759
|
-
|
|
1760
|
-
|
|
1761
|
-
|
|
1762
|
-
await store
|
|
1763
|
-
|
|
2197
|
+
period
|
|
2198
|
+
})
|
|
2199
|
+
});
|
|
2200
|
+
const progress = renewalIntentSchema.parse(JSON.parse(operation.payload));
|
|
2201
|
+
if (progress.amount !== amount || progress.currency !== plan.currency) {
|
|
2202
|
+
if (operation.status !== "processed") await failOperation(store, operation);
|
|
2203
|
+
throw new APIError("BAD_REQUEST", { message: "The renewal intent amount or currency has changed" });
|
|
2204
|
+
}
|
|
2205
|
+
const provider = adapter(options);
|
|
2206
|
+
try {
|
|
2207
|
+
let transaction = await store.findTransactionByTxRef(progress.txRef);
|
|
2208
|
+
transaction ??= await store.createTransaction({
|
|
2209
|
+
txRef: progress.txRef,
|
|
1764
2210
|
referenceId: subscription.referenceId,
|
|
1765
2211
|
userId: subscription.userId,
|
|
1766
2212
|
amount,
|
|
1767
2213
|
currency: plan.currency,
|
|
1768
2214
|
status: "pending",
|
|
1769
2215
|
plan: subscription.plan,
|
|
1770
|
-
metadata
|
|
1771
|
-
|
|
1772
|
-
|
|
2216
|
+
metadata: stringifyFlutterwaveMetadata({
|
|
2217
|
+
...createRenewalMetadata({
|
|
2218
|
+
subscriptionId: subscription.id,
|
|
2219
|
+
referenceId: subscription.referenceId
|
|
2220
|
+
}),
|
|
2221
|
+
renewalOperationId: operationId
|
|
2222
|
+
}),
|
|
2223
|
+
createdAt: /* @__PURE__ */ new Date(),
|
|
2224
|
+
updatedAt: /* @__PURE__ */ new Date()
|
|
1773
2225
|
});
|
|
1774
|
-
|
|
1775
|
-
txRef
|
|
1776
|
-
|
|
1777
|
-
|
|
2226
|
+
if (operation.status === "processed") {
|
|
2227
|
+
const verified = await provider.verifyTransaction({ txRef: progress.txRef });
|
|
2228
|
+
await recordVerifiedPayment(ctx, options, transaction, verified);
|
|
2229
|
+
return renewalResult(verified);
|
|
2230
|
+
}
|
|
2231
|
+
if (progress.phase === "reserved") {
|
|
2232
|
+
if (progress.period !== period) throw new APIError("BAD_REQUEST", { message: "The reserved renewal period has already changed" });
|
|
2233
|
+
if (!subscription.encryptedPaymentToken && !input.redirectUrl) throw new APIError("BAD_REQUEST", { message: "redirectUrl is required when the subscription has no reusable payment token" });
|
|
2234
|
+
if (!await store.updateCurrentSubscription(subscription, {
|
|
2235
|
+
txRef: progress.txRef,
|
|
2236
|
+
status: "past_due",
|
|
2237
|
+
updatedAt: /* @__PURE__ */ new Date()
|
|
2238
|
+
})) throw new APIError("SERVICE_UNAVAILABLE", { message: "Subscription changed while reserving renewal; retry later" });
|
|
2239
|
+
const token = subscription.encryptedPaymentToken ? await decryptPaymentToken(subscription.encryptedPaymentToken, ctx.context.secret) : null;
|
|
2240
|
+
progress.phase = "submitted";
|
|
2241
|
+
operation = await checkpointOperation(store, operation, { payload: JSON.stringify(progress) });
|
|
2242
|
+
if (token === null) {
|
|
2243
|
+
const checkout = await provider.initializePayment({
|
|
2244
|
+
tx_ref: progress.txRef,
|
|
2245
|
+
amount,
|
|
2246
|
+
currency: plan.currency,
|
|
2247
|
+
redirect_url: input.redirectUrl,
|
|
2248
|
+
customer: { email: subscription.billingEmail },
|
|
2249
|
+
meta: parseFlutterwaveMetadata(transaction.metadata)
|
|
2250
|
+
});
|
|
2251
|
+
progress.checkoutUrl = checkout.link;
|
|
2252
|
+
progress.phase = "checkout";
|
|
2253
|
+
operation = await checkpointOperation(store, operation, {
|
|
2254
|
+
payload: JSON.stringify(progress),
|
|
2255
|
+
status: "failed"
|
|
2256
|
+
});
|
|
2257
|
+
return {
|
|
2258
|
+
status: "pending",
|
|
2259
|
+
data: {
|
|
2260
|
+
kind: "checkout",
|
|
2261
|
+
url: checkout.link,
|
|
2262
|
+
txRef: progress.txRef,
|
|
2263
|
+
redirect: true
|
|
2264
|
+
}
|
|
2265
|
+
};
|
|
2266
|
+
}
|
|
2267
|
+
const charged = await provider.chargeToken({
|
|
2268
|
+
token,
|
|
2269
|
+
amount,
|
|
2270
|
+
currency: plan.currency,
|
|
2271
|
+
email: subscription.billingEmail,
|
|
2272
|
+
tx_ref: progress.txRef
|
|
2273
|
+
});
|
|
2274
|
+
transaction = await store.updateTransactionByTxRef(progress.txRef, {
|
|
2275
|
+
transactionId: charged.id,
|
|
2276
|
+
updatedAt: /* @__PURE__ */ new Date()
|
|
2277
|
+
}) ?? transaction;
|
|
2278
|
+
const verified = await provider.verifyTransaction({ transactionId: charged.id });
|
|
2279
|
+
await recordVerifiedPayment(ctx, options, transaction, verified);
|
|
2280
|
+
operation = await checkpointOperation(store, operation, {
|
|
2281
|
+
status: verified.status === "pending" ? "failed" : "processed",
|
|
2282
|
+
processedAt: verified.status === "pending" ? void 0 : /* @__PURE__ */ new Date()
|
|
2283
|
+
});
|
|
2284
|
+
return renewalResult(verified);
|
|
2285
|
+
}
|
|
2286
|
+
if (progress.checkoutUrl !== void 0 && transaction.status === "pending") {
|
|
2287
|
+
operation = await checkpointOperation(store, operation, { status: "failed" });
|
|
2288
|
+
return {
|
|
2289
|
+
status: "pending",
|
|
2290
|
+
data: {
|
|
2291
|
+
kind: "checkout",
|
|
2292
|
+
url: progress.checkoutUrl,
|
|
2293
|
+
txRef: progress.txRef,
|
|
2294
|
+
redirect: true
|
|
2295
|
+
}
|
|
2296
|
+
};
|
|
2297
|
+
}
|
|
2298
|
+
const verified = await provider.verifyTransaction({ txRef: progress.txRef });
|
|
2299
|
+
await recordVerifiedPayment(ctx, options, transaction, verified);
|
|
2300
|
+
operation = await checkpointOperation(store, operation, {
|
|
2301
|
+
status: verified.status === "pending" ? "failed" : "processed",
|
|
2302
|
+
processedAt: verified.status === "pending" ? void 0 : /* @__PURE__ */ new Date()
|
|
1778
2303
|
});
|
|
1779
|
-
return {
|
|
2304
|
+
if (verified.status === "pending" && progress.checkoutUrl !== void 0) return {
|
|
1780
2305
|
status: "pending",
|
|
1781
2306
|
data: {
|
|
1782
2307
|
kind: "checkout",
|
|
1783
|
-
url:
|
|
1784
|
-
txRef,
|
|
2308
|
+
url: progress.checkoutUrl,
|
|
2309
|
+
txRef: progress.txRef,
|
|
1785
2310
|
redirect: true
|
|
1786
2311
|
}
|
|
1787
2312
|
};
|
|
2313
|
+
return renewalResult(verified);
|
|
2314
|
+
} catch (error) {
|
|
2315
|
+
if (operation.status !== "processed") await failOperation(store, operation);
|
|
2316
|
+
throw error;
|
|
1788
2317
|
}
|
|
1789
|
-
|
|
1790
|
-
|
|
1791
|
-
|
|
1792
|
-
|
|
1793
|
-
|
|
1794
|
-
|
|
1795
|
-
|
|
1796
|
-
|
|
1797
|
-
|
|
1798
|
-
|
|
1799
|
-
|
|
1800
|
-
|
|
1801
|
-
|
|
1802
|
-
|
|
1803
|
-
flwRef: verified.flw_ref,
|
|
1804
|
-
referenceId: subscription.referenceId,
|
|
1805
|
-
userId: subscription.userId,
|
|
1806
|
-
amount,
|
|
1807
|
-
chargedAmount: verified.charged_amount,
|
|
1808
|
-
currency: plan.currency,
|
|
1809
|
-
status: "pending",
|
|
1810
|
-
plan: subscription.plan,
|
|
1811
|
-
paymentType: verified.payment_type,
|
|
1812
|
-
metadata,
|
|
1813
|
-
createdAt: now,
|
|
1814
|
-
updatedAt: now
|
|
1815
|
-
});
|
|
1816
|
-
await store.updateSubscription(subscription.id, {
|
|
1817
|
-
txRef,
|
|
1818
|
-
status: "past_due",
|
|
1819
|
-
reconciledAt: now,
|
|
1820
|
-
updatedAt: now
|
|
1821
|
-
});
|
|
1822
|
-
await recordVerifiedPayment(ctx, options, transaction, verified);
|
|
2318
|
+
}
|
|
2319
|
+
const renewalIntentSchema = z.object({
|
|
2320
|
+
phase: z.enum([
|
|
2321
|
+
"reserved",
|
|
2322
|
+
"submitted",
|
|
2323
|
+
"checkout"
|
|
2324
|
+
]),
|
|
2325
|
+
txRef: z.string().min(1),
|
|
2326
|
+
amount: z.number().positive(),
|
|
2327
|
+
currency: z.string().min(1),
|
|
2328
|
+
period: z.string().min(1),
|
|
2329
|
+
checkoutUrl: z.string().optional()
|
|
2330
|
+
});
|
|
2331
|
+
function renewalResult(verified) {
|
|
1823
2332
|
return {
|
|
1824
|
-
status: verified.status === "successful" ? "success" : "failed",
|
|
2333
|
+
status: verified.status === "successful" ? "success" : verified.status === "pending" ? "pending" : "failed",
|
|
1825
2334
|
data: {
|
|
1826
2335
|
id: verified.id,
|
|
1827
2336
|
txRef: verified.tx_ref,
|
|
@@ -1856,15 +2365,11 @@ async function processScheduledFlutterwaveCancellations(ctx, options, input = {}
|
|
|
1856
2365
|
hasMore: due.length === limit
|
|
1857
2366
|
};
|
|
1858
2367
|
}
|
|
1859
|
-
function parseMetadata(value) {
|
|
1860
|
-
if (!value) return void 0;
|
|
1861
|
-
return JSON.parse(value);
|
|
1862
|
-
}
|
|
1863
2368
|
async function refundFlutterwaveTransaction(ctx, options, input) {
|
|
1864
2369
|
const store = createBillingStore(ctx);
|
|
1865
2370
|
const transaction = await store.findTransactionById(input.transactionId);
|
|
1866
2371
|
if (!transaction) throw new APIError("NOT_FOUND", { message: "Transaction not found" });
|
|
1867
|
-
const result = await adapter(options).refundTransaction(input.transactionId, input.amount);
|
|
2372
|
+
const result = await adapter(options).refundTransaction(input.transactionId, input.amount, input.reason);
|
|
1868
2373
|
const now = /* @__PURE__ */ new Date();
|
|
1869
2374
|
return store.createRefund({
|
|
1870
2375
|
refundId: result.id,
|
|
@@ -1927,11 +2432,11 @@ async function reconcileFlutterwaveTransaction(ctx, options, input) {
|
|
|
1927
2432
|
};
|
|
1928
2433
|
}
|
|
1929
2434
|
const refundEnvelopeSchema = z.object({
|
|
1930
|
-
status: z.
|
|
2435
|
+
status: z.literal("success"),
|
|
1931
2436
|
data: z.object({
|
|
1932
|
-
id: z.coerce.number().
|
|
1933
|
-
status: z.string(),
|
|
1934
|
-
amount_refunded: z.coerce.number().optional()
|
|
2437
|
+
id: z.coerce.number().int().positive(),
|
|
2438
|
+
status: z.string().min(1),
|
|
2439
|
+
amount_refunded: z.coerce.number().nonnegative().optional()
|
|
1935
2440
|
})
|
|
1936
2441
|
});
|
|
1937
2442
|
async function reconcileFlutterwaveRefunds(ctx, options) {
|
|
@@ -1945,7 +2450,7 @@ async function reconcileFlutterwaveRefunds(ctx, options) {
|
|
|
1945
2450
|
const response = await fetchImpl(`${baseUrl}/v3/refunds/${refund.refundId}`, { headers: { authorization: `Bearer ${options.secretKey}` } });
|
|
1946
2451
|
if (!response.ok) continue;
|
|
1947
2452
|
const parsed = refundEnvelopeSchema.safeParse(await response.json());
|
|
1948
|
-
if (!parsed.success) continue;
|
|
2453
|
+
if (!parsed.success || parsed.data.data.id !== refund.refundId) continue;
|
|
1949
2454
|
await store.updateRefund(refund.id, {
|
|
1950
2455
|
status: parsed.data.data.status,
|
|
1951
2456
|
amount: parsed.data.data.amount_refunded ?? refund.amount,
|
|
@@ -1991,6 +2496,6 @@ const flutterwave = (options) => {
|
|
|
1991
2496
|
};
|
|
1992
2497
|
};
|
|
1993
2498
|
//#endregion
|
|
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 };
|
|
2499
|
+
export { FlutterwaveAdapterError, chargeSubscriptionRenewal, checkSeatLimit, checkTeamLimit, createCheckoutMetadata, createFlutterwaveAdapter, createFlutterwaveV4Adapter, createProrationMetadata, createRenewalMetadata, decryptPaymentToken, encryptPaymentToken, flutterwave, getMetadataBoolean, getMetadataNumber, getMetadataString, getOrganizationEntitlements, hasFlutterwaveMetadata, parseFlutterwaveMetadata, processScheduledFlutterwaveCancellations, reconcileFlutterwaveRefunds, reconcileFlutterwaveTransaction, refundFlutterwaveTransaction, stringifyFlutterwaveMetadata, syncFlutterwavePlans };
|
|
1995
2500
|
|
|
1996
2501
|
//# sourceMappingURL=index.mjs.map
|