mirror of
https://github.com/vercel/commerce.git
synced 2025-05-18 07:26:59 +00:00
35 lines
1.0 KiB
TypeScript
35 lines
1.0 KiB
TypeScript
import type { CheckoutEndpoint } from '.'
|
|
import getCredentials from '@framework/api/utils/getCredentials'
|
|
import { Order } from '@commercelayer/js-sdk'
|
|
|
|
const checkout: CheckoutEndpoint['handlers']['checkout'] = async ({
|
|
req,
|
|
res,
|
|
}) => {
|
|
let { orderId, accessToken } = req.query
|
|
|
|
const name = 'CL_TOKEN' + "=";
|
|
const cookiesArr = decodeURIComponent(accessToken = typeof accessToken === 'string' ? accessToken : '').split('; ');
|
|
cookiesArr.forEach(val => {
|
|
if (val.indexOf(name) === 0) accessToken = val.substring(name.length)
|
|
})
|
|
|
|
const { endpoint } = getCredentials()
|
|
if (orderId && accessToken) {
|
|
const clOrder = await Order.withCredentials({ endpoint, accessToken })
|
|
.includes('lineItems')
|
|
.find(orderId as string, { rawResponse: true })
|
|
const checkoutUrl = clOrder.data.attributes.checkout_url
|
|
|
|
if (checkoutUrl) {
|
|
res.redirect(`${checkoutUrl}?accessToken=${accessToken}`)
|
|
} else {
|
|
res.redirect('/cart')
|
|
}
|
|
} else {
|
|
res.redirect('/')
|
|
}
|
|
}
|
|
|
|
export default checkout
|