better-auth-flutterwave 0.0.0 → 0.1.5
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/LICENSE +21 -0
- package/README.md +307 -0
- package/dist/client.d.mts +96 -0
- package/dist/client.d.mts.map +1 -0
- package/dist/client.mjs +75 -0
- package/dist/client.mjs.map +1 -0
- package/dist/index-Dcwl_2fw.d.mts +927 -0
- package/dist/index-Dcwl_2fw.d.mts.map +1 -0
- package/dist/index.d.mts +2 -0
- package/dist/index.mjs +1752 -0
- package/dist/index.mjs.map +1 -0
- package/dist/version-CzIALUmS.mjs +73 -0
- package/dist/version-CzIALUmS.mjs.map +1 -0
- package/package.json +119 -8
- package/skills/better-auth-flutterwave-setup/SKILL.md +23 -0
- package/skills/better-auth-flutterwave-setup/agents/openai.yaml +6 -0
- package/skills/flutterwave-billing-flows/SKILL.md +21 -0
- package/skills/flutterwave-billing-flows/agents/openai.yaml +6 -0
- package/skills/flutterwave-catalog-limits/SKILL.md +17 -0
- package/skills/flutterwave-catalog-limits/agents/openai.yaml +6 -0
- package/skills/flutterwave-client-api/SKILL.md +20 -0
- package/skills/flutterwave-client-api/agents/openai.yaml +6 -0
- package/skills/flutterwave-local-subscriptions/SKILL.md +18 -0
- package/skills/flutterwave-local-subscriptions/agents/openai.yaml +6 -0
- package/skills/flutterwave-organization-billing/SKILL.md +18 -0
- package/skills/flutterwave-organization-billing/agents/openai.yaml +6 -0
- package/skills/flutterwave-schema-migrations/SKILL.md +19 -0
- package/skills/flutterwave-schema-migrations/agents/openai.yaml +6 -0
- package/skills/flutterwave-tanstack-start/SKILL.md +20 -0
- package/skills/flutterwave-tanstack-start/agents/openai.yaml +6 -0
- package/skills/flutterwave-testing-fixtures/SKILL.md +20 -0
- package/skills/flutterwave-testing-fixtures/agents/openai.yaml +6 -0
- package/skills/flutterwave-webhooks-events/SKILL.md +17 -0
- package/skills/flutterwave-webhooks-events/agents/openai.yaml +6 -0
- package/index.js +0 -1
package/dist/index.mjs
ADDED
|
@@ -0,0 +1,1752 @@
|
|
|
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-CzIALUmS.mjs";
|
|
2
|
+
import { createRequire } from "node:module";
|
|
3
|
+
import { HIDE_METADATA, defineErrorCodes } from "better-auth";
|
|
4
|
+
import { createHash, timingSafeEqual } from "node:crypto";
|
|
5
|
+
import { APIError, createAuthEndpoint, getSessionFromCtx, originCheck, sessionMiddleware } from "better-auth/api";
|
|
6
|
+
import * as z from "zod";
|
|
7
|
+
import { Buffer } from "node:buffer";
|
|
8
|
+
import { mergeSchema } from "better-auth/db";
|
|
9
|
+
//#region src/billing-store.ts
|
|
10
|
+
function sortSubscriptionsForCurrent(subscriptions) {
|
|
11
|
+
const statusRank = /* @__PURE__ */ new Map([
|
|
12
|
+
["active", 0],
|
|
13
|
+
["trialing", 1],
|
|
14
|
+
["incomplete", 2],
|
|
15
|
+
["past_due", 3],
|
|
16
|
+
["canceled", 4]
|
|
17
|
+
]);
|
|
18
|
+
return [...subscriptions].sort((a, b) => {
|
|
19
|
+
const statusDifference = (statusRank.get(a.status) ?? 99) - (statusRank.get(b.status) ?? 99);
|
|
20
|
+
return statusDifference !== 0 ? statusDifference : new Date(b.updatedAt).getTime() - new Date(a.updatedAt).getTime();
|
|
21
|
+
});
|
|
22
|
+
}
|
|
23
|
+
function createBillingStore(ctx) {
|
|
24
|
+
return createBillingStoreFromAdapter(ctx.context.adapter);
|
|
25
|
+
}
|
|
26
|
+
function createBillingStoreFromAdapter(adapter) {
|
|
27
|
+
const findOne = async (model, where) => await adapter.findOne({
|
|
28
|
+
model,
|
|
29
|
+
where
|
|
30
|
+
}) ?? null;
|
|
31
|
+
const findMany = async (model, where) => await adapter.findMany({
|
|
32
|
+
model,
|
|
33
|
+
...where ? { where } : {}
|
|
34
|
+
}) ?? [];
|
|
35
|
+
return {
|
|
36
|
+
findSubscriptionById: (id) => findOne("flutterwaveSubscription", [{
|
|
37
|
+
field: "id",
|
|
38
|
+
value: id
|
|
39
|
+
}]),
|
|
40
|
+
findSubscriptionByProviderId: (subscriptionId) => findOne("flutterwaveSubscription", [{
|
|
41
|
+
field: "subscriptionId",
|
|
42
|
+
value: subscriptionId
|
|
43
|
+
}]),
|
|
44
|
+
findSubscriptionsByReference: (referenceId) => findMany("flutterwaveSubscription", [{
|
|
45
|
+
field: "referenceId",
|
|
46
|
+
value: referenceId
|
|
47
|
+
}]),
|
|
48
|
+
async findCurrentSubscription(referenceId, groupId) {
|
|
49
|
+
const candidates = await this.findSubscriptionsByReference(referenceId);
|
|
50
|
+
return sortSubscriptionsForCurrent(groupId === void 0 ? candidates : candidates.filter(({ groupId: candidateGroup }) => groupId === null ? candidateGroup === void 0 || candidateGroup === null || candidateGroup === "" : candidateGroup === groupId))[0] ?? null;
|
|
51
|
+
},
|
|
52
|
+
async retireCompetingSubscriptions(referenceId, groupId, exceptId) {
|
|
53
|
+
const candidates = await this.findSubscriptionsByReference(referenceId);
|
|
54
|
+
const now = /* @__PURE__ */ new Date();
|
|
55
|
+
for (const candidate of candidates) {
|
|
56
|
+
const sameGroup = groupId === null ? candidate.groupId === void 0 || candidate.groupId === null || candidate.groupId === "" : candidate.groupId === groupId;
|
|
57
|
+
if (candidate.id !== exceptId && sameGroup && (candidate.status === "active" || candidate.status === "trialing")) await this.updateSubscription(candidate.id, {
|
|
58
|
+
status: "canceled",
|
|
59
|
+
cancelAtPeriodEnd: false,
|
|
60
|
+
canceledAt: now,
|
|
61
|
+
endedAt: now,
|
|
62
|
+
updatedAt: now
|
|
63
|
+
});
|
|
64
|
+
}
|
|
65
|
+
},
|
|
66
|
+
findSubscriptionsByTxRef: (txRef) => findMany("flutterwaveSubscription", [{
|
|
67
|
+
field: "txRef",
|
|
68
|
+
value: txRef
|
|
69
|
+
}]),
|
|
70
|
+
createSubscription: (data) => adapter.create({
|
|
71
|
+
model: "flutterwaveSubscription",
|
|
72
|
+
data
|
|
73
|
+
}),
|
|
74
|
+
updateSubscription: (id, update) => adapter.update({
|
|
75
|
+
model: "flutterwaveSubscription",
|
|
76
|
+
update,
|
|
77
|
+
where: [{
|
|
78
|
+
field: "id",
|
|
79
|
+
value: id
|
|
80
|
+
}]
|
|
81
|
+
}),
|
|
82
|
+
updateSubscriptionByProviderId: (subscriptionId, update) => adapter.update({
|
|
83
|
+
model: "flutterwaveSubscription",
|
|
84
|
+
update,
|
|
85
|
+
where: [{
|
|
86
|
+
field: "subscriptionId",
|
|
87
|
+
value: subscriptionId
|
|
88
|
+
}]
|
|
89
|
+
}),
|
|
90
|
+
createTransaction: (data) => adapter.create({
|
|
91
|
+
model: "flutterwaveTransaction",
|
|
92
|
+
data
|
|
93
|
+
}),
|
|
94
|
+
findTransactionByTxRef: (txRef) => findOne("flutterwaveTransaction", [{
|
|
95
|
+
field: "txRef",
|
|
96
|
+
value: txRef
|
|
97
|
+
}]),
|
|
98
|
+
findTransactionById: (transactionId) => findOne("flutterwaveTransaction", [{
|
|
99
|
+
field: "transactionId",
|
|
100
|
+
value: transactionId
|
|
101
|
+
}]),
|
|
102
|
+
updateTransactionByTxRef: (txRef, update) => adapter.update({
|
|
103
|
+
model: "flutterwaveTransaction",
|
|
104
|
+
update,
|
|
105
|
+
where: [{
|
|
106
|
+
field: "txRef",
|
|
107
|
+
value: txRef
|
|
108
|
+
}]
|
|
109
|
+
}),
|
|
110
|
+
async listTransactions(referenceId) {
|
|
111
|
+
return (await findMany("flutterwaveTransaction", [{
|
|
112
|
+
field: "referenceId",
|
|
113
|
+
value: referenceId
|
|
114
|
+
}])).sort((a, b) => new Date(b.createdAt).getTime() - new Date(a.createdAt).getTime());
|
|
115
|
+
},
|
|
116
|
+
async listProducts() {
|
|
117
|
+
return (await findMany("flutterwaveProduct")).sort((a, b) => a.name.localeCompare(b.name));
|
|
118
|
+
},
|
|
119
|
+
findProductByName: (name) => findOne("flutterwaveProduct", [{
|
|
120
|
+
field: "name",
|
|
121
|
+
value: name
|
|
122
|
+
}]),
|
|
123
|
+
findProductBySlug: (slug) => findOne("flutterwaveProduct", [{
|
|
124
|
+
field: "slug",
|
|
125
|
+
value: slug
|
|
126
|
+
}]),
|
|
127
|
+
async updateProduct(id, update) {
|
|
128
|
+
await adapter.update({
|
|
129
|
+
model: "flutterwaveProduct",
|
|
130
|
+
update,
|
|
131
|
+
where: [{
|
|
132
|
+
field: "id",
|
|
133
|
+
value: id
|
|
134
|
+
}]
|
|
135
|
+
});
|
|
136
|
+
},
|
|
137
|
+
async upsertProductBySlug(slug, data) {
|
|
138
|
+
const existing = await this.findProductBySlug(slug);
|
|
139
|
+
if (existing?.id !== void 0) {
|
|
140
|
+
const { createdAt: _createdAt, ...update } = data;
|
|
141
|
+
await this.updateProduct(existing.id, update);
|
|
142
|
+
} else await adapter.create({
|
|
143
|
+
model: "flutterwaveProduct",
|
|
144
|
+
data: {
|
|
145
|
+
...data,
|
|
146
|
+
slug
|
|
147
|
+
}
|
|
148
|
+
});
|
|
149
|
+
},
|
|
150
|
+
listPlans: () => findMany("flutterwavePlan"),
|
|
151
|
+
findPlanByName: (name) => findOne("flutterwavePlan", [{
|
|
152
|
+
field: "name",
|
|
153
|
+
value: name
|
|
154
|
+
}]),
|
|
155
|
+
findPlanByPaymentPlanId: (paymentPlanId) => findOne("flutterwavePlan", [{
|
|
156
|
+
field: "paymentPlanId",
|
|
157
|
+
value: paymentPlanId
|
|
158
|
+
}]),
|
|
159
|
+
async upsertPlanByPaymentPlanId(paymentPlanId, data) {
|
|
160
|
+
const existing = await this.findPlanByPaymentPlanId(paymentPlanId);
|
|
161
|
+
if (existing?.id !== void 0) {
|
|
162
|
+
const { createdAt: _createdAt, ...update } = data;
|
|
163
|
+
await adapter.update({
|
|
164
|
+
model: "flutterwavePlan",
|
|
165
|
+
update,
|
|
166
|
+
where: [{
|
|
167
|
+
field: "id",
|
|
168
|
+
value: existing.id
|
|
169
|
+
}]
|
|
170
|
+
});
|
|
171
|
+
} else await adapter.create({
|
|
172
|
+
model: "flutterwavePlan",
|
|
173
|
+
data: {
|
|
174
|
+
...data,
|
|
175
|
+
paymentPlanId
|
|
176
|
+
}
|
|
177
|
+
});
|
|
178
|
+
},
|
|
179
|
+
createWebhookEvent: (data) => adapter.create({
|
|
180
|
+
model: "flutterwaveWebhookEvent",
|
|
181
|
+
data
|
|
182
|
+
}),
|
|
183
|
+
findWebhookEvent: (eventId) => findOne("flutterwaveWebhookEvent", [{
|
|
184
|
+
field: "eventId",
|
|
185
|
+
value: eventId
|
|
186
|
+
}]),
|
|
187
|
+
updateWebhookEvent: (eventId, update) => adapter.update({
|
|
188
|
+
model: "flutterwaveWebhookEvent",
|
|
189
|
+
update,
|
|
190
|
+
where: [{
|
|
191
|
+
field: "eventId",
|
|
192
|
+
value: eventId
|
|
193
|
+
}]
|
|
194
|
+
}),
|
|
195
|
+
createRefund: (data) => adapter.create({
|
|
196
|
+
model: "flutterwaveRefund",
|
|
197
|
+
data
|
|
198
|
+
}),
|
|
199
|
+
findRefundByProviderId: (refundId) => findOne("flutterwaveRefund", [{
|
|
200
|
+
field: "refundId",
|
|
201
|
+
value: refundId
|
|
202
|
+
}]),
|
|
203
|
+
listPendingRefunds: () => findMany("flutterwaveRefund", [{
|
|
204
|
+
field: "status",
|
|
205
|
+
value: "pending"
|
|
206
|
+
}]),
|
|
207
|
+
updateRefund: (id, update) => adapter.update({
|
|
208
|
+
model: "flutterwaveRefund",
|
|
209
|
+
update,
|
|
210
|
+
where: [{
|
|
211
|
+
field: "id",
|
|
212
|
+
value: id
|
|
213
|
+
}]
|
|
214
|
+
}),
|
|
215
|
+
findUser: (id) => findOne("user", [{
|
|
216
|
+
field: "id",
|
|
217
|
+
value: id
|
|
218
|
+
}]),
|
|
219
|
+
findOrganization: (id) => findOne("organization", [{
|
|
220
|
+
field: "id",
|
|
221
|
+
value: id
|
|
222
|
+
}]),
|
|
223
|
+
findOrganizationOwner: (organizationId) => findOne("member", [{
|
|
224
|
+
field: "organizationId",
|
|
225
|
+
value: organizationId
|
|
226
|
+
}, {
|
|
227
|
+
field: "role",
|
|
228
|
+
value: "owner"
|
|
229
|
+
}]),
|
|
230
|
+
listMembers: (organizationId) => findMany("member", [{
|
|
231
|
+
field: "organizationId",
|
|
232
|
+
value: organizationId
|
|
233
|
+
}]),
|
|
234
|
+
listTeams: (organizationId) => findMany("team", [{
|
|
235
|
+
field: "organizationId",
|
|
236
|
+
value: organizationId
|
|
237
|
+
}])
|
|
238
|
+
};
|
|
239
|
+
}
|
|
240
|
+
//#endregion
|
|
241
|
+
//#region src/flutterwave-contracts.ts
|
|
242
|
+
const currencySchema = z.string().regex(/^[A-Z]{3}$/, "Currency must be a three-letter ISO code");
|
|
243
|
+
const positiveAmountSchema = z.coerce.number().positive();
|
|
244
|
+
const optionalDateSchema = z.string().nullable().optional();
|
|
245
|
+
const flutterwaveEnvelopeSchema = (data) => z.object({
|
|
246
|
+
status: z.string(),
|
|
247
|
+
message: z.string().optional(),
|
|
248
|
+
data
|
|
249
|
+
}).passthrough();
|
|
250
|
+
const standardCheckoutInputSchema = z.object({
|
|
251
|
+
tx_ref: z.string().min(1).max(100),
|
|
252
|
+
amount: positiveAmountSchema,
|
|
253
|
+
currency: currencySchema,
|
|
254
|
+
redirect_url: z.url(),
|
|
255
|
+
customer: z.object({
|
|
256
|
+
email: z.email(),
|
|
257
|
+
name: z.string().min(1).optional(),
|
|
258
|
+
phonenumber: z.string().min(1).optional()
|
|
259
|
+
}).passthrough(),
|
|
260
|
+
payment_options: z.string().min(1).optional(),
|
|
261
|
+
payment_plan: z.number().int().positive().optional(),
|
|
262
|
+
subaccounts: z.array(z.object({
|
|
263
|
+
id: z.string().min(1),
|
|
264
|
+
transaction_charge_type: z.enum(["flat", "percentage"]).optional(),
|
|
265
|
+
transaction_charge: z.number().nonnegative().optional()
|
|
266
|
+
}).passthrough()).min(1).optional(),
|
|
267
|
+
customizations: z.object({
|
|
268
|
+
title: z.string().optional(),
|
|
269
|
+
description: z.string().optional(),
|
|
270
|
+
logo: z.url().optional()
|
|
271
|
+
}).optional(),
|
|
272
|
+
meta: z.record(z.string(), z.unknown()).optional()
|
|
273
|
+
}).passthrough();
|
|
274
|
+
const checkoutDataSchema = z.object({ link: z.url() }).passthrough();
|
|
275
|
+
const transactionSchema = z.object({
|
|
276
|
+
id: z.coerce.number().int().positive(),
|
|
277
|
+
tx_ref: z.string().min(1),
|
|
278
|
+
flw_ref: z.string().nullable().optional(),
|
|
279
|
+
amount: positiveAmountSchema,
|
|
280
|
+
charged_amount: z.coerce.number().nonnegative().optional(),
|
|
281
|
+
currency: currencySchema,
|
|
282
|
+
status: z.string().min(1),
|
|
283
|
+
payment_type: z.string().nullable().optional(),
|
|
284
|
+
created_at: optionalDateSchema,
|
|
285
|
+
customer: z.object({
|
|
286
|
+
id: z.coerce.number().int().optional(),
|
|
287
|
+
email: z.email(),
|
|
288
|
+
name: z.string().nullable().optional()
|
|
289
|
+
}).passthrough().optional(),
|
|
290
|
+
card: z.object({ token: z.string().min(1).optional() }).passthrough().nullable().optional()
|
|
291
|
+
}).passthrough();
|
|
292
|
+
const paymentPlanSchema = z.object({
|
|
293
|
+
id: z.coerce.number().int().positive(),
|
|
294
|
+
name: z.string().min(1),
|
|
295
|
+
amount: positiveAmountSchema.nullable().optional().transform((value) => value ?? void 0),
|
|
296
|
+
interval: z.string().min(1),
|
|
297
|
+
currency: currencySchema,
|
|
298
|
+
status: z.string().optional(),
|
|
299
|
+
duration: z.coerce.number().int().nonnegative().optional(),
|
|
300
|
+
created_at: optionalDateSchema
|
|
301
|
+
}).passthrough();
|
|
302
|
+
const subscriptionSchema = z.object({
|
|
303
|
+
id: z.coerce.number().int().positive(),
|
|
304
|
+
amount: positiveAmountSchema,
|
|
305
|
+
customer: z.object({
|
|
306
|
+
email: z.email().optional(),
|
|
307
|
+
customer_email: z.email().optional()
|
|
308
|
+
}).passthrough().optional(),
|
|
309
|
+
plan: z.coerce.number().int().positive().optional(),
|
|
310
|
+
status: z.string().min(1),
|
|
311
|
+
currency: currencySchema.optional(),
|
|
312
|
+
created_at: optionalDateSchema
|
|
313
|
+
}).passthrough();
|
|
314
|
+
const tokenChargeInputSchema = z.object({
|
|
315
|
+
token: z.string().min(1),
|
|
316
|
+
currency: currencySchema,
|
|
317
|
+
country: z.string().length(2).toUpperCase().optional(),
|
|
318
|
+
amount: positiveAmountSchema,
|
|
319
|
+
email: z.email(),
|
|
320
|
+
tx_ref: z.string().min(1).max(100),
|
|
321
|
+
narration: z.string().optional()
|
|
322
|
+
}).passthrough();
|
|
323
|
+
const refundSchema = z.object({
|
|
324
|
+
id: z.coerce.number().int().positive().optional(),
|
|
325
|
+
transaction_id: z.coerce.number().int().positive().optional(),
|
|
326
|
+
amount_refunded: z.coerce.number().nonnegative().optional(),
|
|
327
|
+
amount: z.coerce.number().nonnegative().optional(),
|
|
328
|
+
status: z.string().min(1),
|
|
329
|
+
created_at: optionalDateSchema
|
|
330
|
+
}).passthrough();
|
|
331
|
+
//#endregion
|
|
332
|
+
//#region src/flutterwave-sdk.ts
|
|
333
|
+
var FlutterwaveAdapterError = class extends Error {
|
|
334
|
+
operation;
|
|
335
|
+
status;
|
|
336
|
+
cause;
|
|
337
|
+
constructor(operation, message, options) {
|
|
338
|
+
super(message);
|
|
339
|
+
this.name = "FlutterwaveAdapterError";
|
|
340
|
+
this.operation = operation;
|
|
341
|
+
this.status = options?.status;
|
|
342
|
+
this.cause = options?.cause;
|
|
343
|
+
}
|
|
344
|
+
};
|
|
345
|
+
function createSdkClient(publicKey, secretKey) {
|
|
346
|
+
return new (createRequire(import.meta.url)("flutterwave-node-v3"))(publicKey, secretKey);
|
|
347
|
+
}
|
|
348
|
+
function messageFromUnknown(value) {
|
|
349
|
+
if (typeof value === "string") return value;
|
|
350
|
+
if (typeof value !== "object" || value === null) return void 0;
|
|
351
|
+
const message = Reflect.get(value, "message");
|
|
352
|
+
return typeof message === "string" ? message : void 0;
|
|
353
|
+
}
|
|
354
|
+
function parseEnvelope(operation, raw, dataSchema) {
|
|
355
|
+
const envelope = flutterwaveEnvelopeSchema(dataSchema).safeParse(raw);
|
|
356
|
+
if (!envelope.success) throw new FlutterwaveAdapterError(operation, "Flutterwave returned an invalid response", { cause: envelope.error });
|
|
357
|
+
if (envelope.data.status.toLowerCase() !== "success") throw new FlutterwaveAdapterError(operation, envelope.data.message ?? "Flutterwave rejected the request");
|
|
358
|
+
return envelope.data.data;
|
|
359
|
+
}
|
|
360
|
+
async function sdkCall(operation, action, schema) {
|
|
361
|
+
try {
|
|
362
|
+
return parseEnvelope(operation, await action(), schema);
|
|
363
|
+
} catch (error) {
|
|
364
|
+
if (error instanceof FlutterwaveAdapterError) throw error;
|
|
365
|
+
throw new FlutterwaveAdapterError(operation, messageFromUnknown(error) ?? `Flutterwave ${operation} failed`, { cause: error });
|
|
366
|
+
}
|
|
367
|
+
}
|
|
368
|
+
const positiveIdSchema = z.number().int().positive();
|
|
369
|
+
const optionalPositiveAmountSchema = z.number().positive().optional();
|
|
370
|
+
/**
|
|
371
|
+
* Creates the provider boundary used by the plugin.
|
|
372
|
+
*
|
|
373
|
+
* `flutterwave-node-v3` performs always-on telemetry and writes telemetry state in
|
|
374
|
+
* the operating-system temporary directory. Inject `flutterwaveClient` in tests,
|
|
375
|
+
* serverless environments that prohibit those writes, or when custom transport is
|
|
376
|
+
* required. This adapter intentionally uses only the SDK's Promise API.
|
|
377
|
+
*/
|
|
378
|
+
function createFlutterwaveAdapter(options) {
|
|
379
|
+
if (!options.publicKey) throw new FlutterwaveAdapterError("configuration", "publicKey is required");
|
|
380
|
+
if (!options.secretKey) throw new FlutterwaveAdapterError("configuration", "secretKey is required");
|
|
381
|
+
const client = options.flutterwaveClient ?? createSdkClient(options.publicKey, options.secretKey);
|
|
382
|
+
const fetchImpl = options.fetch ?? globalThis.fetch;
|
|
383
|
+
const apiBaseUrl = (options.apiBaseUrl ?? "https://api.flutterwave.com").replace(/\/+$/, "");
|
|
384
|
+
return {
|
|
385
|
+
async initializePayment(input) {
|
|
386
|
+
const body = standardCheckoutInputSchema.parse(input);
|
|
387
|
+
if (typeof fetchImpl !== "function") throw new FlutterwaveAdapterError("initialize payment", "Fetch is not available");
|
|
388
|
+
let response;
|
|
389
|
+
try {
|
|
390
|
+
response = await fetchImpl(`${apiBaseUrl}/v3/payments`, {
|
|
391
|
+
method: "POST",
|
|
392
|
+
headers: {
|
|
393
|
+
authorization: `Bearer ${options.secretKey}`,
|
|
394
|
+
"content-type": "application/json"
|
|
395
|
+
},
|
|
396
|
+
body: JSON.stringify(body)
|
|
397
|
+
});
|
|
398
|
+
} catch (error) {
|
|
399
|
+
throw new FlutterwaveAdapterError("initialize payment", messageFromUnknown(error) ?? "Flutterwave checkout request failed", { cause: error });
|
|
400
|
+
}
|
|
401
|
+
let raw;
|
|
402
|
+
try {
|
|
403
|
+
raw = await response.json();
|
|
404
|
+
} catch (error) {
|
|
405
|
+
throw new FlutterwaveAdapterError("initialize payment", "Flutterwave returned a non-JSON response", {
|
|
406
|
+
status: response.status,
|
|
407
|
+
cause: error
|
|
408
|
+
});
|
|
409
|
+
}
|
|
410
|
+
if (!response.ok) throw new FlutterwaveAdapterError("initialize payment", messageFromUnknown(raw) ?? `Flutterwave checkout failed with HTTP ${response.status}`, { status: response.status });
|
|
411
|
+
return parseEnvelope("initialize payment", raw, checkoutDataSchema);
|
|
412
|
+
},
|
|
413
|
+
async verifyTransaction(input) {
|
|
414
|
+
if (input.transactionId === void 0 === (input.txRef === void 0)) throw new FlutterwaveAdapterError("verify transaction", "Provide exactly one of transactionId or txRef");
|
|
415
|
+
return input.transactionId !== void 0 ? sdkCall("verify transaction", () => client.Transaction.verify({ id: positiveIdSchema.parse(input.transactionId) }), transactionSchema) : sdkCall("verify transaction", () => client.Transaction.verify_by_tx({ tx_ref: z.string().min(1).parse(input.txRef) }), transactionSchema);
|
|
416
|
+
},
|
|
417
|
+
listPaymentPlans: () => sdkCall("list payment plans", () => client.PaymentPlan.get_all({}), z.array(paymentPlanSchema)),
|
|
418
|
+
listSubscriptions: (input = {}) => {
|
|
419
|
+
const query = {
|
|
420
|
+
email: input.email,
|
|
421
|
+
status: input.status,
|
|
422
|
+
...input.plan === void 0 ? {} : { plan: String(input.plan) },
|
|
423
|
+
...input.transactionId === void 0 ? {} : { transaction_id: String(input.transactionId) },
|
|
424
|
+
...input.page === void 0 ? {} : { page: String(input.page) }
|
|
425
|
+
};
|
|
426
|
+
return sdkCall("list subscriptions", () => client.Subscription.fetch_all(query), z.array(subscriptionSchema));
|
|
427
|
+
},
|
|
428
|
+
cancelSubscription: (subscriptionId) => sdkCall("cancel subscription", () => client.Subscription.cancel({ id: positiveIdSchema.parse(subscriptionId) }), subscriptionSchema),
|
|
429
|
+
activateSubscription: (subscriptionId) => sdkCall("activate subscription", () => client.Subscription.activate({ id: positiveIdSchema.parse(subscriptionId) }), subscriptionSchema),
|
|
430
|
+
chargeToken: (input) => {
|
|
431
|
+
const body = tokenChargeInputSchema.parse(input);
|
|
432
|
+
return sdkCall("charge token", () => client.Tokenized.charge(body), transactionSchema);
|
|
433
|
+
},
|
|
434
|
+
refundTransaction: (transactionId, amount) => sdkCall("refund transaction", () => client.Transaction.refund({
|
|
435
|
+
id: positiveIdSchema.parse(transactionId),
|
|
436
|
+
amount: optionalPositiveAmountSchema.parse(amount)
|
|
437
|
+
}), refundSchema)
|
|
438
|
+
};
|
|
439
|
+
}
|
|
440
|
+
//#endregion
|
|
441
|
+
//#region src/reference-access.ts
|
|
442
|
+
const DEFAULT_BILLING_ORG_ROLES = ["owner", "admin"];
|
|
443
|
+
function normalizeBillingRoles(roles) {
|
|
444
|
+
return new Set(roles.map((value) => value.trim()).filter((value) => value !== ""));
|
|
445
|
+
}
|
|
446
|
+
function getBillingRoles(options) {
|
|
447
|
+
return options.organization?.billingRoles ?? DEFAULT_BILLING_ORG_ROLES;
|
|
448
|
+
}
|
|
449
|
+
function hasBillingRole(role, billingRoles = DEFAULT_BILLING_ORG_ROLES) {
|
|
450
|
+
const allowedRoles = normalizeBillingRoles(billingRoles);
|
|
451
|
+
if (Array.isArray(role)) return role.some((value) => hasBillingRole(value, billingRoles));
|
|
452
|
+
if (typeof role !== "string") return false;
|
|
453
|
+
return role.split(",").map((value) => value.trim()).some((value) => allowedRoles.has(value));
|
|
454
|
+
}
|
|
455
|
+
function resolveBillingReferenceId(input) {
|
|
456
|
+
const body = input.body ?? {};
|
|
457
|
+
const query = input.query ?? {};
|
|
458
|
+
const requestQueryReferenceId = typeof input.requestUrl === "string" ? new URL(input.requestUrl).searchParams.get("referenceId") ?? void 0 : void 0;
|
|
459
|
+
return body.referenceId ?? query.referenceId ?? requestQueryReferenceId ?? input.fallbackUserId;
|
|
460
|
+
}
|
|
461
|
+
async function authorizeBillingReference(ctx, options, data) {
|
|
462
|
+
if (data.referenceId === data.user.id) return;
|
|
463
|
+
if (options.subscription?.enabled === true && typeof options.subscription.authorizeReference === "function") {
|
|
464
|
+
if (await options.subscription.authorizeReference({
|
|
465
|
+
user: data.user,
|
|
466
|
+
session: data.session,
|
|
467
|
+
referenceId: data.referenceId,
|
|
468
|
+
action: data.action
|
|
469
|
+
}, ctx) === true) return;
|
|
470
|
+
throw new APIError("UNAUTHORIZED");
|
|
471
|
+
}
|
|
472
|
+
if (options.organization?.enabled === true) {
|
|
473
|
+
const member = await ctx.context.adapter.findOne({
|
|
474
|
+
model: "member",
|
|
475
|
+
where: [{
|
|
476
|
+
field: "userId",
|
|
477
|
+
value: data.user.id
|
|
478
|
+
}, {
|
|
479
|
+
field: "organizationId",
|
|
480
|
+
value: data.referenceId
|
|
481
|
+
}]
|
|
482
|
+
});
|
|
483
|
+
if (member !== null && member !== void 0 && hasBillingRole(member.role, getBillingRoles(options))) return;
|
|
484
|
+
}
|
|
485
|
+
throw new APIError("UNAUTHORIZED");
|
|
486
|
+
}
|
|
487
|
+
//#endregion
|
|
488
|
+
//#region src/route-modules/webhook.ts
|
|
489
|
+
function getWebhookRequest(ctx) {
|
|
490
|
+
return ctx.requestClone ?? ctx.request;
|
|
491
|
+
}
|
|
492
|
+
function getWebhookHeaders(ctx) {
|
|
493
|
+
return ctx.headers ?? ctx.request?.headers;
|
|
494
|
+
}
|
|
495
|
+
//#endregion
|
|
496
|
+
//#region src/route-modules/shared.ts
|
|
497
|
+
const FLUTTERWAVE_ERROR_CODES = defineErrorCodes({
|
|
498
|
+
SUBSCRIPTION_NOT_FOUND: "Subscription not found",
|
|
499
|
+
SUBSCRIPTION_PLAN_NOT_FOUND: "Subscription plan not found",
|
|
500
|
+
FAILED_TO_INITIALIZE_TRANSACTION: "Failed to initialize transaction",
|
|
501
|
+
FAILED_TO_VERIFY_TRANSACTION: "Failed to verify transaction",
|
|
502
|
+
FAILED_TO_DISABLE_SUBSCRIPTION: "Failed to disable subscription",
|
|
503
|
+
FAILED_TO_ENABLE_SUBSCRIPTION: "Failed to enable subscription",
|
|
504
|
+
EMAIL_VERIFICATION_REQUIRED: "Email verification is required before you can subscribe to a plan",
|
|
505
|
+
SUBSCRIPTION_PAYMENT_CHANNEL_NOT_ALLOWED: "This subscription only supports specific payment channels"
|
|
506
|
+
});
|
|
507
|
+
async function hmacSha256Base64(secret, message) {
|
|
508
|
+
const encoder = new TextEncoder();
|
|
509
|
+
const keyData = encoder.encode(secret);
|
|
510
|
+
const msgData = encoder.encode(message);
|
|
511
|
+
const crypto = globalThis.crypto;
|
|
512
|
+
if (crypto !== void 0 && crypto !== null && "subtle" in crypto) {
|
|
513
|
+
const subtle = crypto.subtle;
|
|
514
|
+
const key = await subtle.importKey("raw", keyData, {
|
|
515
|
+
name: "HMAC",
|
|
516
|
+
hash: "SHA-256"
|
|
517
|
+
}, false, ["sign"]);
|
|
518
|
+
const signature = await subtle.sign("HMAC", key, msgData);
|
|
519
|
+
return Buffer.from(signature).toString("base64");
|
|
520
|
+
}
|
|
521
|
+
const { createHmac } = await import("node:crypto");
|
|
522
|
+
return createHmac("sha256", secret).update(message).digest("base64");
|
|
523
|
+
}
|
|
524
|
+
function timingSafeEqualString(left, right) {
|
|
525
|
+
const leftBytes = Buffer.from(left);
|
|
526
|
+
const rightBytes = Buffer.from(right);
|
|
527
|
+
if (leftBytes.length !== rightBytes.length) return false;
|
|
528
|
+
return timingSafeEqual(leftBytes, rightBytes);
|
|
529
|
+
}
|
|
530
|
+
//#endregion
|
|
531
|
+
//#region src/token-crypto.ts
|
|
532
|
+
const encoder = new TextEncoder();
|
|
533
|
+
const decoder = new TextDecoder();
|
|
534
|
+
function toBase64(value) {
|
|
535
|
+
return Buffer.from(value).toString("base64url");
|
|
536
|
+
}
|
|
537
|
+
function fromBase64(value) {
|
|
538
|
+
return new Uint8Array(Buffer.from(value, "base64url"));
|
|
539
|
+
}
|
|
540
|
+
async function deriveKey(secret) {
|
|
541
|
+
const digest = await crypto.subtle.digest("SHA-256", encoder.encode(secret));
|
|
542
|
+
return crypto.subtle.importKey("raw", digest, "AES-GCM", false, ["encrypt", "decrypt"]);
|
|
543
|
+
}
|
|
544
|
+
async function encryptPaymentToken(token, secret) {
|
|
545
|
+
const iv = crypto.getRandomValues(/* @__PURE__ */ new Uint8Array(12));
|
|
546
|
+
const encrypted = await crypto.subtle.encrypt({
|
|
547
|
+
name: "AES-GCM",
|
|
548
|
+
iv
|
|
549
|
+
}, await deriveKey(secret), encoder.encode(token));
|
|
550
|
+
return `v1.${toBase64(iv)}.${toBase64(new Uint8Array(encrypted))}`;
|
|
551
|
+
}
|
|
552
|
+
async function decryptPaymentToken(value, secret) {
|
|
553
|
+
const [version, encodedIv, encodedCiphertext] = value.split(".");
|
|
554
|
+
if (version !== "v1" || !encodedIv || !encodedCiphertext) throw new Error("Unsupported encrypted payment token");
|
|
555
|
+
const iv = Uint8Array.from(fromBase64(encodedIv));
|
|
556
|
+
const ciphertext = Uint8Array.from(fromBase64(encodedCiphertext));
|
|
557
|
+
const decrypted = await crypto.subtle.decrypt({
|
|
558
|
+
name: "AES-GCM",
|
|
559
|
+
iv
|
|
560
|
+
}, await deriveKey(secret), ciphertext);
|
|
561
|
+
return decoder.decode(decrypted);
|
|
562
|
+
}
|
|
563
|
+
//#endregion
|
|
564
|
+
//#region src/utils.ts
|
|
565
|
+
function normalizeSubscriptionGroup(group) {
|
|
566
|
+
const normalized = group?.trim().toLowerCase();
|
|
567
|
+
return normalized === void 0 || normalized === "" ? null : normalized;
|
|
568
|
+
}
|
|
569
|
+
async function getPlans(subscriptionOptions) {
|
|
570
|
+
if (subscriptionOptions?.enabled === true) return typeof subscriptionOptions.plans === "function" ? subscriptionOptions.plans() : subscriptionOptions.plans;
|
|
571
|
+
throw new Error("Subscriptions are not enabled in the Flutterwave options.");
|
|
572
|
+
}
|
|
573
|
+
async function getPlanByName(options, name) {
|
|
574
|
+
if (typeof name !== "string" || name.trim() === "") return null;
|
|
575
|
+
if (options.subscription?.enabled === true) {
|
|
576
|
+
const plans = await getPlans(options.subscription);
|
|
577
|
+
const normalizedName = name.toLowerCase();
|
|
578
|
+
return plans.find((plan) => typeof plan.name === "string" && plan.name.toLowerCase() === normalizedName) ?? null;
|
|
579
|
+
}
|
|
580
|
+
return null;
|
|
581
|
+
}
|
|
582
|
+
//#endregion
|
|
583
|
+
//#region src/routes.ts
|
|
584
|
+
const subaccountSchema = z.object({
|
|
585
|
+
id: z.string().min(1),
|
|
586
|
+
transactionSplitRatio: z.number().positive().optional(),
|
|
587
|
+
transactionChargeType: z.enum([
|
|
588
|
+
"flat",
|
|
589
|
+
"percentage",
|
|
590
|
+
"flat_subaccount"
|
|
591
|
+
]).optional(),
|
|
592
|
+
transactionCharge: z.number().nonnegative().optional()
|
|
593
|
+
});
|
|
594
|
+
const initializeBodySchema = z.object({
|
|
595
|
+
amount: z.number().positive().optional(),
|
|
596
|
+
currency: z.string().length(3).transform((value) => value.toUpperCase()).optional(),
|
|
597
|
+
redirectUrl: z.string().url(),
|
|
598
|
+
txRef: z.string().min(1).max(100).optional(),
|
|
599
|
+
referenceId: z.string().optional(),
|
|
600
|
+
plan: z.string().optional(),
|
|
601
|
+
product: z.string().optional(),
|
|
602
|
+
quantity: z.number().int().positive().default(1),
|
|
603
|
+
metadata: z.record(z.string(), z.unknown()).optional(),
|
|
604
|
+
paymentOptions: z.string().optional(),
|
|
605
|
+
subaccounts: z.array(subaccountSchema).optional()
|
|
606
|
+
});
|
|
607
|
+
const verifyBodySchema = z.object({
|
|
608
|
+
transactionId: z.union([z.string(), z.number()]).optional(),
|
|
609
|
+
txRef: z.string().optional(),
|
|
610
|
+
referenceId: z.string().optional()
|
|
611
|
+
}).refine((body) => body.transactionId === void 0 !== (body.txRef === void 0), { message: "Provide exactly one of transactionId or txRef" });
|
|
612
|
+
const webhookPayloadSchema = z.object({
|
|
613
|
+
event: z.string().min(1),
|
|
614
|
+
data: z.object({
|
|
615
|
+
id: z.union([z.string(), z.number()]).optional(),
|
|
616
|
+
tx_ref: z.string().optional(),
|
|
617
|
+
flw_ref: z.string().optional(),
|
|
618
|
+
status: z.string().optional(),
|
|
619
|
+
amount: z.coerce.number().optional(),
|
|
620
|
+
charged_amount: z.coerce.number().optional(),
|
|
621
|
+
currency: z.string().optional(),
|
|
622
|
+
payment_type: z.string().optional(),
|
|
623
|
+
customer: z.object({ email: z.string().optional() }).passthrough().optional()
|
|
624
|
+
}).passthrough()
|
|
625
|
+
});
|
|
626
|
+
function adapter$1(options) {
|
|
627
|
+
return createFlutterwaveAdapter({
|
|
628
|
+
publicKey: options.publicKey,
|
|
629
|
+
secretKey: options.secretKey,
|
|
630
|
+
flutterwaveClient: options.flutterwaveClient,
|
|
631
|
+
fetch: options.fetch,
|
|
632
|
+
apiBaseUrl: options.apiBaseUrl
|
|
633
|
+
});
|
|
634
|
+
}
|
|
635
|
+
function mapTransaction(data) {
|
|
636
|
+
return {
|
|
637
|
+
id: data.id,
|
|
638
|
+
txRef: data.tx_ref,
|
|
639
|
+
flwRef: data.flw_ref ?? void 0,
|
|
640
|
+
status: data.status,
|
|
641
|
+
amount: data.amount,
|
|
642
|
+
chargedAmount: data.charged_amount,
|
|
643
|
+
currency: data.currency,
|
|
644
|
+
paymentType: data.payment_type ?? void 0,
|
|
645
|
+
customer: data.customer ? {
|
|
646
|
+
email: data.customer.email,
|
|
647
|
+
name: data.customer.name ?? void 0
|
|
648
|
+
} : void 0
|
|
649
|
+
};
|
|
650
|
+
}
|
|
651
|
+
async function authenticatedReference(ctx, options, action, requested) {
|
|
652
|
+
const current = await getSessionFromCtx(ctx);
|
|
653
|
+
if (!current) throw new APIError("UNAUTHORIZED");
|
|
654
|
+
const referenceId = requested ?? current.user.id;
|
|
655
|
+
await authorizeBillingReference(ctx, options, {
|
|
656
|
+
user: current.user,
|
|
657
|
+
session: current.session,
|
|
658
|
+
referenceId,
|
|
659
|
+
action
|
|
660
|
+
});
|
|
661
|
+
return {
|
|
662
|
+
user: current.user,
|
|
663
|
+
session: current.session,
|
|
664
|
+
referenceId
|
|
665
|
+
};
|
|
666
|
+
}
|
|
667
|
+
async function resolveBillingEmail(ctx, options, referenceId, user) {
|
|
668
|
+
if (referenceId === user.id) return user.email;
|
|
669
|
+
if (options.organization?.enabled !== true) throw new APIError("UNAUTHORIZED");
|
|
670
|
+
const store = createBillingStore(ctx);
|
|
671
|
+
const explicit = (await store.findOrganization(referenceId))?.email;
|
|
672
|
+
if (explicit) return explicit;
|
|
673
|
+
const owner = await store.findOrganizationOwner(referenceId);
|
|
674
|
+
const ownerUser = owner ? await store.findUser(owner.userId) : null;
|
|
675
|
+
if (!ownerUser?.email) throw new APIError("BAD_REQUEST", { message: "Billing email not found" });
|
|
676
|
+
return ownerUser.email;
|
|
677
|
+
}
|
|
678
|
+
async function configuredProducts(options) {
|
|
679
|
+
const source = options.products?.products;
|
|
680
|
+
if (!source) return [];
|
|
681
|
+
return typeof source === "function" ? source() : source;
|
|
682
|
+
}
|
|
683
|
+
const initializeTransaction = (options, path) => createAuthEndpoint(path, {
|
|
684
|
+
method: "POST",
|
|
685
|
+
body: initializeBodySchema,
|
|
686
|
+
use: [sessionMiddleware, originCheck]
|
|
687
|
+
}, async (ctx) => {
|
|
688
|
+
const { user, referenceId } = await authenticatedReference(ctx, options, "initialize-transaction", ctx.body.referenceId);
|
|
689
|
+
if (options.subscription?.requireEmailVerification === true && ctx.body.plan && user.emailVerified !== true) throw new APIError("BAD_REQUEST", FLUTTERWAVE_ERROR_CODES.EMAIL_VERIFICATION_REQUIRED);
|
|
690
|
+
const billingEmail = await resolveBillingEmail(ctx, options, referenceId, user);
|
|
691
|
+
const plans = await getPlans(options.subscription);
|
|
692
|
+
const plan = ctx.body.plan ? plans.find((candidate) => candidate.name.toLowerCase() === ctx.body.plan?.toLowerCase()) : void 0;
|
|
693
|
+
if (ctx.body.plan && !plan) throw new APIError("NOT_FOUND", { message: "Plan not found" });
|
|
694
|
+
const products = await configuredProducts(options);
|
|
695
|
+
const product = ctx.body.product ? products.find((candidate) => candidate.name.toLowerCase() === ctx.body.product?.toLowerCase() || candidate.slug === ctx.body.product) : void 0;
|
|
696
|
+
if (ctx.body.product && !product) throw new APIError("NOT_FOUND", { message: "Product not found" });
|
|
697
|
+
const amount = ctx.body.amount ?? (plan?.amount !== void 0 ? plan.amount + (plan.seatAmount ?? 0) * Math.max(0, ctx.body.quantity - 1) : product ? product.price * ctx.body.quantity : void 0);
|
|
698
|
+
const currency = ctx.body.currency ?? plan?.currency ?? product?.currency;
|
|
699
|
+
if (!amount || !currency) throw new APIError("BAD_REQUEST", { message: "amount and currency are required" });
|
|
700
|
+
const requestedSplits = ctx.body.subaccounts ?? options.marketplace?.defaultSplit;
|
|
701
|
+
const allowed = new Set(options.marketplace?.allowedSubaccountIds ?? []);
|
|
702
|
+
if (requestedSplits?.some(({ id }) => !allowed.has(id))) throw new APIError("FORBIDDEN", { message: "Subaccount is not allowlisted" });
|
|
703
|
+
const txRef = ctx.body.txRef ?? `flw_${crypto.randomUUID()}`;
|
|
704
|
+
const groupId = normalizeSubscriptionGroup(plan?.group);
|
|
705
|
+
const metadata = createCheckoutMetadata({
|
|
706
|
+
referenceId,
|
|
707
|
+
userId: user.id,
|
|
708
|
+
plan: plan?.name,
|
|
709
|
+
groupId,
|
|
710
|
+
product: product?.name,
|
|
711
|
+
extra: ctx.body.metadata,
|
|
712
|
+
trial: {
|
|
713
|
+
isTrial: false,
|
|
714
|
+
requested: false,
|
|
715
|
+
granted: false
|
|
716
|
+
}
|
|
717
|
+
});
|
|
718
|
+
const result = await adapter$1(options).initializePayment({
|
|
719
|
+
tx_ref: txRef,
|
|
720
|
+
amount,
|
|
721
|
+
currency,
|
|
722
|
+
redirect_url: ctx.body.redirectUrl,
|
|
723
|
+
customer: {
|
|
724
|
+
email: billingEmail,
|
|
725
|
+
name: user.name
|
|
726
|
+
},
|
|
727
|
+
payment_options: plan?.paymentPlanId ? "card" : ctx.body.paymentOptions,
|
|
728
|
+
payment_plan: plan?.paymentPlanId,
|
|
729
|
+
subaccounts: requestedSplits?.map((split) => ({
|
|
730
|
+
id: split.id,
|
|
731
|
+
transaction_charge_type: split.transactionChargeType === "flat_subaccount" ? "flat" : split.transactionChargeType,
|
|
732
|
+
transaction_charge: split.transactionCharge,
|
|
733
|
+
transaction_split_ratio: split.transactionSplitRatio
|
|
734
|
+
})),
|
|
735
|
+
meta: metadata
|
|
736
|
+
});
|
|
737
|
+
const store = createBillingStore(ctx);
|
|
738
|
+
const now = /* @__PURE__ */ new Date();
|
|
739
|
+
await store.createTransaction({
|
|
740
|
+
txRef,
|
|
741
|
+
referenceId,
|
|
742
|
+
userId: user.id,
|
|
743
|
+
amount,
|
|
744
|
+
currency,
|
|
745
|
+
status: "pending",
|
|
746
|
+
plan: plan?.name,
|
|
747
|
+
product: product?.name,
|
|
748
|
+
subaccountId: requestedSplits?.[0]?.id,
|
|
749
|
+
metadata: stringifyFlutterwaveMetadata(metadata),
|
|
750
|
+
createdAt: now,
|
|
751
|
+
updatedAt: now
|
|
752
|
+
});
|
|
753
|
+
if (plan) await store.createSubscription({
|
|
754
|
+
userId: user.id,
|
|
755
|
+
referenceId,
|
|
756
|
+
plan: plan.name,
|
|
757
|
+
paymentPlanId: plan.paymentPlanId,
|
|
758
|
+
txRef,
|
|
759
|
+
billingEmail,
|
|
760
|
+
status: "incomplete",
|
|
761
|
+
seats: ctx.body.quantity,
|
|
762
|
+
groupId,
|
|
763
|
+
cancelAtPeriodEnd: false,
|
|
764
|
+
billingInterval: plan.interval,
|
|
765
|
+
createdAt: now,
|
|
766
|
+
updatedAt: now
|
|
767
|
+
});
|
|
768
|
+
return {
|
|
769
|
+
kind: "checkout",
|
|
770
|
+
url: result.link,
|
|
771
|
+
txRef,
|
|
772
|
+
redirect: true
|
|
773
|
+
};
|
|
774
|
+
});
|
|
775
|
+
const verifyTransaction = (options, path) => createAuthEndpoint(path, {
|
|
776
|
+
method: "POST",
|
|
777
|
+
body: verifyBodySchema,
|
|
778
|
+
use: [sessionMiddleware, originCheck]
|
|
779
|
+
}, async (ctx) => {
|
|
780
|
+
const store = createBillingStore(ctx);
|
|
781
|
+
const expected = ctx.body.txRef ? await store.findTransactionByTxRef(ctx.body.txRef) : await store.findTransactionById(Number(ctx.body.transactionId));
|
|
782
|
+
if (!expected) throw new APIError("NOT_FOUND", { message: "Transaction not found" });
|
|
783
|
+
if (ctx.body.referenceId !== void 0 && ctx.body.referenceId !== expected.referenceId) throw new APIError("UNAUTHORIZED");
|
|
784
|
+
await authenticatedReference(ctx, options, "verify-transaction", expected.referenceId);
|
|
785
|
+
const verified = await adapter$1(options).verifyTransaction({
|
|
786
|
+
transactionId: ctx.body.transactionId === void 0 ? void 0 : Number(ctx.body.transactionId),
|
|
787
|
+
txRef: ctx.body.txRef
|
|
788
|
+
});
|
|
789
|
+
if (verified.tx_ref !== expected.txRef || verified.amount !== expected.amount || verified.currency !== expected.currency || verified.status !== "successful") throw new APIError("BAD_REQUEST", { message: "Verified transaction does not match the expected payment" });
|
|
790
|
+
const now = /* @__PURE__ */ new Date();
|
|
791
|
+
await store.updateTransactionByTxRef(expected.txRef, {
|
|
792
|
+
transactionId: verified.id,
|
|
793
|
+
flwRef: verified.flw_ref,
|
|
794
|
+
chargedAmount: verified.charged_amount,
|
|
795
|
+
paymentType: verified.payment_type,
|
|
796
|
+
status: verified.status,
|
|
797
|
+
verifiedAt: now,
|
|
798
|
+
reconciledAt: now,
|
|
799
|
+
updatedAt: now
|
|
800
|
+
});
|
|
801
|
+
const linked = await store.findSubscriptionsByTxRef(expected.txRef);
|
|
802
|
+
for (const subscription of linked) {
|
|
803
|
+
let subscriptionId = subscription.subscriptionId;
|
|
804
|
+
if (subscription.paymentPlanId && subscription.billingEmail) {
|
|
805
|
+
const matches = (await adapter$1(options).listSubscriptions({
|
|
806
|
+
email: subscription.billingEmail,
|
|
807
|
+
plan: subscription.paymentPlanId,
|
|
808
|
+
transactionId: verified.id
|
|
809
|
+
})).filter((candidate) => candidate.status !== "cancelled");
|
|
810
|
+
subscriptionId = matches.length === 1 ? matches[0]?.id : void 0;
|
|
811
|
+
}
|
|
812
|
+
await store.updateSubscription(subscription.id, {
|
|
813
|
+
subscriptionId,
|
|
814
|
+
status: subscription.paymentPlanId !== void 0 && subscription.paymentPlanId !== null && subscriptionId === void 0 ? "incomplete" : "active",
|
|
815
|
+
encryptedPaymentToken: verified.card?.token ? await encryptPaymentToken(verified.card.token, ctx.context.secret) : subscription.encryptedPaymentToken,
|
|
816
|
+
periodStart: now,
|
|
817
|
+
reconciledAt: now,
|
|
818
|
+
updatedAt: now
|
|
819
|
+
});
|
|
820
|
+
await store.retireCompetingSubscriptions(subscription.referenceId, subscription.groupId ?? null, subscription.id);
|
|
821
|
+
}
|
|
822
|
+
return {
|
|
823
|
+
status: verified.status,
|
|
824
|
+
txRef: verified.tx_ref,
|
|
825
|
+
data: mapTransaction(verified)
|
|
826
|
+
};
|
|
827
|
+
});
|
|
828
|
+
const referenceQuerySchema = z.object({ referenceId: z.string().optional() });
|
|
829
|
+
const listTransactions = (options, path) => createAuthEndpoint(path, {
|
|
830
|
+
method: "GET",
|
|
831
|
+
query: referenceQuerySchema,
|
|
832
|
+
use: [sessionMiddleware]
|
|
833
|
+
}, async (ctx) => {
|
|
834
|
+
const current = await getSessionFromCtx(ctx);
|
|
835
|
+
if (!current) throw new APIError("UNAUTHORIZED");
|
|
836
|
+
const referenceId = resolveBillingReferenceId({
|
|
837
|
+
query: ctx.query,
|
|
838
|
+
requestUrl: ctx.request?.url,
|
|
839
|
+
fallbackUserId: current.user.id
|
|
840
|
+
});
|
|
841
|
+
await authenticatedReference(ctx, options, "list-transactions", referenceId);
|
|
842
|
+
return { transactions: await createBillingStore(ctx).listTransactions(referenceId) };
|
|
843
|
+
});
|
|
844
|
+
const listSubscriptions = (options, path) => createAuthEndpoint(path, {
|
|
845
|
+
method: "GET",
|
|
846
|
+
query: referenceQuerySchema,
|
|
847
|
+
use: [sessionMiddleware]
|
|
848
|
+
}, async (ctx) => {
|
|
849
|
+
const current = await getSessionFromCtx(ctx);
|
|
850
|
+
if (!current) throw new APIError("UNAUTHORIZED");
|
|
851
|
+
const referenceId = resolveBillingReferenceId({
|
|
852
|
+
query: ctx.query,
|
|
853
|
+
requestUrl: ctx.request?.url,
|
|
854
|
+
fallbackUserId: current.user.id
|
|
855
|
+
});
|
|
856
|
+
await authenticatedReference(ctx, options, "list-subscriptions", referenceId);
|
|
857
|
+
return { subscriptions: await createBillingStore(ctx).findSubscriptionsByReference(referenceId) };
|
|
858
|
+
});
|
|
859
|
+
const subscriptionBodySchema = z.object({
|
|
860
|
+
subscriptionId: z.coerce.number().int().positive(),
|
|
861
|
+
atPeriodEnd: z.boolean().optional()
|
|
862
|
+
});
|
|
863
|
+
const cancelSubscription = (options, path) => createAuthEndpoint(path, {
|
|
864
|
+
method: "POST",
|
|
865
|
+
body: subscriptionBodySchema,
|
|
866
|
+
use: [sessionMiddleware, originCheck]
|
|
867
|
+
}, async (ctx) => {
|
|
868
|
+
const store = createBillingStore(ctx);
|
|
869
|
+
const local = await store.findSubscriptionByProviderId(ctx.body.subscriptionId);
|
|
870
|
+
if (!local) throw new APIError("NOT_FOUND", { message: "Subscription not found" });
|
|
871
|
+
await authenticatedReference(ctx, options, "disable-subscription", local.referenceId);
|
|
872
|
+
const now = /* @__PURE__ */ new Date();
|
|
873
|
+
if (ctx.body.atPeriodEnd === true || options.subscription?.cancelBehavior === "at_period_end") {
|
|
874
|
+
await store.updateSubscription(local.id, {
|
|
875
|
+
cancelAtPeriodEnd: true,
|
|
876
|
+
cancelAt: local.periodEnd ?? now,
|
|
877
|
+
updatedAt: now
|
|
878
|
+
});
|
|
879
|
+
return { status: "scheduled" };
|
|
880
|
+
}
|
|
881
|
+
await adapter$1(options).cancelSubscription(ctx.body.subscriptionId);
|
|
882
|
+
await store.updateSubscription(local.id, {
|
|
883
|
+
status: "canceled",
|
|
884
|
+
cancelAtPeriodEnd: false,
|
|
885
|
+
canceledAt: now,
|
|
886
|
+
endedAt: now,
|
|
887
|
+
updatedAt: now
|
|
888
|
+
});
|
|
889
|
+
return { status: "canceled" };
|
|
890
|
+
});
|
|
891
|
+
const restoreSubscription = (options, path) => createAuthEndpoint(path, {
|
|
892
|
+
method: "POST",
|
|
893
|
+
body: subscriptionBodySchema.omit({ atPeriodEnd: true }),
|
|
894
|
+
use: [sessionMiddleware, originCheck]
|
|
895
|
+
}, async (ctx) => {
|
|
896
|
+
const store = createBillingStore(ctx);
|
|
897
|
+
const local = await store.findSubscriptionByProviderId(ctx.body.subscriptionId);
|
|
898
|
+
if (!local) throw new APIError("NOT_FOUND", { message: "Subscription not found" });
|
|
899
|
+
await authenticatedReference(ctx, options, "enable-subscription", local.referenceId);
|
|
900
|
+
await adapter$1(options).activateSubscription(ctx.body.subscriptionId);
|
|
901
|
+
await store.updateSubscription(local.id, {
|
|
902
|
+
status: "active",
|
|
903
|
+
cancelAtPeriodEnd: false,
|
|
904
|
+
cancelAt: null,
|
|
905
|
+
canceledAt: null,
|
|
906
|
+
endedAt: null,
|
|
907
|
+
updatedAt: /* @__PURE__ */ new Date()
|
|
908
|
+
});
|
|
909
|
+
return { status: "active" };
|
|
910
|
+
});
|
|
911
|
+
const createSubscription = initializeTransaction;
|
|
912
|
+
const upgradeSubscription = initializeTransaction;
|
|
913
|
+
const listProducts = (options, path) => createAuthEndpoint(path, { method: "GET" }, async (ctx) => {
|
|
914
|
+
const configured = await configuredProducts(options);
|
|
915
|
+
const stored = await createBillingStore(ctx).listProducts();
|
|
916
|
+
return { products: stored.length > 0 ? stored : configured };
|
|
917
|
+
});
|
|
918
|
+
const listPlans = (options, path) => createAuthEndpoint(path, { method: "GET" }, async (ctx) => {
|
|
919
|
+
const configured = await getPlans(options.subscription);
|
|
920
|
+
const stored = await createBillingStore(ctx).listPlans();
|
|
921
|
+
return { plans: stored.length > 0 ? stored : configured };
|
|
922
|
+
});
|
|
923
|
+
const getConfig = (options, path) => createAuthEndpoint(path, { method: "GET" }, async (ctx) => ({
|
|
924
|
+
plans: (await createBillingStore(ctx).listPlans()).concat(await getPlans(options.subscription)),
|
|
925
|
+
products: await configuredProducts(options),
|
|
926
|
+
subscriptions: options.subscription?.enabled === true,
|
|
927
|
+
marketplace: options.marketplace !== void 0
|
|
928
|
+
}));
|
|
929
|
+
const flutterwaveWebhook = (options, path) => createAuthEndpoint(path, {
|
|
930
|
+
method: "POST",
|
|
931
|
+
metadata: {
|
|
932
|
+
...HIDE_METADATA,
|
|
933
|
+
openapi: { operationId: "flutterwaveWebhook" }
|
|
934
|
+
},
|
|
935
|
+
cloneRequest: true,
|
|
936
|
+
disableBody: true
|
|
937
|
+
}, async (ctx) => {
|
|
938
|
+
const request = getWebhookRequest(ctx);
|
|
939
|
+
if (!request) throw new APIError("BAD_REQUEST", { message: "Request is missing" });
|
|
940
|
+
const rawBody = await request.text();
|
|
941
|
+
const signature = getWebhookHeaders(ctx)?.get("flutterwave-signature");
|
|
942
|
+
if (!signature) throw new APIError("UNAUTHORIZED", { message: "Missing signature" });
|
|
943
|
+
if (!timingSafeEqualString(signature, await hmacSha256Base64(options.webhook?.secretHash ?? options.secretHash, rawBody))) throw new APIError("UNAUTHORIZED", { message: "Invalid signature" });
|
|
944
|
+
let webhookJson;
|
|
945
|
+
try {
|
|
946
|
+
webhookJson = JSON.parse(rawBody);
|
|
947
|
+
} catch {
|
|
948
|
+
ctx.context.logger.warn("Ignoring non-JSON signed Flutterwave webhook");
|
|
949
|
+
return ctx.json({ received: true });
|
|
950
|
+
}
|
|
951
|
+
const parsedEvent = webhookPayloadSchema.safeParse(webhookJson);
|
|
952
|
+
if (!parsedEvent.success) {
|
|
953
|
+
ctx.context.logger.warn("Ignoring malformed signed Flutterwave webhook");
|
|
954
|
+
return ctx.json({ received: true });
|
|
955
|
+
}
|
|
956
|
+
const event = parsedEvent.data;
|
|
957
|
+
const data = event.data;
|
|
958
|
+
const eventId = createHash("sha256").update(`${event.event}:${String(data.id ?? "")}:${String(data.status ?? "")}`).digest("hex");
|
|
959
|
+
const store = createBillingStore(ctx);
|
|
960
|
+
const existingEvent = await store.findWebhookEvent(eventId);
|
|
961
|
+
if (existingEvent?.status === "processed") return ctx.json({ received: true });
|
|
962
|
+
const now = /* @__PURE__ */ new Date();
|
|
963
|
+
if (existingEvent === null) try {
|
|
964
|
+
await store.createWebhookEvent({
|
|
965
|
+
eventId,
|
|
966
|
+
eventType: event.event,
|
|
967
|
+
transactionId: data.id === void 0 ? void 0 : Number(data.id),
|
|
968
|
+
txRef: data.tx_ref,
|
|
969
|
+
payload: rawBody,
|
|
970
|
+
status: "processing",
|
|
971
|
+
createdAt: now,
|
|
972
|
+
updatedAt: now
|
|
973
|
+
});
|
|
974
|
+
} catch (error) {
|
|
975
|
+
const concurrent = await store.findWebhookEvent(eventId);
|
|
976
|
+
if (concurrent === null) throw error;
|
|
977
|
+
if (concurrent.status === "processed" || concurrent.status === "processing") return ctx.json({ received: true });
|
|
978
|
+
}
|
|
979
|
+
else await store.updateWebhookEvent(eventId, {
|
|
980
|
+
status: "processing",
|
|
981
|
+
updatedAt: now
|
|
982
|
+
});
|
|
983
|
+
if (data.tx_ref && data.id !== void 0) try {
|
|
984
|
+
const local = await store.findTransactionByTxRef(data.tx_ref);
|
|
985
|
+
const verified = await adapter$1(options).verifyTransaction({ transactionId: Number(data.id) });
|
|
986
|
+
if (local && verified.tx_ref === local.txRef && verified.amount === local.amount && verified.currency === local.currency) {
|
|
987
|
+
await store.updateTransactionByTxRef(local.txRef, {
|
|
988
|
+
transactionId: verified.id,
|
|
989
|
+
flwRef: verified.flw_ref,
|
|
990
|
+
chargedAmount: verified.charged_amount,
|
|
991
|
+
paymentType: verified.payment_type,
|
|
992
|
+
status: verified.status,
|
|
993
|
+
verifiedAt: now,
|
|
994
|
+
reconciledAt: now,
|
|
995
|
+
updatedAt: now
|
|
996
|
+
});
|
|
997
|
+
if (verified.status === "successful") for (const subscription of await store.findSubscriptionsByTxRef(local.txRef)) {
|
|
998
|
+
let subscriptionId = subscription.subscriptionId;
|
|
999
|
+
if (subscription.paymentPlanId !== void 0 && subscription.paymentPlanId !== null && subscription.billingEmail !== void 0 && subscription.billingEmail !== null && subscription.billingEmail !== "") {
|
|
1000
|
+
const matches = (await adapter$1(options).listSubscriptions({
|
|
1001
|
+
email: subscription.billingEmail,
|
|
1002
|
+
plan: subscription.paymentPlanId,
|
|
1003
|
+
transactionId: verified.id
|
|
1004
|
+
})).filter((candidate) => candidate.status !== "cancelled");
|
|
1005
|
+
subscriptionId = matches.length === 1 ? matches[0]?.id : void 0;
|
|
1006
|
+
}
|
|
1007
|
+
await store.updateSubscription(subscription.id, {
|
|
1008
|
+
subscriptionId,
|
|
1009
|
+
status: subscription.paymentPlanId !== void 0 && subscription.paymentPlanId !== null && subscriptionId === void 0 ? "incomplete" : "active",
|
|
1010
|
+
encryptedPaymentToken: verified.card?.token !== void 0 ? await encryptPaymentToken(verified.card.token, ctx.context.secret) : subscription.encryptedPaymentToken,
|
|
1011
|
+
reconciledAt: now,
|
|
1012
|
+
updatedAt: now
|
|
1013
|
+
});
|
|
1014
|
+
await store.retireCompetingSubscriptions(subscription.referenceId, subscription.groupId ?? null, subscription.id);
|
|
1015
|
+
}
|
|
1016
|
+
}
|
|
1017
|
+
} catch (error) {
|
|
1018
|
+
ctx.context.logger.error("Flutterwave webhook reconciliation failed", error);
|
|
1019
|
+
await store.updateWebhookEvent(eventId, {
|
|
1020
|
+
status: "failed",
|
|
1021
|
+
updatedAt: /* @__PURE__ */ new Date()
|
|
1022
|
+
});
|
|
1023
|
+
return ctx.json({ received: true });
|
|
1024
|
+
}
|
|
1025
|
+
await store.updateWebhookEvent(eventId, {
|
|
1026
|
+
status: "processed",
|
|
1027
|
+
processedAt: /* @__PURE__ */ new Date(),
|
|
1028
|
+
updatedAt: /* @__PURE__ */ new Date()
|
|
1029
|
+
});
|
|
1030
|
+
await options.onEvent?.(event);
|
|
1031
|
+
return ctx.json({ received: true });
|
|
1032
|
+
});
|
|
1033
|
+
//#endregion
|
|
1034
|
+
//#region src/schema.ts
|
|
1035
|
+
const transactions = { flutterwaveTransaction: { fields: {
|
|
1036
|
+
txRef: {
|
|
1037
|
+
type: "string",
|
|
1038
|
+
required: true,
|
|
1039
|
+
unique: true
|
|
1040
|
+
},
|
|
1041
|
+
transactionId: {
|
|
1042
|
+
type: "number",
|
|
1043
|
+
required: false,
|
|
1044
|
+
unique: true
|
|
1045
|
+
},
|
|
1046
|
+
flwRef: {
|
|
1047
|
+
type: "string",
|
|
1048
|
+
required: false,
|
|
1049
|
+
index: true
|
|
1050
|
+
},
|
|
1051
|
+
referenceId: {
|
|
1052
|
+
type: "string",
|
|
1053
|
+
required: true,
|
|
1054
|
+
index: true
|
|
1055
|
+
},
|
|
1056
|
+
userId: {
|
|
1057
|
+
type: "string",
|
|
1058
|
+
required: true,
|
|
1059
|
+
index: true
|
|
1060
|
+
},
|
|
1061
|
+
amount: {
|
|
1062
|
+
type: "number",
|
|
1063
|
+
required: false
|
|
1064
|
+
},
|
|
1065
|
+
chargedAmount: {
|
|
1066
|
+
type: "number",
|
|
1067
|
+
required: false
|
|
1068
|
+
},
|
|
1069
|
+
currency: {
|
|
1070
|
+
type: "string",
|
|
1071
|
+
required: true
|
|
1072
|
+
},
|
|
1073
|
+
status: {
|
|
1074
|
+
type: "string",
|
|
1075
|
+
required: true,
|
|
1076
|
+
index: true
|
|
1077
|
+
},
|
|
1078
|
+
paymentPlanId: {
|
|
1079
|
+
type: "number",
|
|
1080
|
+
required: false,
|
|
1081
|
+
index: true
|
|
1082
|
+
},
|
|
1083
|
+
plan: {
|
|
1084
|
+
type: "string",
|
|
1085
|
+
required: false,
|
|
1086
|
+
index: true
|
|
1087
|
+
},
|
|
1088
|
+
product: {
|
|
1089
|
+
type: "string",
|
|
1090
|
+
required: false
|
|
1091
|
+
},
|
|
1092
|
+
paymentType: {
|
|
1093
|
+
type: "string",
|
|
1094
|
+
required: false
|
|
1095
|
+
},
|
|
1096
|
+
subaccountId: {
|
|
1097
|
+
type: "string",
|
|
1098
|
+
required: false,
|
|
1099
|
+
index: true
|
|
1100
|
+
},
|
|
1101
|
+
metadata: {
|
|
1102
|
+
type: "string",
|
|
1103
|
+
required: false
|
|
1104
|
+
},
|
|
1105
|
+
verifiedAt: {
|
|
1106
|
+
type: "date",
|
|
1107
|
+
required: false
|
|
1108
|
+
},
|
|
1109
|
+
reconciledAt: {
|
|
1110
|
+
type: "date",
|
|
1111
|
+
required: false
|
|
1112
|
+
},
|
|
1113
|
+
createdAt: {
|
|
1114
|
+
type: "date",
|
|
1115
|
+
required: true
|
|
1116
|
+
},
|
|
1117
|
+
updatedAt: {
|
|
1118
|
+
type: "date",
|
|
1119
|
+
required: true
|
|
1120
|
+
}
|
|
1121
|
+
} } };
|
|
1122
|
+
const subscriptions = { flutterwaveSubscription: { fields: {
|
|
1123
|
+
plan: {
|
|
1124
|
+
type: "string",
|
|
1125
|
+
required: true,
|
|
1126
|
+
index: true
|
|
1127
|
+
},
|
|
1128
|
+
referenceId: {
|
|
1129
|
+
type: "string",
|
|
1130
|
+
required: true,
|
|
1131
|
+
index: true
|
|
1132
|
+
},
|
|
1133
|
+
userId: {
|
|
1134
|
+
type: "string",
|
|
1135
|
+
required: true,
|
|
1136
|
+
index: true
|
|
1137
|
+
},
|
|
1138
|
+
billingEmail: {
|
|
1139
|
+
type: "string",
|
|
1140
|
+
required: true,
|
|
1141
|
+
index: true
|
|
1142
|
+
},
|
|
1143
|
+
subscriptionId: {
|
|
1144
|
+
type: "number",
|
|
1145
|
+
required: false,
|
|
1146
|
+
unique: true
|
|
1147
|
+
},
|
|
1148
|
+
paymentPlanId: {
|
|
1149
|
+
type: "number",
|
|
1150
|
+
required: false,
|
|
1151
|
+
index: true
|
|
1152
|
+
},
|
|
1153
|
+
txRef: {
|
|
1154
|
+
type: "string",
|
|
1155
|
+
required: false,
|
|
1156
|
+
index: true
|
|
1157
|
+
},
|
|
1158
|
+
encryptedPaymentToken: {
|
|
1159
|
+
type: "string",
|
|
1160
|
+
required: false
|
|
1161
|
+
},
|
|
1162
|
+
status: {
|
|
1163
|
+
type: "string",
|
|
1164
|
+
required: true,
|
|
1165
|
+
defaultValue: "incomplete",
|
|
1166
|
+
index: true
|
|
1167
|
+
},
|
|
1168
|
+
periodStart: {
|
|
1169
|
+
type: "date",
|
|
1170
|
+
required: false
|
|
1171
|
+
},
|
|
1172
|
+
periodEnd: {
|
|
1173
|
+
type: "date",
|
|
1174
|
+
required: false
|
|
1175
|
+
},
|
|
1176
|
+
trialStart: {
|
|
1177
|
+
type: "date",
|
|
1178
|
+
required: false
|
|
1179
|
+
},
|
|
1180
|
+
trialEnd: {
|
|
1181
|
+
type: "date",
|
|
1182
|
+
required: false
|
|
1183
|
+
},
|
|
1184
|
+
cancelAtPeriodEnd: {
|
|
1185
|
+
type: "boolean",
|
|
1186
|
+
required: false,
|
|
1187
|
+
defaultValue: false
|
|
1188
|
+
},
|
|
1189
|
+
cancelAt: {
|
|
1190
|
+
type: "date",
|
|
1191
|
+
required: false
|
|
1192
|
+
},
|
|
1193
|
+
canceledAt: {
|
|
1194
|
+
type: "date",
|
|
1195
|
+
required: false
|
|
1196
|
+
},
|
|
1197
|
+
endedAt: {
|
|
1198
|
+
type: "date",
|
|
1199
|
+
required: false
|
|
1200
|
+
},
|
|
1201
|
+
billingInterval: {
|
|
1202
|
+
type: "string",
|
|
1203
|
+
required: false
|
|
1204
|
+
},
|
|
1205
|
+
groupId: {
|
|
1206
|
+
type: "string",
|
|
1207
|
+
required: false,
|
|
1208
|
+
index: true
|
|
1209
|
+
},
|
|
1210
|
+
seats: {
|
|
1211
|
+
type: "number",
|
|
1212
|
+
required: false
|
|
1213
|
+
},
|
|
1214
|
+
pendingPlan: {
|
|
1215
|
+
type: "string",
|
|
1216
|
+
required: false
|
|
1217
|
+
},
|
|
1218
|
+
reconciledAt: {
|
|
1219
|
+
type: "date",
|
|
1220
|
+
required: false
|
|
1221
|
+
},
|
|
1222
|
+
createdAt: {
|
|
1223
|
+
type: "date",
|
|
1224
|
+
required: true
|
|
1225
|
+
},
|
|
1226
|
+
updatedAt: {
|
|
1227
|
+
type: "date",
|
|
1228
|
+
required: true
|
|
1229
|
+
}
|
|
1230
|
+
} } };
|
|
1231
|
+
const products = { flutterwaveProduct: { fields: {
|
|
1232
|
+
name: {
|
|
1233
|
+
type: "string",
|
|
1234
|
+
required: true
|
|
1235
|
+
},
|
|
1236
|
+
description: {
|
|
1237
|
+
type: "string",
|
|
1238
|
+
required: false
|
|
1239
|
+
},
|
|
1240
|
+
price: {
|
|
1241
|
+
type: "number",
|
|
1242
|
+
required: true
|
|
1243
|
+
},
|
|
1244
|
+
currency: {
|
|
1245
|
+
type: "string",
|
|
1246
|
+
required: true
|
|
1247
|
+
},
|
|
1248
|
+
quantity: {
|
|
1249
|
+
type: "number",
|
|
1250
|
+
required: false,
|
|
1251
|
+
defaultValue: 0
|
|
1252
|
+
},
|
|
1253
|
+
unlimited: {
|
|
1254
|
+
type: "boolean",
|
|
1255
|
+
required: false,
|
|
1256
|
+
defaultValue: true
|
|
1257
|
+
},
|
|
1258
|
+
slug: {
|
|
1259
|
+
type: "string",
|
|
1260
|
+
required: true,
|
|
1261
|
+
unique: true
|
|
1262
|
+
},
|
|
1263
|
+
metadata: {
|
|
1264
|
+
type: "string",
|
|
1265
|
+
required: false
|
|
1266
|
+
},
|
|
1267
|
+
createdAt: {
|
|
1268
|
+
type: "date",
|
|
1269
|
+
required: true
|
|
1270
|
+
},
|
|
1271
|
+
updatedAt: {
|
|
1272
|
+
type: "date",
|
|
1273
|
+
required: true
|
|
1274
|
+
}
|
|
1275
|
+
} } };
|
|
1276
|
+
const plans = { flutterwavePlan: { fields: {
|
|
1277
|
+
name: {
|
|
1278
|
+
type: "string",
|
|
1279
|
+
required: true
|
|
1280
|
+
},
|
|
1281
|
+
description: {
|
|
1282
|
+
type: "string",
|
|
1283
|
+
required: false
|
|
1284
|
+
},
|
|
1285
|
+
amount: {
|
|
1286
|
+
type: "number",
|
|
1287
|
+
required: true
|
|
1288
|
+
},
|
|
1289
|
+
currency: {
|
|
1290
|
+
type: "string",
|
|
1291
|
+
required: true
|
|
1292
|
+
},
|
|
1293
|
+
interval: {
|
|
1294
|
+
type: "string",
|
|
1295
|
+
required: true
|
|
1296
|
+
},
|
|
1297
|
+
group: {
|
|
1298
|
+
type: "string",
|
|
1299
|
+
required: false
|
|
1300
|
+
},
|
|
1301
|
+
paymentPlanId: {
|
|
1302
|
+
type: "number",
|
|
1303
|
+
required: false,
|
|
1304
|
+
unique: true
|
|
1305
|
+
},
|
|
1306
|
+
metadata: {
|
|
1307
|
+
type: "string",
|
|
1308
|
+
required: false
|
|
1309
|
+
},
|
|
1310
|
+
reconciledAt: {
|
|
1311
|
+
type: "date",
|
|
1312
|
+
required: false
|
|
1313
|
+
},
|
|
1314
|
+
createdAt: {
|
|
1315
|
+
type: "date",
|
|
1316
|
+
required: true
|
|
1317
|
+
},
|
|
1318
|
+
updatedAt: {
|
|
1319
|
+
type: "date",
|
|
1320
|
+
required: true
|
|
1321
|
+
}
|
|
1322
|
+
} } };
|
|
1323
|
+
const webhookEvents = { flutterwaveWebhookEvent: { fields: {
|
|
1324
|
+
eventId: {
|
|
1325
|
+
type: "string",
|
|
1326
|
+
required: true,
|
|
1327
|
+
unique: true
|
|
1328
|
+
},
|
|
1329
|
+
eventType: {
|
|
1330
|
+
type: "string",
|
|
1331
|
+
required: true,
|
|
1332
|
+
index: true
|
|
1333
|
+
},
|
|
1334
|
+
transactionId: {
|
|
1335
|
+
type: "number",
|
|
1336
|
+
required: false,
|
|
1337
|
+
index: true
|
|
1338
|
+
},
|
|
1339
|
+
txRef: {
|
|
1340
|
+
type: "string",
|
|
1341
|
+
required: false,
|
|
1342
|
+
index: true
|
|
1343
|
+
},
|
|
1344
|
+
payload: {
|
|
1345
|
+
type: "string",
|
|
1346
|
+
required: true
|
|
1347
|
+
},
|
|
1348
|
+
status: {
|
|
1349
|
+
type: "string",
|
|
1350
|
+
required: true,
|
|
1351
|
+
defaultValue: "pending",
|
|
1352
|
+
index: true
|
|
1353
|
+
},
|
|
1354
|
+
processedAt: {
|
|
1355
|
+
type: "date",
|
|
1356
|
+
required: false
|
|
1357
|
+
},
|
|
1358
|
+
createdAt: {
|
|
1359
|
+
type: "date",
|
|
1360
|
+
required: true
|
|
1361
|
+
},
|
|
1362
|
+
updatedAt: {
|
|
1363
|
+
type: "date",
|
|
1364
|
+
required: true
|
|
1365
|
+
}
|
|
1366
|
+
} } };
|
|
1367
|
+
const refunds = { flutterwaveRefund: { fields: {
|
|
1368
|
+
refundId: {
|
|
1369
|
+
type: "number",
|
|
1370
|
+
required: false,
|
|
1371
|
+
unique: true
|
|
1372
|
+
},
|
|
1373
|
+
transactionId: {
|
|
1374
|
+
type: "number",
|
|
1375
|
+
required: true,
|
|
1376
|
+
index: true
|
|
1377
|
+
},
|
|
1378
|
+
txRef: {
|
|
1379
|
+
type: "string",
|
|
1380
|
+
required: true,
|
|
1381
|
+
index: true
|
|
1382
|
+
},
|
|
1383
|
+
referenceId: {
|
|
1384
|
+
type: "string",
|
|
1385
|
+
required: true,
|
|
1386
|
+
index: true
|
|
1387
|
+
},
|
|
1388
|
+
amount: {
|
|
1389
|
+
type: "number",
|
|
1390
|
+
required: true
|
|
1391
|
+
},
|
|
1392
|
+
currency: {
|
|
1393
|
+
type: "string",
|
|
1394
|
+
required: true
|
|
1395
|
+
},
|
|
1396
|
+
status: {
|
|
1397
|
+
type: "string",
|
|
1398
|
+
required: true,
|
|
1399
|
+
index: true
|
|
1400
|
+
},
|
|
1401
|
+
reason: {
|
|
1402
|
+
type: "string",
|
|
1403
|
+
required: false
|
|
1404
|
+
},
|
|
1405
|
+
metadata: {
|
|
1406
|
+
type: "string",
|
|
1407
|
+
required: false
|
|
1408
|
+
},
|
|
1409
|
+
reconciledAt: {
|
|
1410
|
+
type: "date",
|
|
1411
|
+
required: false
|
|
1412
|
+
},
|
|
1413
|
+
createdAt: {
|
|
1414
|
+
type: "date",
|
|
1415
|
+
required: true
|
|
1416
|
+
},
|
|
1417
|
+
updatedAt: {
|
|
1418
|
+
type: "date",
|
|
1419
|
+
required: true
|
|
1420
|
+
}
|
|
1421
|
+
} } };
|
|
1422
|
+
const flutterwavePluginSchema = {
|
|
1423
|
+
...transactions,
|
|
1424
|
+
...subscriptions,
|
|
1425
|
+
...products,
|
|
1426
|
+
...plans,
|
|
1427
|
+
...webhookEvents,
|
|
1428
|
+
...refunds
|
|
1429
|
+
};
|
|
1430
|
+
const getSchema = (options) => {
|
|
1431
|
+
const { flutterwaveSubscription: _subscription, ...withoutSubscriptions } = flutterwavePluginSchema;
|
|
1432
|
+
const baseSchema = options.subscription?.enabled === true ? flutterwavePluginSchema : withoutSubscriptions;
|
|
1433
|
+
const optionSchema = options.schema;
|
|
1434
|
+
if (options.schema !== void 0 && options.subscription?.enabled !== true && "flutterwaveSubscription" in options.schema) {
|
|
1435
|
+
const { flutterwaveSubscription: _customSubscription, ...restSchema } = optionSchema ?? {};
|
|
1436
|
+
return mergeSchema(baseSchema, restSchema);
|
|
1437
|
+
}
|
|
1438
|
+
return mergeSchema(baseSchema, optionSchema);
|
|
1439
|
+
};
|
|
1440
|
+
//#endregion
|
|
1441
|
+
//#region src/limits.ts
|
|
1442
|
+
const checkSeatLimit = async (ctx, organizationId, seatsToAdd = 1) => {
|
|
1443
|
+
const store = createBillingStore(ctx);
|
|
1444
|
+
const seatLimit = (await store.findSubscriptionsByReference(organizationId)).filter((subscription) => subscription.status === "active" || subscription.status === "trialing").reduce((maximum, subscription) => typeof subscription.seats === "number" ? Math.max(maximum ?? subscription.seats, subscription.seats) : maximum, void 0);
|
|
1445
|
+
const members = await store.listMembers(organizationId);
|
|
1446
|
+
if (seatLimit === void 0) return true;
|
|
1447
|
+
if (members.length + seatsToAdd > seatLimit) throw new APIError("FORBIDDEN", { message: `Organization member limit reached. Used: ${members.length}, Max: ${seatLimit}` });
|
|
1448
|
+
return true;
|
|
1449
|
+
};
|
|
1450
|
+
async function getOrganizationEntitlements(ctx, organizationId, options) {
|
|
1451
|
+
const subscriptions = (await createBillingStore(ctx).findSubscriptionsByReference(organizationId)).filter((subscription) => subscription.status === "active" || subscription.status === "trialing");
|
|
1452
|
+
const limits = {};
|
|
1453
|
+
const features = /* @__PURE__ */ new Set();
|
|
1454
|
+
for (const subscription of subscriptions) {
|
|
1455
|
+
const plan = await getPlanByName(options, subscription.plan);
|
|
1456
|
+
for (const [name, value] of Object.entries(plan?.limits ?? {})) if (typeof value === "number" && Number.isFinite(value)) limits[name] = Math.max(limits[name] ?? value, value);
|
|
1457
|
+
for (const feature of plan?.features ?? []) features.add(feature);
|
|
1458
|
+
}
|
|
1459
|
+
return {
|
|
1460
|
+
limits,
|
|
1461
|
+
features: [...features]
|
|
1462
|
+
};
|
|
1463
|
+
}
|
|
1464
|
+
const checkTeamLimit = async (ctx, organizationId, maxTeams) => {
|
|
1465
|
+
if ((await createBillingStore(ctx).listTeams(organizationId)).length >= maxTeams) throw new APIError("FORBIDDEN", { message: `Organization team limit reached. Max teams: ${maxTeams}` });
|
|
1466
|
+
return true;
|
|
1467
|
+
};
|
|
1468
|
+
//#endregion
|
|
1469
|
+
//#region src/operations.ts
|
|
1470
|
+
function adapter(options) {
|
|
1471
|
+
return createFlutterwaveAdapter({
|
|
1472
|
+
publicKey: options.publicKey,
|
|
1473
|
+
secretKey: options.secretKey,
|
|
1474
|
+
flutterwaveClient: options.flutterwaveClient,
|
|
1475
|
+
fetch: options.fetch,
|
|
1476
|
+
apiBaseUrl: options.apiBaseUrl
|
|
1477
|
+
});
|
|
1478
|
+
}
|
|
1479
|
+
async function syncFlutterwavePlans(ctx, options) {
|
|
1480
|
+
const remote = await adapter(options).listPaymentPlans();
|
|
1481
|
+
const store = createBillingStore(ctx);
|
|
1482
|
+
const now = /* @__PURE__ */ new Date();
|
|
1483
|
+
for (const plan of remote) await store.upsertPlanByPaymentPlanId(plan.id, {
|
|
1484
|
+
name: plan.name,
|
|
1485
|
+
amount: plan.amount,
|
|
1486
|
+
currency: plan.currency,
|
|
1487
|
+
interval: plan.interval,
|
|
1488
|
+
paymentPlanId: plan.id,
|
|
1489
|
+
reconciledAt: now,
|
|
1490
|
+
createdAt: now,
|
|
1491
|
+
updatedAt: now
|
|
1492
|
+
});
|
|
1493
|
+
return {
|
|
1494
|
+
status: "success",
|
|
1495
|
+
count: remote.length
|
|
1496
|
+
};
|
|
1497
|
+
}
|
|
1498
|
+
async function chargeSubscriptionRenewal(ctx, options, input) {
|
|
1499
|
+
const store = createBillingStore(ctx);
|
|
1500
|
+
const subscription = await store.findSubscriptionById(input.subscriptionId);
|
|
1501
|
+
if (!subscription) throw new APIError("NOT_FOUND", { message: "Subscription not found" });
|
|
1502
|
+
const plan = await store.findPlanByName(subscription.plan) ?? await (async () => {
|
|
1503
|
+
const configured = options.subscription?.plans;
|
|
1504
|
+
return (typeof configured === "function" ? await configured() : configured ?? []).find((candidate) => candidate.name === subscription.plan) ?? null;
|
|
1505
|
+
})();
|
|
1506
|
+
const amount = input.amount ?? plan?.amount;
|
|
1507
|
+
if (!amount || !plan?.currency || !subscription.billingEmail) throw new APIError("BAD_REQUEST", { message: "Subscription billing details are incomplete" });
|
|
1508
|
+
const txRef = `flw_renewal_${crypto.randomUUID()}`;
|
|
1509
|
+
const metadata = stringifyFlutterwaveMetadata(createRenewalMetadata({
|
|
1510
|
+
subscriptionId: subscription.id,
|
|
1511
|
+
referenceId: subscription.referenceId
|
|
1512
|
+
}));
|
|
1513
|
+
if (!subscription.encryptedPaymentToken) {
|
|
1514
|
+
if (!input.redirectUrl) throw new APIError("BAD_REQUEST", { message: "redirectUrl is required when the subscription has no reusable payment token" });
|
|
1515
|
+
const checkout = await adapter(options).initializePayment({
|
|
1516
|
+
tx_ref: txRef,
|
|
1517
|
+
amount,
|
|
1518
|
+
currency: plan.currency,
|
|
1519
|
+
redirect_url: input.redirectUrl,
|
|
1520
|
+
customer: { email: subscription.billingEmail },
|
|
1521
|
+
meta: parseMetadata(metadata)
|
|
1522
|
+
});
|
|
1523
|
+
const now = /* @__PURE__ */ new Date();
|
|
1524
|
+
await store.createTransaction({
|
|
1525
|
+
txRef,
|
|
1526
|
+
referenceId: subscription.referenceId,
|
|
1527
|
+
userId: subscription.userId,
|
|
1528
|
+
amount,
|
|
1529
|
+
currency: plan.currency,
|
|
1530
|
+
status: "pending",
|
|
1531
|
+
plan: subscription.plan,
|
|
1532
|
+
metadata,
|
|
1533
|
+
createdAt: now,
|
|
1534
|
+
updatedAt: now
|
|
1535
|
+
});
|
|
1536
|
+
await store.updateSubscription(subscription.id, {
|
|
1537
|
+
txRef,
|
|
1538
|
+
status: "past_due",
|
|
1539
|
+
updatedAt: now
|
|
1540
|
+
});
|
|
1541
|
+
return {
|
|
1542
|
+
status: "pending",
|
|
1543
|
+
data: {
|
|
1544
|
+
kind: "checkout",
|
|
1545
|
+
url: checkout.link,
|
|
1546
|
+
txRef,
|
|
1547
|
+
redirect: true
|
|
1548
|
+
}
|
|
1549
|
+
};
|
|
1550
|
+
}
|
|
1551
|
+
const token = await decryptPaymentToken(subscription.encryptedPaymentToken, ctx.context.secret);
|
|
1552
|
+
const charged = await adapter(options).chargeToken({
|
|
1553
|
+
token,
|
|
1554
|
+
amount,
|
|
1555
|
+
currency: plan.currency,
|
|
1556
|
+
email: subscription.billingEmail,
|
|
1557
|
+
tx_ref: txRef
|
|
1558
|
+
});
|
|
1559
|
+
const verified = await adapter(options).verifyTransaction({ transactionId: charged.id });
|
|
1560
|
+
if (verified.tx_ref !== txRef || verified.amount !== amount || verified.currency !== plan.currency) throw new APIError("BAD_REQUEST", { message: "Tokenized renewal did not match the expected payment" });
|
|
1561
|
+
const now = /* @__PURE__ */ new Date();
|
|
1562
|
+
await store.createTransaction({
|
|
1563
|
+
txRef,
|
|
1564
|
+
transactionId: verified.id,
|
|
1565
|
+
flwRef: verified.flw_ref,
|
|
1566
|
+
referenceId: subscription.referenceId,
|
|
1567
|
+
userId: subscription.userId,
|
|
1568
|
+
amount,
|
|
1569
|
+
chargedAmount: verified.charged_amount,
|
|
1570
|
+
currency: plan.currency,
|
|
1571
|
+
status: verified.status,
|
|
1572
|
+
plan: subscription.plan,
|
|
1573
|
+
paymentType: verified.payment_type,
|
|
1574
|
+
metadata,
|
|
1575
|
+
verifiedAt: now,
|
|
1576
|
+
reconciledAt: now,
|
|
1577
|
+
createdAt: now,
|
|
1578
|
+
updatedAt: now
|
|
1579
|
+
});
|
|
1580
|
+
await store.updateSubscription(subscription.id, {
|
|
1581
|
+
txRef,
|
|
1582
|
+
status: verified.status === "successful" ? "active" : "past_due",
|
|
1583
|
+
reconciledAt: now,
|
|
1584
|
+
updatedAt: now
|
|
1585
|
+
});
|
|
1586
|
+
return {
|
|
1587
|
+
status: verified.status === "successful" ? "success" : "failed",
|
|
1588
|
+
data: {
|
|
1589
|
+
id: verified.id,
|
|
1590
|
+
txRef: verified.tx_ref,
|
|
1591
|
+
flwRef: verified.flw_ref ?? void 0,
|
|
1592
|
+
amount: verified.amount,
|
|
1593
|
+
chargedAmount: verified.charged_amount,
|
|
1594
|
+
currency: verified.currency,
|
|
1595
|
+
status: verified.status,
|
|
1596
|
+
paymentType: verified.payment_type ?? void 0
|
|
1597
|
+
}
|
|
1598
|
+
};
|
|
1599
|
+
}
|
|
1600
|
+
function parseMetadata(value) {
|
|
1601
|
+
if (!value) return void 0;
|
|
1602
|
+
return JSON.parse(value);
|
|
1603
|
+
}
|
|
1604
|
+
async function refundFlutterwaveTransaction(ctx, options, input) {
|
|
1605
|
+
const store = createBillingStore(ctx);
|
|
1606
|
+
const transaction = await store.findTransactionById(input.transactionId);
|
|
1607
|
+
if (!transaction) throw new APIError("NOT_FOUND", { message: "Transaction not found" });
|
|
1608
|
+
const result = await adapter(options).refundTransaction(input.transactionId, input.amount);
|
|
1609
|
+
const now = /* @__PURE__ */ new Date();
|
|
1610
|
+
return store.createRefund({
|
|
1611
|
+
refundId: result.id,
|
|
1612
|
+
transactionId: input.transactionId,
|
|
1613
|
+
txRef: transaction.txRef,
|
|
1614
|
+
referenceId: transaction.referenceId,
|
|
1615
|
+
amount: result.amount_refunded ?? result.amount ?? input.amount ?? transaction.amount,
|
|
1616
|
+
currency: transaction.currency,
|
|
1617
|
+
status: result.status,
|
|
1618
|
+
reason: input.reason,
|
|
1619
|
+
createdAt: now,
|
|
1620
|
+
updatedAt: now
|
|
1621
|
+
});
|
|
1622
|
+
}
|
|
1623
|
+
//#endregion
|
|
1624
|
+
//#region src/reconciliation.ts
|
|
1625
|
+
async function reconcileFlutterwaveTransaction(ctx, options, input) {
|
|
1626
|
+
const store = createBillingStore(ctx);
|
|
1627
|
+
const local = input.txRef ? await store.findTransactionByTxRef(input.txRef) : input.transactionId ? await store.findTransactionById(input.transactionId) : null;
|
|
1628
|
+
if (!local) throw new APIError("NOT_FOUND", { message: "Transaction not found" });
|
|
1629
|
+
const verified = await createFlutterwaveAdapter({
|
|
1630
|
+
publicKey: options.publicKey,
|
|
1631
|
+
secretKey: options.secretKey,
|
|
1632
|
+
flutterwaveClient: options.flutterwaveClient,
|
|
1633
|
+
fetch: options.fetch,
|
|
1634
|
+
apiBaseUrl: options.apiBaseUrl
|
|
1635
|
+
}).verifyTransaction({
|
|
1636
|
+
txRef: input.txRef,
|
|
1637
|
+
transactionId: input.transactionId
|
|
1638
|
+
});
|
|
1639
|
+
if (!(verified.tx_ref === local.txRef && verified.amount === local.amount && verified.currency === local.currency)) {
|
|
1640
|
+
if (input.throwOnError === false) return {
|
|
1641
|
+
ok: false,
|
|
1642
|
+
source: input.source ?? "server",
|
|
1643
|
+
txRef: local.txRef,
|
|
1644
|
+
error: {
|
|
1645
|
+
code: "TRANSACTION_MISMATCH",
|
|
1646
|
+
message: "Transaction details do not match"
|
|
1647
|
+
}
|
|
1648
|
+
};
|
|
1649
|
+
throw new APIError("BAD_REQUEST", { message: "Transaction details do not match" });
|
|
1650
|
+
}
|
|
1651
|
+
const now = /* @__PURE__ */ new Date();
|
|
1652
|
+
await store.updateTransactionByTxRef(local.txRef, {
|
|
1653
|
+
transactionId: verified.id,
|
|
1654
|
+
flwRef: verified.flw_ref,
|
|
1655
|
+
chargedAmount: verified.charged_amount,
|
|
1656
|
+
paymentType: verified.payment_type,
|
|
1657
|
+
status: verified.status,
|
|
1658
|
+
verifiedAt: now,
|
|
1659
|
+
reconciledAt: now,
|
|
1660
|
+
updatedAt: now
|
|
1661
|
+
});
|
|
1662
|
+
for (const subscription of await store.findSubscriptionsByTxRef(local.txRef)) await store.updateSubscription(subscription.id, {
|
|
1663
|
+
status: verified.status === "successful" ? "active" : subscription.status,
|
|
1664
|
+
reconciledAt: now,
|
|
1665
|
+
updatedAt: now
|
|
1666
|
+
});
|
|
1667
|
+
const data = {
|
|
1668
|
+
id: verified.id,
|
|
1669
|
+
txRef: verified.tx_ref,
|
|
1670
|
+
flwRef: verified.flw_ref ?? void 0,
|
|
1671
|
+
amount: verified.amount,
|
|
1672
|
+
chargedAmount: verified.charged_amount,
|
|
1673
|
+
currency: verified.currency,
|
|
1674
|
+
status: verified.status,
|
|
1675
|
+
paymentType: verified.payment_type ?? void 0
|
|
1676
|
+
};
|
|
1677
|
+
return {
|
|
1678
|
+
ok: true,
|
|
1679
|
+
source: input.source ?? "server",
|
|
1680
|
+
txRef: local.txRef,
|
|
1681
|
+
status: verified.status,
|
|
1682
|
+
data
|
|
1683
|
+
};
|
|
1684
|
+
}
|
|
1685
|
+
const refundEnvelopeSchema = z.object({
|
|
1686
|
+
status: z.string(),
|
|
1687
|
+
data: z.object({
|
|
1688
|
+
id: z.coerce.number().optional(),
|
|
1689
|
+
status: z.string(),
|
|
1690
|
+
amount_refunded: z.coerce.number().optional()
|
|
1691
|
+
})
|
|
1692
|
+
});
|
|
1693
|
+
async function reconcileFlutterwaveRefunds(ctx, options) {
|
|
1694
|
+
const store = createBillingStore(ctx);
|
|
1695
|
+
const pending = await store.listPendingRefunds();
|
|
1696
|
+
const fetchImpl = options.fetch ?? globalThis.fetch;
|
|
1697
|
+
const baseUrl = (options.apiBaseUrl ?? "https://api.flutterwave.com").replace(/\/+$/, "");
|
|
1698
|
+
let updated = 0;
|
|
1699
|
+
for (const refund of pending) {
|
|
1700
|
+
if (!refund.refundId) continue;
|
|
1701
|
+
const response = await fetchImpl(`${baseUrl}/v3/refunds/${refund.refundId}`, { headers: { authorization: `Bearer ${options.secretKey}` } });
|
|
1702
|
+
if (!response.ok) continue;
|
|
1703
|
+
const parsed = refundEnvelopeSchema.safeParse(await response.json());
|
|
1704
|
+
if (!parsed.success) continue;
|
|
1705
|
+
await store.updateRefund(refund.id, {
|
|
1706
|
+
status: parsed.data.data.status,
|
|
1707
|
+
amount: parsed.data.data.amount_refunded ?? refund.amount,
|
|
1708
|
+
reconciledAt: /* @__PURE__ */ new Date(),
|
|
1709
|
+
updatedAt: /* @__PURE__ */ new Date()
|
|
1710
|
+
});
|
|
1711
|
+
updated++;
|
|
1712
|
+
}
|
|
1713
|
+
return {
|
|
1714
|
+
status: "success",
|
|
1715
|
+
count: updated
|
|
1716
|
+
};
|
|
1717
|
+
}
|
|
1718
|
+
//#endregion
|
|
1719
|
+
//#region src/index.ts
|
|
1720
|
+
const INTERNAL_ERROR_CODES = defineErrorCodes(Object.fromEntries(Object.entries(FLUTTERWAVE_ERROR_CODES).map(([key, value]) => [key, typeof value === "string" ? value : value.message])));
|
|
1721
|
+
const flutterwave = (options) => {
|
|
1722
|
+
const routeOptions = options;
|
|
1723
|
+
return {
|
|
1724
|
+
id: "flutterwave",
|
|
1725
|
+
version: PACKAGE_VERSION,
|
|
1726
|
+
endpoints: {
|
|
1727
|
+
initializeFlutterwaveTransaction: initializeTransaction(routeOptions, "/flutterwave/transaction/initialize"),
|
|
1728
|
+
verifyFlutterwaveTransaction: verifyTransaction(routeOptions, "/flutterwave/transaction/verify"),
|
|
1729
|
+
listFlutterwaveTransactions: listTransactions(routeOptions, "/flutterwave/transaction/list"),
|
|
1730
|
+
listFlutterwaveSubscriptions: listSubscriptions(routeOptions, "/flutterwave/subscription/list"),
|
|
1731
|
+
createFlutterwaveSubscription: createSubscription(routeOptions, "/flutterwave/subscription/create"),
|
|
1732
|
+
upgradeFlutterwaveSubscription: upgradeSubscription(routeOptions, "/flutterwave/subscription/upgrade"),
|
|
1733
|
+
cancelFlutterwaveSubscription: cancelSubscription(routeOptions, "/flutterwave/subscription/cancel"),
|
|
1734
|
+
restoreFlutterwaveSubscription: restoreSubscription(routeOptions, "/flutterwave/subscription/restore"),
|
|
1735
|
+
listFlutterwaveProducts: listProducts(routeOptions, "/flutterwave/product/list"),
|
|
1736
|
+
listFlutterwavePlans: listPlans(routeOptions, "/flutterwave/plan/list"),
|
|
1737
|
+
getFlutterwaveConfig: getConfig(routeOptions, "/flutterwave/config"),
|
|
1738
|
+
flutterwaveWebhook: flutterwaveWebhook(routeOptions, "/flutterwave/webhook")
|
|
1739
|
+
},
|
|
1740
|
+
schema: getSchema(routeOptions),
|
|
1741
|
+
init: (ctx) => {
|
|
1742
|
+
if (options.organization?.enabled === true && !ctx.hasPlugin("organization")) ctx.logger.error("Flutterwave organization billing requires the Better Auth organization plugin.");
|
|
1743
|
+
return { options: {} };
|
|
1744
|
+
},
|
|
1745
|
+
$ERROR_CODES: INTERNAL_ERROR_CODES,
|
|
1746
|
+
options
|
|
1747
|
+
};
|
|
1748
|
+
};
|
|
1749
|
+
//#endregion
|
|
1750
|
+
export { FlutterwaveAdapterError, chargeSubscriptionRenewal, checkSeatLimit, checkTeamLimit, createCheckoutMetadata, createFlutterwaveAdapter, createProrationMetadata, createRenewalMetadata, decryptPaymentToken, encryptPaymentToken, flutterwave, getMetadataBoolean, getMetadataNumber, getMetadataString, getOrganizationEntitlements, hasFlutterwaveMetadata, parseFlutterwaveMetadata, reconcileFlutterwaveRefunds, reconcileFlutterwaveTransaction, refundFlutterwaveTransaction, stringifyFlutterwaveMetadata, syncFlutterwavePlans };
|
|
1751
|
+
|
|
1752
|
+
//# sourceMappingURL=index.mjs.map
|