forked from SecureBananaLabs/bug-bounty
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathpaymentService.js
More file actions
58 lines (48 loc) · 1.41 KB
/
Copy pathpaymentService.js
File metadata and controls
58 lines (48 loc) · 1.41 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
import Stripe from "stripe";
let stripeClient;
function getStripeClient() {
if (!process.env.STRIPE_SECRET_KEY) {
throw new Error("STRIPE_SECRET_KEY is required to create payment intents");
}
stripeClient ??= new Stripe(process.env.STRIPE_SECRET_KEY);
return stripeClient;
}
function validatePaymentPayload(payload = {}) {
if (!Number.isInteger(payload.amount) || payload.amount <= 0) {
throw new Error("amount must be a positive integer in the smallest currency unit");
}
const currency = payload.currency ?? "usd";
if (typeof currency !== "string" || currency.trim() === "") {
throw new Error("currency must be a non-empty string");
}
return {
amount: payload.amount,
currency: currency.toLowerCase(),
metadata: payload.metadata
};
}
export async function createPaymentIntent(payload) {
const { amount, currency, metadata } = validatePaymentPayload(payload);
try {
const paymentIntent = await getStripeClient().paymentIntents.create({
amount,
currency,
...(metadata ? { metadata } : {})
});
return {
paymentId: paymentIntent.id,
clientSecret: paymentIntent.client_secret,
amount,
currency,
provider: "stripe"
};
} catch (error) {
if (error?.type?.startsWith("Stripe")) {
throw new Error(error.message);
}
throw error;
}
}
export function __setStripeClientForTest(client) {
stripeClient = client;
}