const stripe = require('stripe')(process.env.STRIPE_API_SECRET_TEST) const validateCartItems = require('use-shopping-cart/utilities').validateCartItems const pricing = require("../../data/pricing.json"); export default async function handler(req, res) { const { query: { cart }, method, } = req; let cartItems; try { cartItems = req.body; } catch (error) { console.log(error); res.status(400).json({ message: "Invalid cart data provided in request body.", error: error.message }); return; } const getPrice = (productCode) => { return pricing[productCode]; } let inventory = []; for (const index in cartItems) { const cartItem = cartItems[index]; inventory.push(cartItem); } let line_items; try { line_items = validateCartItems(inventory, cartItems); } catch (error) { res.status(422).json({ message: "Some of the items in your cart are invalid.", error: error.message }); return; } let session; try { session = await stripe.checkout.sessions.create({ payment_method_types: ["card"], billing_address_collection: "auto", shipping_address_collection: { allowed_countries: ["US", "CA", "GB"] }, mode: "payment", success_url: `${process.env.NEXT_PUBLIC_URL}?success=true`, cancel_url: `${process.env.NEXT_PUBLIC_URL}?cancel=true`, line_items }); } catch (error) { res.status(500).json({ message: "Error encountered while communicating with Stripe.", error: error.message }); return; } console.log("Session id: ", session.id); res.status(200).json({ sessionId: session.id }); }