Created
July 12, 2023 00:48
-
-
Save dayhaysoos/2c1efc6c797073cd7dabfea0d5e8add9 to your computer and use it in GitHub Desktop.
yeet
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import Stripe from 'stripe'; | |
import { | |
validateCartItems, | |
formatLineItems, | |
} from 'use-shopping-cart/utilities'; | |
import inventory from './data/products.json'; | |
const stripe = new Stripe(process.env.STRIPE_SECRET_KEY, { | |
apiVersion: '2020-08-27', | |
typescript: false, | |
}); | |
export default async function handler(req, res) { | |
if (req.method.toUpperCase() !== 'POST') { | |
return { | |
statusCode: 405, | |
headers: { | |
Allow: 'POST', | |
}, | |
}; | |
} | |
if (req.headers['content-type'] !== 'application/json') { | |
return res.status(415).json({ | |
headers: { | |
Accept: 'application/json', | |
}, | |
}); | |
} | |
let cartDetails; | |
try { | |
cartDetails = JSON.parse(JSON.stringify(req.body)); | |
} catch (error) { | |
return res.status(400).json({ | |
message: 'Received malformed JSON.', | |
error: error.message, | |
}); | |
} | |
let line_items; | |
try { | |
line_items = formatLineItems(cartDetails); | |
} catch (error) { | |
return res.status(422).json({ | |
message: 'Some of the items in your cart are invalid.', | |
error: error.message, | |
}); | |
} | |
let session; | |
try { | |
session = await stripe.checkout.sessions.create({ | |
payment_method_types: ['card'], | |
billing_address_collection: 'auto', | |
shipping_address_collection: { | |
allowed_countries: ['DE', 'AT'], | |
}, | |
mode: 'payment', | |
success_url: `${process.env.URL}/success.html`, | |
cancel_url: process.env.URL, | |
line_items, | |
}); | |
} catch (error) { | |
return res.status(500).json({ | |
message: 'While communicating with Stripe, we encountered an error.', | |
error: error.message, | |
}); | |
} | |
return res.status(200).json({ body: session.id }); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment