Uber_Clone/app/api/(stripe)/create+api.ts

44 lines
1.3 KiB
TypeScript
Raw Permalink Normal View History

2025-04-09 09:31:23 +00:00
import {Stripe} from "stripe";
2025-04-14 05:26:03 +00:00
const stripe = new Stripe(process.env.STRIPE_SECRET_KEY!);
2025-04-09 09:31:23 +00:00
export async function POST(request:Request) {
const body = await request.json();
const { name, email, amount} = body;
if(!name || !email || !amount){
return new Response (JSON.stringify({error:"please enter a valid email Address",status:400}))
}
let customer;
const existingCustomer = await stripe.customers.list({email});
if(existingCustomer.data.length > 0){
customer = existingCustomer.data[0];
}else{
const newCustomer = await stripe.customers.create({
name,
email,
});
customer = newCustomer;
}
const ephemeralKey = await stripe.ephemeralKeys.create(
{customer: customer.id},
2025-04-14 05:26:03 +00:00
{apiVersion: "2023-03-16"}
2025-04-09 09:31:23 +00:00
);
const paymentIntent = await stripe.paymentIntents.create({
amount: parseInt(amount) * 100,
2025-04-14 05:26:03 +00:00
currency: "usd",
2025-04-09 09:31:23 +00:00
customer: customer.id,
automatic_payment_methods: {
enabled: true,
allow_redirects:"never",
},
});
return new Response(JSON.stringify({
2025-04-14 05:26:03 +00:00
paymentIntent: { id:paymentIntent.id,
client_secret:paymentIntent.client_secret},
2025-04-09 09:31:23 +00:00
ephemeralKey: ephemeralKey.secret,
customer: customer.id,
}),
);
}