Files
firecrawl/apps/api/src/services/billing/stripe.ts
T

60 lines
2.0 KiB
TypeScript
Raw Normal View History

2024-11-07 20:57:33 +01:00
import { logger } from "../../lib/logger";
2024-10-22 19:47:23 -03:00
import Stripe from "stripe";
const stripe = new Stripe(process.env.STRIPE_SECRET_KEY ?? "");
async function getCustomerDefaultPaymentMethod(customerId: string) {
const paymentMethods = await stripe.customers.listPaymentMethods(customerId, {
2024-12-11 19:46:11 -03:00
limit: 3
2024-10-22 19:47:23 -03:00
});
return paymentMethods.data[0] ?? null;
2024-10-22 19:47:23 -03:00
}
type ReturnStatus = "succeeded" | "requires_action" | "failed";
export async function createPaymentIntent(
team_id: string,
customer_id: string
): Promise<{ return_status: ReturnStatus; charge_id: string }> {
try {
2024-12-11 19:46:11 -03:00
const defaultPaymentMethod =
await getCustomerDefaultPaymentMethod(customer_id);
if (!defaultPaymentMethod) {
2024-12-11 19:46:11 -03:00
logger.error(
`No default payment method found for customer: ${customer_id}`
);
return { return_status: "failed", charge_id: "" };
}
2024-10-22 19:47:23 -03:00
const paymentIntent = await stripe.paymentIntents.create({
amount: 1100,
currency: "usd",
customer: customer_id,
description: "Firecrawl: Auto re-charge of 1000 credits",
payment_method_types: [defaultPaymentMethod?.type ?? "card"],
payment_method: defaultPaymentMethod?.id,
2024-10-22 19:47:23 -03:00
off_session: true,
2024-12-11 19:46:11 -03:00
confirm: true
2024-10-22 19:47:23 -03:00
});
if (paymentIntent.status === "succeeded") {
2024-11-07 20:57:33 +01:00
logger.info(`Payment succeeded for team: ${team_id}`);
2024-10-22 19:47:23 -03:00
return { return_status: "succeeded", charge_id: paymentIntent.id };
} else if (
paymentIntent.status === "requires_action" ||
paymentIntent.status === "processing" ||
paymentIntent.status === "requires_capture"
) {
2024-11-07 20:57:33 +01:00
logger.warn(`Payment requires further action for team: ${team_id}`);
2024-10-22 19:47:23 -03:00
return { return_status: "requires_action", charge_id: paymentIntent.id };
} else {
2024-11-07 20:57:33 +01:00
logger.error(`Payment failed for team: ${team_id}`);
2024-10-22 19:47:23 -03:00
return { return_status: "failed", charge_id: paymentIntent.id };
}
} catch (error) {
2024-11-07 20:57:33 +01:00
logger.error(
2024-10-22 19:47:23 -03:00
`Failed to create or confirm PaymentIntent for team: ${team_id}`
);
console.error(error);
return { return_status: "failed", charge_id: "" };
}
}