better-auth-flutterwave 0.3.1 → 0.4.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/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-C3pJ_ZLK.mjs";
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-CceayuXv.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: [{
@@ -465,7 +472,10 @@ function createHttpClient(fetchImpl, apiBaseUrl, secretKey) {
465
472
  Transaction: {
466
473
  verify: ({ id }) => request(`/v3/transactions/${id}/verify`),
467
474
  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 })
475
+ refund: ({ id, amount, comments }) => post(`/v3/transactions/${id}/refund`, {
476
+ ...amount === void 0 ? {} : { amount },
477
+ ...comments === void 0 ? {} : { comments }
478
+ })
469
479
  },
470
480
  PaymentPlan: { get_all: (query) => request(`/v3/payment-plans${queryString(query)}`) },
471
481
  Subscription: {
@@ -564,9 +574,10 @@ function createFlutterwaveAdapter(options) {
564
574
  const body = tokenChargeInputSchema.parse(input);
565
575
  return sdkCall("charge token", () => client.Tokenized.charge(body), transactionSchema);
566
576
  },
567
- refundTransaction: (transactionId, amount) => sdkCall("refund transaction", () => client.Transaction.refund({
577
+ refundTransaction: (transactionId, amount, reason) => sdkCall("refund transaction", () => client.Transaction.refund({
568
578
  id: positiveIdSchema.parse(transactionId),
569
- amount: optionalPositiveAmountSchema.parse(amount)
579
+ amount: optionalPositiveAmountSchema.parse(amount),
580
+ ...reason === void 0 ? {} : { comments: z.string().min(1).parse(reason) }
570
581
  }), refundSchema)
571
582
  };
572
583
  }
@@ -689,7 +700,7 @@ function paymentMatches(expected, verified) {
689
700
  return verified.tx_ref === expected.txRef && verified.amount === expected.amount && verified.currency === expected.currency;
690
701
  }
691
702
  /** Shared fulfillment for browser verification, webhooks, and trusted reconciliation. */
692
- async function recordVerifiedPayment(ctx, options, expected, verified) {
703
+ async function recordVerifiedPayment(ctx, options, expected, verified, webhookEvent) {
693
704
  if (!paymentMatches(expected, verified)) throw new APIError("BAD_REQUEST", { message: "Verified transaction does not match the expected payment" });
694
705
  const store = createBillingStore(ctx);
695
706
  const now = /* @__PURE__ */ new Date();
@@ -733,7 +744,7 @@ async function recordVerifiedPayment(ctx, options, expected, verified) {
733
744
  const priorEnd = subscription.periodEnd ? new Date(subscription.periodEnd) : null;
734
745
  const periodStart = renewal && priorEnd !== null && priorEnd > paymentTime ? priorEnd : paymentTime;
735
746
  const advancePeriod = subscription.periodEnd == null || (renewal ? subscription.status === "past_due" : expected.status !== "successful");
736
- if (await store.updateCurrentSubscription(subscription, {
747
+ const update = {
737
748
  subscriptionId,
738
749
  status: identified ? "active" : "incomplete",
739
750
  encryptedPaymentToken: verified.card?.token !== void 0 ? await encryptPaymentToken(verified.card.token, ctx.context.secret) : subscription.encryptedPaymentToken,
@@ -743,7 +754,45 @@ async function recordVerifiedPayment(ctx, options, expected, verified) {
743
754
  } : {},
744
755
  reconciledAt: now,
745
756
  updatedAt: now
746
- }) && identified) await store.retireCompetingSubscriptions(subscription.referenceId, group, subscription.id);
757
+ };
758
+ if (await store.updateCurrentSubscription(subscription, update) && identified) {
759
+ const plan = (await getPlans(options.subscription)).find((candidate) => candidate.name.toLowerCase() === subscription.plan.toLowerCase());
760
+ if (plan) {
761
+ const callbackEvent = webhookEvent ?? {
762
+ event: "charge.completed",
763
+ data: {
764
+ id: verified.id,
765
+ tx_ref: verified.tx_ref,
766
+ ...verified.flw_ref !== void 0 && verified.flw_ref !== null && verified.flw_ref !== "" ? { flw_ref: verified.flw_ref } : {},
767
+ status: verified.status,
768
+ amount: verified.amount,
769
+ currency: verified.currency
770
+ }
771
+ };
772
+ const currentSubscription = {
773
+ ...subscription,
774
+ ...update
775
+ };
776
+ if (subscription.status === "incomplete") {
777
+ await options.subscription?.onSubscriptionComplete?.({
778
+ event: callbackEvent,
779
+ subscription: currentSubscription,
780
+ plan
781
+ }, ctx);
782
+ await options.subscription?.onSubscriptionCreated?.({
783
+ event: callbackEvent,
784
+ subscription: currentSubscription,
785
+ plan
786
+ }, ctx);
787
+ }
788
+ await options.subscription?.onSubscriptionUpdate?.({
789
+ event: callbackEvent,
790
+ subscription: currentSubscription,
791
+ plan
792
+ }, ctx);
793
+ }
794
+ await store.retireCompetingSubscriptions(subscription.referenceId, group, subscription.id);
795
+ }
747
796
  }
748
797
  }
749
798
  //#endregion
@@ -866,7 +915,7 @@ const verifyBodySchema = z.object({
866
915
  txRef: z.string().optional(),
867
916
  referenceId: z.string().optional()
868
917
  }).refine((body) => body.transactionId === void 0 !== (body.txRef === void 0), { message: "Provide exactly one of transactionId or txRef" });
869
- const webhookPayloadSchema = z.object({
918
+ const v3WebhookPayloadSchema = z.object({
870
919
  event: z.string().min(1),
871
920
  data: z.object({
872
921
  id: z.union([z.string(), z.number()]).optional(),
@@ -877,7 +926,25 @@ const webhookPayloadSchema = z.object({
877
926
  charged_amount: z.coerce.number().optional(),
878
927
  currency: z.string().optional(),
879
928
  payment_type: z.string().optional(),
880
- customer: z.object({ email: z.string().optional() }).passthrough().optional()
929
+ customer: z.object({ email: z.string().optional() }).passthrough().optional(),
930
+ plan: z.object({ id: z.union([z.string(), z.number()]).optional() }).passthrough().optional()
931
+ }).passthrough()
932
+ });
933
+ const v4WebhookPayloadSchema = z.object({
934
+ type: z.string().min(1),
935
+ id: z.string().optional(),
936
+ webhook_id: z.string().optional(),
937
+ timestamp: z.union([z.string(), z.number()]).optional(),
938
+ data: z.object({
939
+ id: z.string().optional(),
940
+ reference: z.string().optional(),
941
+ status: z.string().optional(),
942
+ amount: z.coerce.number().optional(),
943
+ currency: z.string().optional(),
944
+ customer: z.object({
945
+ id: z.string().optional(),
946
+ email: z.string().optional()
947
+ }).passthrough().optional()
881
948
  }).passthrough()
882
949
  });
883
950
  function adapter$1(options) {
@@ -953,6 +1020,7 @@ const initializeTransaction = (options, path) => createAuthEndpoint(path, {
953
1020
  if (ctx.body.product && !product) throw new APIError("NOT_FOUND", { message: "Product not found" });
954
1021
  if (plan && product) throw new APIError("BAD_REQUEST", { message: "Select a plan or a product, not both" });
955
1022
  if (plan) {
1023
+ 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
1024
  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
1025
  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
1026
  }
@@ -1124,13 +1192,30 @@ const cancelSubscription = (options, path) => createAuthEndpoint(path, {
1124
1192
  }
1125
1193
  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
1194
  if (local.subscriptionId != null) await adapter$1(options).cancelSubscription(local.subscriptionId);
1127
- await store.updateSubscription(local.id, {
1195
+ const canceled = await store.updateSubscription(local.id, {
1128
1196
  status: "canceled",
1129
1197
  cancelAtPeriodEnd: false,
1130
1198
  canceledAt: now,
1131
1199
  endedAt: now,
1132
1200
  updatedAt: now
1133
1201
  });
1202
+ if (canceled) {
1203
+ const plan = await getPlans(options.subscription).then((plans) => plans.find((candidate) => candidate.name.toLowerCase() === local.plan.toLowerCase()));
1204
+ if (plan) {
1205
+ const callbackData = {
1206
+ event: {
1207
+ event: "subscription.cancelled",
1208
+ data: {}
1209
+ },
1210
+ subscription: canceled
1211
+ };
1212
+ await options.subscription?.onSubscriptionCancel?.(callbackData, ctx);
1213
+ await options.subscription?.onSubscriptionUpdate?.({
1214
+ ...callbackData,
1215
+ plan
1216
+ }, ctx);
1217
+ }
1218
+ }
1134
1219
  return { status: "canceled" };
1135
1220
  });
1136
1221
  const restoreSubscription = (options, path) => createAuthEndpoint(path, {
@@ -1190,9 +1275,14 @@ const flutterwaveWebhook = (options, path) => createAuthEndpoint(path, {
1190
1275
  const request = getWebhookRequest(ctx);
1191
1276
  if (!request) throw new APIError("BAD_REQUEST", { message: "Request is missing" });
1192
1277
  const rawBody = await request.text();
1193
- const signature = getWebhookHeaders(ctx)?.get("flutterwave-signature");
1194
- if (!signature) throw new APIError("UNAUTHORIZED", { message: "Missing signature" });
1195
- if (!timingSafeEqualString(signature, await hmacSha256Base64(options.webhook?.secretHash ?? options.secretHash, rawBody))) throw new APIError("UNAUTHORIZED", { message: "Invalid signature" });
1278
+ const headers = getWebhookHeaders(ctx);
1279
+ const signature = headers?.get("flutterwave-signature");
1280
+ const legacyHash = headers?.get("verif-hash");
1281
+ const secretHash = options.webhook?.secretHash ?? options.secretHash;
1282
+ if (typeof signature !== "string" && typeof legacyHash !== "string") throw new APIError("UNAUTHORIZED", { message: "Missing signature" });
1283
+ const validV4Signature = typeof signature === "string" && timingSafeEqualString(signature, await hmacSha256Base64(secretHash, rawBody));
1284
+ const validV3Hash = typeof legacyHash === "string" && timingSafeEqualString(legacyHash, secretHash);
1285
+ if (!validV4Signature && !validV3Hash) throw new APIError("UNAUTHORIZED", { message: "Invalid signature" });
1196
1286
  let webhookJson;
1197
1287
  try {
1198
1288
  webhookJson = JSON.parse(rawBody);
@@ -1200,14 +1290,20 @@ const flutterwaveWebhook = (options, path) => createAuthEndpoint(path, {
1200
1290
  ctx.context.logger.warn("Ignoring non-JSON signed Flutterwave webhook");
1201
1291
  return ctx.json({ received: true });
1202
1292
  }
1203
- const parsedEvent = webhookPayloadSchema.safeParse(webhookJson);
1204
- if (!parsedEvent.success) {
1293
+ const parsedV3 = v3WebhookPayloadSchema.safeParse(webhookJson);
1294
+ const parsedV4 = parsedV3.success ? void 0 : v4WebhookPayloadSchema.safeParse(webhookJson);
1295
+ if (!parsedV3.success && !parsedV4?.success) {
1205
1296
  ctx.context.logger.warn("Ignoring malformed signed Flutterwave webhook");
1206
1297
  return ctx.json({ received: true });
1207
1298
  }
1208
- const event = parsedEvent.data;
1209
- const data = event.data;
1210
- const eventId = createHash("sha256").update(data.id === void 0 ? rawBody : `${event.event}:${String(data.id)}:${String(data.status ?? "")}`).digest("hex");
1299
+ let event;
1300
+ if (parsedV3.success) event = parsedV3.data;
1301
+ else if (parsedV4?.success) event = parsedV4.data;
1302
+ else throw new APIError("BAD_REQUEST", { message: "Malformed webhook" });
1303
+ 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");
1304
+ const eventType = "type" in event ? event.type : event.event;
1305
+ const txRef = "type" in event ? event.data.reference : event.data.tx_ref;
1306
+ const providerTransactionId = "type" in event ? void 0 : event.data.id;
1211
1307
  const store = createBillingStore(ctx);
1212
1308
  const existingEvent = await store.findWebhookEvent(eventId);
1213
1309
  if (existingEvent?.status === "processed") return ctx.json({ received: true });
@@ -1216,9 +1312,9 @@ const flutterwaveWebhook = (options, path) => createAuthEndpoint(path, {
1216
1312
  if (existingEvent === null) try {
1217
1313
  await store.createWebhookEvent({
1218
1314
  eventId,
1219
- eventType: event.event,
1220
- transactionId: data.id === void 0 ? void 0 : Number(data.id),
1221
- txRef: data.tx_ref,
1315
+ eventType,
1316
+ transactionId: providerTransactionId !== void 0 && Number.isSafeInteger(Number(providerTransactionId)) ? Number(providerTransactionId) : void 0,
1317
+ txRef,
1222
1318
  payload: rawBody,
1223
1319
  status: "processing",
1224
1320
  createdAt: now,
@@ -1236,12 +1332,14 @@ const flutterwaveWebhook = (options, path) => createAuthEndpoint(path, {
1236
1332
  if (!await store.claimWebhookEvent(existingEvent, now)) throw busy();
1237
1333
  }
1238
1334
  try {
1239
- if (data.tx_ref && data.id !== void 0) {
1240
- const local = await store.findTransactionByTxRef(data.tx_ref);
1335
+ const v3TransactionRef = "event" in event ? event.data.tx_ref : void 0;
1336
+ if (v3TransactionRef && "event" in event && event.data.id !== void 0) {
1337
+ const data = event.data;
1338
+ const local = await store.findTransactionByTxRef(v3TransactionRef);
1241
1339
  if (!local) throw new Error("The webhook payment has not been recorded locally yet");
1242
1340
  const verified = await adapter$1(options).verifyTransaction({ transactionId: Number(data.id) });
1243
1341
  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);
1342
+ await recordVerifiedPayment(ctx, options, local, verified, event);
1245
1343
  Object.assign(data, {
1246
1344
  id: verified.id,
1247
1345
  tx_ref: verified.tx_ref,
@@ -1250,6 +1348,38 @@ const flutterwaveWebhook = (options, path) => createAuthEndpoint(path, {
1250
1348
  status: verified.status
1251
1349
  });
1252
1350
  }
1351
+ if ("event" in event && event.event === "subscription.cancelled") {
1352
+ const customerEmail = event.data.customer?.email;
1353
+ const planId = Number(event.data.plan?.id);
1354
+ if (customerEmail && Number.isInteger(planId) && planId > 0) {
1355
+ const matches = await store.findSubscriptionsByBillingEmailAndPlanId(customerEmail, planId);
1356
+ if (matches.length === 1) {
1357
+ const match = matches[0];
1358
+ const now = /* @__PURE__ */ new Date();
1359
+ const scheduledEnd = match.cancelAt ?? match.periodEnd;
1360
+ const keepPaidAccess = match.status !== "canceled" && match.endedAt == null && match.cancelAtPeriodEnd && scheduledEnd != null && new Date(scheduledEnd).getTime() > now.getTime();
1361
+ const subscription = await store.updateSubscription(match.id, {
1362
+ status: keepPaidAccess ? match.status : "canceled",
1363
+ cancelAtPeriodEnd: keepPaidAccess,
1364
+ cancelAt: keepPaidAccess ? scheduledEnd : null,
1365
+ canceledAt: match.canceledAt ?? now,
1366
+ endedAt: keepPaidAccess ? null : match.endedAt ?? now,
1367
+ updatedAt: now
1368
+ }) ?? match;
1369
+ const callbackData = {
1370
+ event,
1371
+ subscription
1372
+ };
1373
+ await options.subscription?.onSubscriptionCancel?.(callbackData, ctx);
1374
+ const plan = await getPlans(options.subscription).then((plans) => plans.find((candidate) => candidate.name.toLowerCase() === match.plan.toLowerCase()));
1375
+ if (plan) await options.subscription?.onSubscriptionUpdate?.({
1376
+ ...callbackData,
1377
+ subscription,
1378
+ plan
1379
+ }, ctx);
1380
+ } else if (matches.length > 1) ctx.context.logger.warn("Flutterwave cancellation event matched multiple local subscriptions; manual reconciliation is required");
1381
+ }
1382
+ }
1253
1383
  await options.onEvent?.(event);
1254
1384
  await store.updateWebhookEvent(eventId, {
1255
1385
  status: "processed",
@@ -1674,6 +1804,182 @@ const getSchema = (options) => {
1674
1804
  return mergeSchema(baseSchema, optionSchema);
1675
1805
  };
1676
1806
  //#endregion
1807
+ //#region src/flutterwave-v4.ts
1808
+ const DEFAULT_IDENTITY_URL = "https://idp.flutterwave.com/realms/flutterwave/protocol/openid-connect/token";
1809
+ const DEFAULT_API_URL = "https://f4bexperience.flutterwave.com";
1810
+ /**
1811
+ * Create a server-only Flutterwave v4 transport. It accepts encrypted card
1812
+ * fields only; raw PAN/CVV handling belongs in a PCI-compliant client flow.
1813
+ */
1814
+ function createFlutterwaveV4Adapter(options) {
1815
+ if (!options.clientId || !options.clientSecret) throw new Error("Flutterwave v4 clientId and clientSecret are required");
1816
+ const fetchImpl = options.fetch ?? globalThis.fetch;
1817
+ if (typeof fetchImpl !== "function") throw new Error("Fetch is not available");
1818
+ const baseUrl = (options.apiBaseUrl ?? DEFAULT_API_URL).replace(/\/+$/, "");
1819
+ const identityUrl = options.identityUrl ?? DEFAULT_IDENTITY_URL;
1820
+ const now = options.now ?? Date.now;
1821
+ let token;
1822
+ let refreshAt = 0;
1823
+ let tokenRequest;
1824
+ const getToken = async () => {
1825
+ if (token !== void 0 && token.length > 0 && now() < refreshAt) return token;
1826
+ if (tokenRequest) return tokenRequest;
1827
+ tokenRequest = (async () => {
1828
+ const response = await fetchImpl(identityUrl, {
1829
+ method: "POST",
1830
+ headers: { "content-type": "application/x-www-form-urlencoded" },
1831
+ body: new URLSearchParams({
1832
+ client_id: options.clientId,
1833
+ client_secret: options.clientSecret,
1834
+ grant_type: "client_credentials"
1835
+ })
1836
+ });
1837
+ const raw = await parseJson(response, "authenticate");
1838
+ const accessToken = field(raw, "access_token");
1839
+ const expiresIn = Number(field(raw, "expires_in"));
1840
+ if (!response.ok || typeof accessToken !== "string" || !Number.isFinite(expiresIn)) throw v4Error("authenticate", response.status, raw);
1841
+ token = accessToken;
1842
+ refreshAt = now() + Math.max(0, expiresIn - 60) * 1e3;
1843
+ return accessToken;
1844
+ })().finally(() => {
1845
+ tokenRequest = void 0;
1846
+ });
1847
+ return tokenRequest;
1848
+ };
1849
+ const request = async (operation, path, input = {}, allowAuthRetry = true) => {
1850
+ const method = input.method ?? "GET";
1851
+ if (method !== "GET") validateIdempotencyKey(input.idempotencyKey);
1852
+ if (input.traceId !== void 0) validateTraceId(input.traceId);
1853
+ const headers = new Headers({
1854
+ accept: "application/json",
1855
+ authorization: `Bearer ${await getToken()}`,
1856
+ "content-type": "application/json"
1857
+ });
1858
+ if (input.idempotencyKey !== void 0) headers.set("x-idempotency-key", input.idempotencyKey);
1859
+ if (input.traceId !== void 0) headers.set("x-trace-id", input.traceId);
1860
+ const response = await fetchImpl(`${baseUrl}${path}`, {
1861
+ method,
1862
+ headers,
1863
+ ...input.body === void 0 ? {} : { body: JSON.stringify(input.body) }
1864
+ });
1865
+ const raw = await parseJson(response, operation);
1866
+ if (response.status === 401 && allowAuthRetry) {
1867
+ token = void 0;
1868
+ refreshAt = 0;
1869
+ return request(operation, path, input, false);
1870
+ }
1871
+ if (!response.ok) throw v4Error(operation, response.status, raw);
1872
+ const status = field(raw, "status");
1873
+ const data = field(raw, "data");
1874
+ if (status !== "success" || !isObject(data) || typeof data.id !== "string") throw new Error(`Flutterwave v4 ${operation} returned an invalid response`);
1875
+ return data;
1876
+ };
1877
+ const withTraceId = (value) => value ?? randomBytes(16).toString("hex");
1878
+ return {
1879
+ createCustomer: async (input) => {
1880
+ const { idempotencyKey, traceId, ...body } = input;
1881
+ if (!input.email.includes("@")) throw new Error("A valid customer email is required");
1882
+ return request("create customer", "/customers", {
1883
+ method: "POST",
1884
+ body,
1885
+ idempotencyKey,
1886
+ traceId: withTraceId(traceId)
1887
+ });
1888
+ },
1889
+ createCardPaymentMethod: async (input) => {
1890
+ const { idempotencyKey, traceId, customerId, ...card } = input;
1891
+ if (Object.values(card).some((value) => typeof value !== "string" || value.length === 0)) throw new Error("Flutterwave v4 requires encrypted card fields and a nonce");
1892
+ return request("create payment method", "/payment-methods", {
1893
+ method: "POST",
1894
+ body: {
1895
+ type: "card",
1896
+ card,
1897
+ ...customerId !== void 0 ? { customer_id: customerId } : {}
1898
+ },
1899
+ idempotencyKey,
1900
+ traceId: withTraceId(traceId)
1901
+ });
1902
+ },
1903
+ createCharge: async (input) => {
1904
+ validateReference(input.reference);
1905
+ if (!Number.isFinite(input.amount) || input.amount < .01) throw new Error("Flutterwave v4 charge amount must be at least 0.01");
1906
+ const { idempotencyKey, traceId, customerId, paymentMethodId, redirectUrl, ...charge } = input;
1907
+ return request("create charge", "/charges", {
1908
+ method: "POST",
1909
+ body: {
1910
+ ...charge,
1911
+ customer_id: customerId,
1912
+ payment_method_id: paymentMethodId,
1913
+ ...redirectUrl !== void 0 ? { redirect_url: redirectUrl } : {}
1914
+ },
1915
+ idempotencyKey,
1916
+ traceId: withTraceId(traceId)
1917
+ });
1918
+ },
1919
+ retrieveCharge: async (chargeId) => {
1920
+ if (!chargeId) throw new Error("Flutterwave v4 charge id is required");
1921
+ return request("retrieve charge", `/charges/${encodeURIComponent(chargeId)}`);
1922
+ },
1923
+ updateChargeAuthorization: async (input) => {
1924
+ if (!input.chargeId) throw new Error("Flutterwave v4 charge id is required");
1925
+ return request("update charge authorization", `/charges/${encodeURIComponent(input.chargeId)}`, {
1926
+ method: "PUT",
1927
+ body: { authorization: input.authorization },
1928
+ idempotencyKey: input.idempotencyKey,
1929
+ traceId: withTraceId(input.traceId)
1930
+ });
1931
+ },
1932
+ createRefund: async (input) => {
1933
+ if (!input.chargeId || !isV4RefundReason(input.reason)) throw new Error("Flutterwave v4 refund chargeId and reason are required");
1934
+ if (!Number.isFinite(input.amount) || input.amount < .01) throw new Error("Flutterwave v4 refund amount must be at least 0.01");
1935
+ const { idempotencyKey, traceId, chargeId, ...refund } = input;
1936
+ return request("create refund", "/refunds", {
1937
+ method: "POST",
1938
+ body: {
1939
+ charge_id: chargeId,
1940
+ ...refund
1941
+ },
1942
+ idempotencyKey,
1943
+ traceId: withTraceId(traceId)
1944
+ });
1945
+ }
1946
+ };
1947
+ }
1948
+ async function parseJson(response, operation) {
1949
+ try {
1950
+ return await response.json();
1951
+ } catch (cause) {
1952
+ throw new Error(`Flutterwave v4 ${operation} returned non-JSON HTTP ${response.status}`, { cause });
1953
+ }
1954
+ }
1955
+ function isObject(value) {
1956
+ return typeof value === "object" && value !== null;
1957
+ }
1958
+ function field(value, key) {
1959
+ return isObject(value) ? value[key] : void 0;
1960
+ }
1961
+ function validateIdempotencyKey(value) {
1962
+ 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");
1963
+ }
1964
+ function validateTraceId(value) {
1965
+ if (!/^[\x21-\x7E]{12,255}$/.test(value)) throw new Error("Flutterwave v4 trace ids must be 12-255 printable ASCII characters");
1966
+ }
1967
+ function validateReference(value) {
1968
+ if (!/^[A-Za-z0-9-]{6,42}$/.test(value)) throw new Error("Flutterwave v4 references must be 6-42 letters, digits, or hyphens");
1969
+ }
1970
+ function isV4RefundReason(value) {
1971
+ return value === "duplicate" || value === "fraudulent" || value === "requested_by_customer" || value === "expired_uncaptured_charge";
1972
+ }
1973
+ function v4Error(operation, status, raw) {
1974
+ const message = field(field(raw, "error"), "message") ?? field(raw, "message");
1975
+ const error = new Error(typeof message === "string" ? message : `Flutterwave v4 ${operation} failed with HTTP ${status}`);
1976
+ Object.assign(error, {
1977
+ status,
1978
+ retryable: status === 408 || status === 429 || status >= 500
1979
+ });
1980
+ return error;
1981
+ }
1982
+ //#endregion
1677
1983
  //#region src/limits.ts
1678
1984
  const checkSeatLimit = async (ctx, organizationId, seatsToAdd = 1) => {
1679
1985
  const store = createBillingStore(ctx);
@@ -1864,7 +2170,7 @@ async function refundFlutterwaveTransaction(ctx, options, input) {
1864
2170
  const store = createBillingStore(ctx);
1865
2171
  const transaction = await store.findTransactionById(input.transactionId);
1866
2172
  if (!transaction) throw new APIError("NOT_FOUND", { message: "Transaction not found" });
1867
- const result = await adapter(options).refundTransaction(input.transactionId, input.amount);
2173
+ const result = await adapter(options).refundTransaction(input.transactionId, input.amount, input.reason);
1868
2174
  const now = /* @__PURE__ */ new Date();
1869
2175
  return store.createRefund({
1870
2176
  refundId: result.id,
@@ -1991,6 +2297,6 @@ const flutterwave = (options) => {
1991
2297
  };
1992
2298
  };
1993
2299
  //#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 };
2300
+ 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
2301
 
1996
2302
  //# sourceMappingURL=index.mjs.map