better-auth-flutterwave 0.4.0 → 0.4.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +22 -0
- package/dist/client.d.mts +1 -1
- package/dist/client.mjs +1 -1
- package/dist/{index-CD0cRLo_.d.mts → index-YHYXcci3.d.mts} +4 -2
- package/dist/{index-CD0cRLo_.d.mts.map → index-YHYXcci3.d.mts.map} +1 -1
- package/dist/index.d.mts +1 -1
- package/dist/index.mjs +306 -107
- package/dist/index.mjs.map +1 -1
- package/dist/{version-CceayuXv.mjs → version-WC4th7kC.mjs} +2 -2
- package/dist/{version-CceayuXv.mjs.map → version-WC4th7kC.mjs.map} +1 -1
- package/package.json +2 -2
- 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/README.md
CHANGED
|
@@ -217,6 +217,13 @@ idempotent: a crash after external work but before recording completion can caus
|
|
|
217
217
|
execute a callback again. A provider cancellation notification preserves access through a future
|
|
218
218
|
scheduled paid-period end; immediate cancellations end access when processed.
|
|
219
219
|
|
|
220
|
+
Verified-payment lifecycle hooks share a durable fulfillment record across browser verification,
|
|
221
|
+
webhooks, and reconciliation. The record retains initial subscription intent before activation and
|
|
222
|
+
checkpoints each successful hook. A failed initial hook is retried even after the subscription becomes
|
|
223
|
+
active; successful earlier hooks are skipped. Fulfillment records use the existing event table and
|
|
224
|
+
five-minute leases, so concurrent requests retry instead of dispatching the same hooks simultaneously.
|
|
225
|
+
Handlers must still be idempotent if external work succeeds before its checkpoint is stored.
|
|
226
|
+
|
|
220
227
|
Do not parse and reserialize the request before signature verification. Do not use the API
|
|
221
228
|
`secretKey` as the webhook secret hash.
|
|
222
229
|
|
|
@@ -258,6 +265,21 @@ jobs:
|
|
|
258
265
|
another batch may be needed. Scheduling requires a known paid `periodEnd`; legacy records must
|
|
259
266
|
be reconciled first or canceled immediately.
|
|
260
267
|
|
|
268
|
+
Renewal jobs should supply a stable `renewalId` and reuse it for every retry of the same billing
|
|
269
|
+
intent. Without one, the plugin reserves the current paid-period end (or the initial period).
|
|
270
|
+
New renewal intents are rejected before a future paid period ends. A pending transaction and dispatch intent are saved
|
|
271
|
+
before charging. Once dispatch starts, retries verify that same reference and never initiate another
|
|
272
|
+
charge, even if the provider response or subsequent verification was lost. A provider rejection or
|
|
273
|
+
an unverifiable reference requires reconciliation or operator investigation; it does not authorize a
|
|
274
|
+
new charge. Hosted-checkout retries return the saved URL. No provider-side idempotency guarantee is
|
|
275
|
+
assumed. Completed `renewalId` retries return the original verified payment.
|
|
276
|
+
|
|
277
|
+
For v3 refunds, `completed` means initiated and awaiting disbursement. Reconciliation also polls
|
|
278
|
+
`processing`, `pending-momo`, and `pending`, and accepts only successful fetch responses with the
|
|
279
|
+
expected refund ID. Method-specific terminal statuses such as `completed-mpgs` and
|
|
280
|
+
`completed-bank-transfer` indicate successful disbursement. See the
|
|
281
|
+
[Flutterwave v3 refund lifecycle](https://developer.flutterwave.com/docs/refunds).
|
|
282
|
+
|
|
261
283
|
Cancellation and restoration accept either the local subscription `id` or a numeric Flutterwave
|
|
262
284
|
`subscriptionId`. A scheduled local cancellation can be withdrawn while its paid period is still
|
|
263
285
|
active. A local subscription that has already ended requires a new checkout. Renewal calculates
|
package/dist/client.d.mts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { B as FlutterwaveInitializeResult, C as FlutterwaveMetadata, H as FlutterwavePlan, J as FlutterwaveTransaction, U as FlutterwaveProduct, Y as FlutterwaveTransactionResponse, it as Subscription, j as parseFlutterwaveMetadata, t as flutterwave } from "./index-
|
|
1
|
+
import { B as FlutterwaveInitializeResult, C as FlutterwaveMetadata, H as FlutterwavePlan, J as FlutterwaveTransaction, U as FlutterwaveProduct, Y as FlutterwaveTransactionResponse, it as Subscription, j as parseFlutterwaveMetadata, t as flutterwave } from "./index-YHYXcci3.mjs";
|
|
2
2
|
import { BetterFetch, BetterFetchOption, BetterFetchResponse } from "@better-fetch/fetch";
|
|
3
3
|
import { BetterAuthClientPlugin } from "better-auth/client";
|
|
4
4
|
//#region src/client.d.ts
|
package/dist/client.mjs
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { l as parseFlutterwaveMetadata, t as PACKAGE_VERSION } from "./version-
|
|
1
|
+
import { l as parseFlutterwaveMetadata, t as PACKAGE_VERSION } from "./version-WC4th7kC.mjs";
|
|
2
2
|
//#region src/client.ts
|
|
3
3
|
const flutterwaveClient = (_options) => ({
|
|
4
4
|
id: "flutterwave-client",
|
|
@@ -456,6 +456,8 @@ interface ChargeRecurringSubscriptionInput {
|
|
|
456
456
|
subscriptionId: string;
|
|
457
457
|
amount?: number;
|
|
458
458
|
redirectUrl?: string;
|
|
459
|
+
/** Stable job/payment intent identifier; reuse it for every retry of the same renewal. */
|
|
460
|
+
renewalId?: string;
|
|
459
461
|
}
|
|
460
462
|
interface ChargeRecurringSubscriptionResult {
|
|
461
463
|
status: "success" | "pending" | "failed";
|
|
@@ -815,7 +817,7 @@ declare const flutterwaveWebhook: <P extends string>(options: AnyFlutterwaveOpti
|
|
|
815
817
|
}>;
|
|
816
818
|
//#endregion
|
|
817
819
|
//#region src/version.d.ts
|
|
818
|
-
declare const PACKAGE_VERSION = "0.4.
|
|
820
|
+
declare const PACKAGE_VERSION = "0.4.2";
|
|
819
821
|
//#endregion
|
|
820
822
|
//#region src/metadata.d.ts
|
|
821
823
|
type FlutterwaveMetadata = Record<string, unknown>;
|
|
@@ -1060,4 +1062,4 @@ type FlutterwavePluginInstance<O extends AnyFlutterwaveOptions> = Omit<BetterAut
|
|
|
1060
1062
|
declare const flutterwave: <TFlutterwaveClient extends FlutterwaveClientLike = FlutterwaveClientLike, O extends FlutterwaveOptions<TFlutterwaveClient> = FlutterwaveOptions<TFlutterwaveClient>>(options: O) => FlutterwavePluginInstance<O>;
|
|
1061
1063
|
//#endregion
|
|
1062
1064
|
export { FlutterwaveWebhookPayload as $, hasFlutterwaveMetadata as A, FlutterwaveInitializeResult as B, FlutterwaveMetadata as C, getMetadataBoolean as D, createRenewalMetadata as E, ChargeRecurringSubscriptionResult as F, FlutterwaveSubaccountSplit as G, FlutterwavePlan as H, FlutterwaveCheckoutChannel as I, FlutterwaveTransaction as J, FlutterwaveSubscription as K, FlutterwaveClientLike as L, stringifyFlutterwaveMetadata as M, AnyFlutterwaveOptions as N, getMetadataNumber as O, ChargeRecurringSubscriptionInput as P, FlutterwaveWebhookEventRecord as Q, FlutterwaveCurrency as R, createFlutterwaveV4Adapter as S, createProrationMetadata as T, FlutterwaveProduct as U, FlutterwaveOptions as V, FlutterwaveRefund as W, FlutterwaveV4WebhookEvent as X, FlutterwaveTransactionResponse as Y, FlutterwaveWebhookEvent as Z, FlutterwaveV4CustomerInput as _, processScheduledFlutterwaveCancellations as a, SubscriptionOptions as at, FlutterwaveV4RefundReason as b, checkSeatLimit as c, FlutterwaveAdapterError as ct, decryptPaymentToken as d, createFlutterwaveAdapter as dt, InputFlutterwaveProduct as et, encryptPaymentToken as f, FlutterwaveTokenChargeInput as ft, FlutterwaveV4ChargeInput as g, FlutterwaveV4ChargeAuthorization as h, chargeSubscriptionRenewal as i, Subscription as it, parseFlutterwaveMetadata as j, getMetadataString as k, checkTeamLimit as l, FlutterwaveAdapterOptions as lt, FlutterwaveV4CardPaymentMethodInput as m, reconcileFlutterwaveRefunds as n, Organization as nt, refundFlutterwaveTransaction as o, User as ot, FlutterwaveV4Adapter as p, FlutterwaveSyncResult as q, reconcileFlutterwaveTransaction as r, Session as rt, syncFlutterwavePlans as s, FlutterwaveAdapter as st, flutterwave as t, Member as tt, getOrganizationEntitlements as u, FlutterwaveSdkClient as ut, FlutterwaveV4Options as v, createCheckoutMetadata as w, FlutterwaveV4Resource as x, FlutterwaveV4RefundInput as y, FlutterwaveCustomer as z };
|
|
1063
|
-
//# sourceMappingURL=index-
|
|
1065
|
+
//# sourceMappingURL=index-YHYXcci3.d.mts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index-
|
|
1
|
+
{"version":3,"file":"index-YHYXcci3.d.mts","names":["_$__types_ts0.FlutterwaveTransaction","_$__types_ts0.Subscription","_$__types_ts0.FlutterwavePlan","_$__types_ts0.FlutterwaveRefund"],"sources":["../src/schema.ts","../src/flutterwave-contracts.ts","../src/flutterwave-sdk.ts","../src/types.d.ts","../src/routes.ts","../src/version.ts","../src/metadata.ts","../src/flutterwave-v4.ts","../src/token-crypto.ts","../src/limits.ts","../src/billing-store.ts","../src/operations.ts","../src/reconciliation.ts","../src/index.ts"],"mappings":";;;;;KAIK,kBAAkB,0BAA0B,4BAA4B,OAC3E;EAEE,QAAQ,OAAO,WAAW;EAC1B;EACA;;KAIC,qBAAqB;KAuBrB,sBAAsB;KA4BtB,iBAAiB;KAcjB,cAAc;KAed,sBAAsB;KAatB,gBAAgB;KAgBT,0BAA0B,qBACpC,sBACA,iBACA,cACA,sBACA;cA0IW,YAAa,SAAS,uBAAqB;;;cCzP3C,6BAA2B,EAAA;;;;;;;;;;;;;;;;;;;;;;;;;;GAoCxB,EAAA,KAAA;cAEH,oBAAkB,EAAA;;GAIf,EAAA,KAAA;cAEH,mBAAiB,EAAA;;;;;;;;;;;;;;;;;;GA2Bd,EAAA,KAAA;cAEH,mBAAiB,EAAA;;;;;;;;;GAcd,EAAA,KAAA;cAEH,oBAAkB,EAAA;;;;;;;;;;;GAgBf,EAAA,KAAA;cAEH,wBAAsB,EAAA;;;;;;;;GAUnB,EAAA,KAAA;c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ACA;EACA;EACA;EACA,YAAY;EACZ,YAAY;;UAEC;EACb;EACA;EACA;EACA;;UAEa;EACb;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;IACI;IACA,gBAAgB,cAAc,iBAAiB;IAC/C,cAAc,cAAc,iBAAiB;IAC7C,kBAAkB,cAAc,iBAAiB;;EAErD,SAAS;EACT;EACA;EACA,YAAY;EACZ,YAAY;;UAEC;EACb;EACA,MAAM;IACF;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;MACI;;IAEJ;MACI;MACA;;;;UAIK;EACb;EACA;EACA;EACA;EACA,MAAM;IACF;IACA;IACA;IACA;IACA;IACA;MACI;MACA;;;;KAIA,4BAA4B;UACvB;EACb;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA,WAAW;EACX;EACA;EACA,OAAO;;UAEM;EACb;EACA;EACA;EACA;;UAEa;EACb;EACA,OAAO,2BAA2B,QAAQ;EAC1C;EACA;EACA;EACA,yBAAyB;EACzB,sBAAsB;IAClB,MAAM;IACN,SAAS;IACT;IACA;KACD,KAAK,2BAA2B;EACnC,0BAA0B;IACtB,OAAO;IACP,cAAc;IACd,MAAM;KACP,KAAK,2BAA2B;EACnC,yBAAyB;IACrB,OAAO;IACP,cAAc;IACd,MAAM;KACP,KAAK,2BAA2B;EACnC,wBAAwB;IACpB,OAAO;IACP,cAAc;IACd,MAAM;KACP,KAAK,2BAA2B;EACnC,wBAAwB;IACpB,OAAO;IACP,cAAc;KACf,KAAK,2BAA2B;;UAEtB,mBAAmB,2BAA2B,wBAAwB;EACnF;EACA;EACA;EACA,oBAAoB;EACpB,eAAe,WAAW;EAC1B;EACA;EACA;IACI;;EAEJ,eAAe;EACf;IACI;IACA;;EAEJ;IACI,WAAW,8BAA8B,QAAQ;;EAErD;IACI;IACA,eAAe;;EAEnB,WAAW,OAAO,0BAA0B,8BAA8B;EAC1E,SAAS,kBAAkB;;UAEd;EACb;EACA;EACA;EACA;EACA;EACA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AC3C,sBAAsB,kBAAkB;EACxC,sBAAsB,kBAAkB;EACxC,oBAAoB,kBAAkB;;KAGnC,0BAA0B,UAAU,yBAAyB,KAChE;EAGA;EACA,gBAAgB;EAChB,WAAW;EACX,QAAQ,kBAAkB;EAC1B,SAAS,QAAQ;EACjB,qBAAqB;EACrB,OAAO,KAAK;IAAkB,SAAS;;;cAG5B,cACX,2BAA2B,wBAAwB,uBACnD,UAAU,mBAAmB,sBAAsB,mBAAmB,qBAEtE,SAAS,MACR,0BAA0B"}
|
package/dist/index.d.mts
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import { $ as FlutterwaveWebhookPayload, A as hasFlutterwaveMetadata, B as FlutterwaveInitializeResult, C as FlutterwaveMetadata, D as getMetadataBoolean, E as createRenewalMetadata, F as ChargeRecurringSubscriptionResult, G as FlutterwaveSubaccountSplit, H as FlutterwavePlan, I as FlutterwaveCheckoutChannel, J as FlutterwaveTransaction, K as FlutterwaveSubscription, L as FlutterwaveClientLike, M as stringifyFlutterwaveMetadata, N as AnyFlutterwaveOptions, O as getMetadataNumber, P as ChargeRecurringSubscriptionInput, Q as FlutterwaveWebhookEventRecord, R as FlutterwaveCurrency, S as createFlutterwaveV4Adapter, T as createProrationMetadata, U as FlutterwaveProduct, V as FlutterwaveOptions, W as FlutterwaveRefund, X as FlutterwaveV4WebhookEvent, Y as FlutterwaveTransactionResponse, Z as FlutterwaveWebhookEvent, _ as FlutterwaveV4CustomerInput, a as processScheduledFlutterwaveCancellations, at as SubscriptionOptions, b as FlutterwaveV4RefundReason, c as checkSeatLimit, ct as FlutterwaveAdapterError, d as decryptPaymentToken, dt as createFlutterwaveAdapter, et as InputFlutterwaveProduct, f as encryptPaymentToken, ft as FlutterwaveTokenChargeInput, g as FlutterwaveV4ChargeInput, h as FlutterwaveV4ChargeAuthorization, i as chargeSubscriptionRenewal, it as Subscription, j as parseFlutterwaveMetadata, k as getMetadataString, l as checkTeamLimit, lt as FlutterwaveAdapterOptions, m as FlutterwaveV4CardPaymentMethodInput, n as reconcileFlutterwaveRefunds, nt as Organization, o as refundFlutterwaveTransaction, ot as User, p as FlutterwaveV4Adapter, q as FlutterwaveSyncResult, r as reconcileFlutterwaveTransaction, rt as Session, s as syncFlutterwavePlans, st as FlutterwaveAdapter, t as flutterwave, tt as Member, u as getOrganizationEntitlements, ut as FlutterwaveSdkClient, v as FlutterwaveV4Options, w as createCheckoutMetadata, x as FlutterwaveV4Resource, y as FlutterwaveV4RefundInput, z as FlutterwaveCustomer } from "./index-
|
|
1
|
+
import { $ as FlutterwaveWebhookPayload, A as hasFlutterwaveMetadata, B as FlutterwaveInitializeResult, C as FlutterwaveMetadata, D as getMetadataBoolean, E as createRenewalMetadata, F as ChargeRecurringSubscriptionResult, G as FlutterwaveSubaccountSplit, H as FlutterwavePlan, I as FlutterwaveCheckoutChannel, J as FlutterwaveTransaction, K as FlutterwaveSubscription, L as FlutterwaveClientLike, M as stringifyFlutterwaveMetadata, N as AnyFlutterwaveOptions, O as getMetadataNumber, P as ChargeRecurringSubscriptionInput, Q as FlutterwaveWebhookEventRecord, R as FlutterwaveCurrency, S as createFlutterwaveV4Adapter, T as createProrationMetadata, U as FlutterwaveProduct, V as FlutterwaveOptions, W as FlutterwaveRefund, X as FlutterwaveV4WebhookEvent, Y as FlutterwaveTransactionResponse, Z as FlutterwaveWebhookEvent, _ as FlutterwaveV4CustomerInput, a as processScheduledFlutterwaveCancellations, at as SubscriptionOptions, b as FlutterwaveV4RefundReason, c as checkSeatLimit, ct as FlutterwaveAdapterError, d as decryptPaymentToken, dt as createFlutterwaveAdapter, et as InputFlutterwaveProduct, f as encryptPaymentToken, ft as FlutterwaveTokenChargeInput, g as FlutterwaveV4ChargeInput, h as FlutterwaveV4ChargeAuthorization, i as chargeSubscriptionRenewal, it as Subscription, j as parseFlutterwaveMetadata, k as getMetadataString, l as checkTeamLimit, lt as FlutterwaveAdapterOptions, m as FlutterwaveV4CardPaymentMethodInput, n as reconcileFlutterwaveRefunds, nt as Organization, o as refundFlutterwaveTransaction, ot as User, p as FlutterwaveV4Adapter, q as FlutterwaveSyncResult, r as reconcileFlutterwaveTransaction, rt as Session, s as syncFlutterwavePlans, st as FlutterwaveAdapter, t as flutterwave, tt as Member, u as getOrganizationEntitlements, ut as FlutterwaveSdkClient, v as FlutterwaveV4Options, w as createCheckoutMetadata, x as FlutterwaveV4Resource, y as FlutterwaveV4RefundInput, z as FlutterwaveCustomer } from "./index-YHYXcci3.mjs";
|
|
2
2
|
export { type AnyFlutterwaveOptions, type ChargeRecurringSubscriptionInput, type ChargeRecurringSubscriptionResult, type FlutterwaveAdapter, FlutterwaveAdapterError, type FlutterwaveAdapterOptions, type FlutterwaveCheckoutChannel, type FlutterwaveClientLike, type FlutterwaveCurrency, type FlutterwaveCustomer, type FlutterwaveInitializeResult, type FlutterwaveMetadata, type FlutterwaveOptions, type FlutterwavePlan, type FlutterwaveProduct, type FlutterwaveRefund, type FlutterwaveSdkClient, type FlutterwaveSubaccountSplit, type FlutterwaveSubscription, type FlutterwaveSyncResult, type FlutterwaveTokenChargeInput, type FlutterwaveTransaction, type FlutterwaveTransactionResponse, type FlutterwaveV4Adapter, type FlutterwaveV4CardPaymentMethodInput, type FlutterwaveV4ChargeAuthorization, type FlutterwaveV4ChargeInput, type FlutterwaveV4CustomerInput, type FlutterwaveV4Options, type FlutterwaveV4RefundInput, type FlutterwaveV4RefundReason, type FlutterwaveV4Resource, type FlutterwaveV4WebhookEvent, type FlutterwaveWebhookEvent, type FlutterwaveWebhookEventRecord, type FlutterwaveWebhookPayload, type InputFlutterwaveProduct, type Member, type Organization, type Session, type Subscription, type SubscriptionOptions, type User, chargeSubscriptionRenewal, checkSeatLimit, checkTeamLimit, createCheckoutMetadata, createFlutterwaveAdapter, createFlutterwaveV4Adapter, createProrationMetadata, createRenewalMetadata, decryptPaymentToken, encryptPaymentToken, flutterwave, getMetadataBoolean, getMetadataNumber, getMetadataString, getOrganizationEntitlements, hasFlutterwaveMetadata, parseFlutterwaveMetadata, processScheduledFlutterwaveCancellations, reconcileFlutterwaveRefunds, reconcileFlutterwaveTransaction, refundFlutterwaveTransaction, stringifyFlutterwaveMetadata, syncFlutterwavePlans };
|
package/dist/index.mjs
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { a as getMetadataBoolean, c as hasFlutterwaveMetadata, i as createRenewalMetadata, l as parseFlutterwaveMetadata, n as createCheckoutMetadata, o as getMetadataNumber, r as createProrationMetadata, s as getMetadataString, t as PACKAGE_VERSION, u as stringifyFlutterwaveMetadata } from "./version-
|
|
1
|
+
import { a as getMetadataBoolean, c as hasFlutterwaveMetadata, i as createRenewalMetadata, l as parseFlutterwaveMetadata, n as createCheckoutMetadata, o as getMetadataNumber, r as createProrationMetadata, s as getMetadataString, t as PACKAGE_VERSION, u as stringifyFlutterwaveMetadata } from "./version-WC4th7kC.mjs";
|
|
2
2
|
import { HIDE_METADATA, defineErrorCodes } from "better-auth";
|
|
3
3
|
import { createHash, randomBytes, timingSafeEqual } from "node:crypto";
|
|
4
4
|
import { APIError, createAuthEndpoint, getSessionFromCtx, originCheckMiddleware, sessionMiddleware } from "better-auth/api";
|
|
@@ -290,6 +290,26 @@ function createBillingStoreFromAdapter(adapter) {
|
|
|
290
290
|
}
|
|
291
291
|
}) === 1;
|
|
292
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
|
+
},
|
|
293
313
|
createRefund: (data) => adapter.create({
|
|
294
314
|
model: "flutterwaveRefund",
|
|
295
315
|
data
|
|
@@ -298,10 +318,19 @@ function createBillingStoreFromAdapter(adapter) {
|
|
|
298
318
|
field: "refundId",
|
|
299
319
|
value: refundId
|
|
300
320
|
}]),
|
|
301
|
-
listPendingRefunds: () => findMany(
|
|
302
|
-
|
|
303
|
-
|
|
304
|
-
|
|
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
|
+
}),
|
|
305
334
|
updateRefund: (id, update) => adapter.update({
|
|
306
335
|
model: "flutterwaveRefund",
|
|
307
336
|
update,
|
|
@@ -582,6 +611,55 @@ function createFlutterwaveAdapter(options) {
|
|
|
582
611
|
};
|
|
583
612
|
}
|
|
584
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
|
|
585
663
|
//#region src/token-crypto.ts
|
|
586
664
|
const encoder = new TextEncoder();
|
|
587
665
|
const decoder = new TextDecoder();
|
|
@@ -696,6 +774,14 @@ function getNextPeriodEnd(startDate, interval) {
|
|
|
696
774
|
}
|
|
697
775
|
//#endregion
|
|
698
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
|
+
});
|
|
699
785
|
function paymentMatches(expected, verified) {
|
|
700
786
|
return verified.tx_ref === expected.txRef && verified.amount === expected.amount && verified.currency === expected.currency;
|
|
701
787
|
}
|
|
@@ -755,43 +841,79 @@ async function recordVerifiedPayment(ctx, options, expected, verified, webhookEv
|
|
|
755
841
|
reconciledAt: now,
|
|
756
842
|
updatedAt: now
|
|
757
843
|
};
|
|
758
|
-
if (
|
|
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
|
+
}
|
|
759
867
|
const plan = (await getPlans(options.subscription)).find((candidate) => candidate.name.toLowerCase() === subscription.plan.toLowerCase());
|
|
760
868
|
if (plan) {
|
|
761
|
-
const
|
|
762
|
-
event:
|
|
763
|
-
|
|
764
|
-
|
|
765
|
-
|
|
766
|
-
|
|
767
|
-
|
|
768
|
-
|
|
769
|
-
|
|
770
|
-
|
|
771
|
-
|
|
772
|
-
|
|
773
|
-
|
|
774
|
-
|
|
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
|
|
775
886
|
};
|
|
776
|
-
|
|
777
|
-
|
|
778
|
-
|
|
779
|
-
subscription:
|
|
780
|
-
|
|
781
|
-
|
|
782
|
-
|
|
783
|
-
|
|
784
|
-
|
|
785
|
-
|
|
786
|
-
|
|
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) });
|
|
787
907
|
}
|
|
788
|
-
await options.subscription?.onSubscriptionUpdate?.({
|
|
789
|
-
event: callbackEvent,
|
|
790
|
-
subscription: currentSubscription,
|
|
791
|
-
plan
|
|
792
|
-
}, ctx);
|
|
793
908
|
}
|
|
794
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;
|
|
795
917
|
}
|
|
796
918
|
}
|
|
797
919
|
}
|
|
@@ -2048,86 +2170,167 @@ async function chargeSubscriptionRenewal(ctx, options, input) {
|
|
|
2048
2170
|
return (typeof configured === "function" ? await configured() : configured ?? []).find((candidate) => candidate.name === subscription.plan) ?? null;
|
|
2049
2171
|
})();
|
|
2050
2172
|
const amount = input.amount ?? (plan ? calculatePlanAmount(plan, subscription.seats) : void 0);
|
|
2051
|
-
if (!amount || !plan?.currency || !subscription.billingEmail) throw new APIError("BAD_REQUEST", { message: "Subscription billing details are incomplete" });
|
|
2052
|
-
|
|
2053
|
-
const
|
|
2054
|
-
|
|
2055
|
-
|
|
2056
|
-
|
|
2057
|
-
|
|
2058
|
-
|
|
2059
|
-
|
|
2060
|
-
|
|
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,
|
|
2061
2195
|
amount,
|
|
2062
2196
|
currency: plan.currency,
|
|
2063
|
-
|
|
2064
|
-
|
|
2065
|
-
|
|
2066
|
-
|
|
2067
|
-
|
|
2068
|
-
await store
|
|
2069
|
-
|
|
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,
|
|
2070
2210
|
referenceId: subscription.referenceId,
|
|
2071
2211
|
userId: subscription.userId,
|
|
2072
2212
|
amount,
|
|
2073
2213
|
currency: plan.currency,
|
|
2074
2214
|
status: "pending",
|
|
2075
2215
|
plan: subscription.plan,
|
|
2076
|
-
metadata
|
|
2077
|
-
|
|
2078
|
-
|
|
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()
|
|
2079
2225
|
});
|
|
2080
|
-
|
|
2081
|
-
txRef
|
|
2082
|
-
|
|
2083
|
-
|
|
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()
|
|
2084
2303
|
});
|
|
2085
|
-
return {
|
|
2304
|
+
if (verified.status === "pending" && progress.checkoutUrl !== void 0) return {
|
|
2086
2305
|
status: "pending",
|
|
2087
2306
|
data: {
|
|
2088
2307
|
kind: "checkout",
|
|
2089
|
-
url:
|
|
2090
|
-
txRef,
|
|
2308
|
+
url: progress.checkoutUrl,
|
|
2309
|
+
txRef: progress.txRef,
|
|
2091
2310
|
redirect: true
|
|
2092
2311
|
}
|
|
2093
2312
|
};
|
|
2313
|
+
return renewalResult(verified);
|
|
2314
|
+
} catch (error) {
|
|
2315
|
+
if (operation.status !== "processed") await failOperation(store, operation);
|
|
2316
|
+
throw error;
|
|
2094
2317
|
}
|
|
2095
|
-
|
|
2096
|
-
|
|
2097
|
-
|
|
2098
|
-
|
|
2099
|
-
|
|
2100
|
-
|
|
2101
|
-
|
|
2102
|
-
|
|
2103
|
-
|
|
2104
|
-
|
|
2105
|
-
|
|
2106
|
-
|
|
2107
|
-
|
|
2108
|
-
|
|
2109
|
-
flwRef: verified.flw_ref,
|
|
2110
|
-
referenceId: subscription.referenceId,
|
|
2111
|
-
userId: subscription.userId,
|
|
2112
|
-
amount,
|
|
2113
|
-
chargedAmount: verified.charged_amount,
|
|
2114
|
-
currency: plan.currency,
|
|
2115
|
-
status: "pending",
|
|
2116
|
-
plan: subscription.plan,
|
|
2117
|
-
paymentType: verified.payment_type,
|
|
2118
|
-
metadata,
|
|
2119
|
-
createdAt: now,
|
|
2120
|
-
updatedAt: now
|
|
2121
|
-
});
|
|
2122
|
-
await store.updateSubscription(subscription.id, {
|
|
2123
|
-
txRef,
|
|
2124
|
-
status: "past_due",
|
|
2125
|
-
reconciledAt: now,
|
|
2126
|
-
updatedAt: now
|
|
2127
|
-
});
|
|
2128
|
-
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) {
|
|
2129
2332
|
return {
|
|
2130
|
-
status: verified.status === "successful" ? "success" : "failed",
|
|
2333
|
+
status: verified.status === "successful" ? "success" : verified.status === "pending" ? "pending" : "failed",
|
|
2131
2334
|
data: {
|
|
2132
2335
|
id: verified.id,
|
|
2133
2336
|
txRef: verified.tx_ref,
|
|
@@ -2162,10 +2365,6 @@ async function processScheduledFlutterwaveCancellations(ctx, options, input = {}
|
|
|
2162
2365
|
hasMore: due.length === limit
|
|
2163
2366
|
};
|
|
2164
2367
|
}
|
|
2165
|
-
function parseMetadata(value) {
|
|
2166
|
-
if (!value) return void 0;
|
|
2167
|
-
return JSON.parse(value);
|
|
2168
|
-
}
|
|
2169
2368
|
async function refundFlutterwaveTransaction(ctx, options, input) {
|
|
2170
2369
|
const store = createBillingStore(ctx);
|
|
2171
2370
|
const transaction = await store.findTransactionById(input.transactionId);
|
|
@@ -2233,11 +2432,11 @@ async function reconcileFlutterwaveTransaction(ctx, options, input) {
|
|
|
2233
2432
|
};
|
|
2234
2433
|
}
|
|
2235
2434
|
const refundEnvelopeSchema = z.object({
|
|
2236
|
-
status: z.
|
|
2435
|
+
status: z.literal("success"),
|
|
2237
2436
|
data: z.object({
|
|
2238
|
-
id: z.coerce.number().
|
|
2239
|
-
status: z.string(),
|
|
2240
|
-
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()
|
|
2241
2440
|
})
|
|
2242
2441
|
});
|
|
2243
2442
|
async function reconcileFlutterwaveRefunds(ctx, options) {
|
|
@@ -2251,7 +2450,7 @@ async function reconcileFlutterwaveRefunds(ctx, options) {
|
|
|
2251
2450
|
const response = await fetchImpl(`${baseUrl}/v3/refunds/${refund.refundId}`, { headers: { authorization: `Bearer ${options.secretKey}` } });
|
|
2252
2451
|
if (!response.ok) continue;
|
|
2253
2452
|
const parsed = refundEnvelopeSchema.safeParse(await response.json());
|
|
2254
|
-
if (!parsed.success) continue;
|
|
2453
|
+
if (!parsed.success || parsed.data.data.id !== refund.refundId) continue;
|
|
2255
2454
|
await store.updateRefund(refund.id, {
|
|
2256
2455
|
status: parsed.data.data.status,
|
|
2257
2456
|
amount: parsed.data.data.amount_refunded ?? refund.amount,
|