forked from vercel/next.js
/
cart.ts
59 lines (54 loc) · 2.08 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
53
54
55
56
57
58
59
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/utilities/serverless'
import inventory from '../../../data/products'
import Stripe from 'stripe'
const stripe = new Stripe(process.env.STRIPE_SECRET_KEY!, {
// https://github.com/stripe/stripe-node#configuration
apiVersion: '2020-08-27',
})
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 line_items = validateCartItems(inventory as any, req.body)
const hasSubscription = line_items.find((item) => {
return !!item.price_data.recurring
})
// 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`,
mode: hasSubscription ? 'subscription' : 'payment',
}
const checkoutSession: Stripe.Checkout.Session =
await stripe.checkout.sessions.create(params)
res.status(200).json(checkoutSession)
} catch (err) {
console.log(err)
const errorMessage =
err instanceof Error ? err.message : 'Internal server error'
res.status(500).json({ statusCode: 500, message: errorMessage })
}
} else {
res.setHeader('Allow', 'POST')
res.status(405).end('Method Not Allowed')
}
}