(req: NextApiRequest, res: NextApiResponse)
| 12 | const prisma = new PrismaClient(); |
| 13 | |
| 14 | export default async function handler(req: NextApiRequest, res: NextApiResponse) { |
| 15 | const session = await getServerSession(req, res, authOptions); |
| 16 | |
| 17 | if (!session?.user?.email) { |
| 18 | res.status(401).json({ statusCode: 401, message: "Unauthorized" }); |
| 19 | return; |
| 20 | } |
| 21 | |
| 22 | if (req.method === "POST") { |
| 23 | const email = session?.user?.email!; |
| 24 | const user = await prisma.user.findUniqueOrThrow({ |
| 25 | where: { email: email }, |
| 26 | }); |
| 27 | try { |
| 28 | // Create Checkout Sessions from body params. |
| 29 | const params: Stripe.Checkout.SessionCreateParams = { |
| 30 | submit_type: "pay", |
| 31 | mode: "payment", |
| 32 | payment_method_types: ["affirm", "alipay", "card", "cashapp", "klarna", "link", "wechat_pay"], |
| 33 | line_items: [ |
| 34 | { |
| 35 | price: req.body.price, |
| 36 | quantity: 1, |
| 37 | }, |
| 38 | ], |
| 39 | payment_method_options: { |
| 40 | wechat_pay: { |
| 41 | client: "web", |
| 42 | }, |
| 43 | }, |
| 44 | payment_intent_data: { |
| 45 | // not compatiable with affirm, alipay, klarna, wechat_pay |
| 46 | // setup_future_usage: "off_session", |
| 47 | metadata: { |
| 48 | email: session?.user?.email!, |
| 49 | plan: "PRO", |
| 50 | price: req.body.price, |
| 51 | }, |
| 52 | }, |
| 53 | // Link customer if present otherwise pass email and let Stripe create a new customer. |
| 54 | // customer and customer_email can't be set at the same time. |
| 55 | customer: user.stripeId || undefined, |
| 56 | customer_email: user.stripeId ? undefined : email, |
| 57 | customer_creation: user.stripeId ? undefined : "always", |
| 58 | success_url: `${req.headers.origin}/setting?session_id={CHECKOUT_SESSION_ID}`, |
| 59 | cancel_url: `${req.headers.origin}/setting`, |
| 60 | }; |
| 61 | const checkoutSession: Stripe.Checkout.Session = await stripe.checkout.sessions.create(params); |
| 62 | |
| 63 | res.status(200).json(checkoutSession); |
| 64 | } catch (err) { |
| 65 | const errorMessage = err instanceof Error ? err.message : "Internal server error"; |
| 66 | res.status(500).json({ statusCode: 500, message: errorMessage }); |
| 67 | } |
| 68 | } else { |
| 69 | res.setHeader("Allow", "POST"); |
| 70 | res.status(405).end("Method Not Allowed"); |
| 71 | } |
nothing calls this directly
no outgoing calls
no test coverage detected