forked from vercel/next.js
/
cart.ts
52 lines (48 loc) · 1.82 KB
/
cart.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
import { NextApiRequest, NextApiResponse } from 'next'
/*
* Product data can be loaded from anywhere. In this case, we’re loading it from
* a local JSON file, but this could also come from an async call to your
* inventory management service, a database query, or some other API call.
*
* The important thing is that the product info is loaded from somewhere trusted
* so you know the pricing information is accurate.
*/
import { validateCartItems } from 'use-shopping-cart/src/serverUtil'
import inventory from '../../../data/products.json'
import Stripe from 'stripe'
const stripe = new Stripe(process.env.STRIPE_SECRET_KEY!, {
// https://github.com/stripe/stripe-node#configuration
apiVersion: '2020-03-02',
})
export default async function handler(
req: NextApiRequest,
res: NextApiResponse
) {
if (req.method === 'POST') {
try {
// Validate the cart details that were sent from the client.
const cartItems = req.body
const line_items = validateCartItems(inventory, cartItems)
// Create Checkout Sessions from body params.
const params: Stripe.Checkout.SessionCreateParams = {
submit_type: 'pay',
payment_method_types: ['card'],
billing_address_collection: 'auto',
shipping_address_collection: {
allowed_countries: ['US', 'CA'],
},
line_items,
success_url: `${req.headers.origin}/result?session_id={CHECKOUT_SESSION_ID}`,
cancel_url: `${req.headers.origin}/use-shopping-cart`,
}
const checkoutSession: Stripe.Checkout.Session =
await stripe.checkout.sessions.create(params)
res.status(200).json(checkoutSession)
} catch (err) {
res.status(500).json({ statusCode: 500, message: err.message })
}
} else {
res.setHeader('Allow', 'POST')
res.status(405).end('Method Not Allowed')
}
}