import isAllowedMethod from './utils/is-allowed-method' import createApiHandler, { BigcommerceApiHandler, } from './utils/create-api-handler' import { BigcommerceApiError } from './utils/errors' const METHODS = ['GET'] const fullCheckout = true // TODO: a complete implementation should have schema validation for `req.body` const checkoutApi: BigcommerceApiHandler = async (req, res, config) => { if (!isAllowedMethod(req, res, METHODS)) return const { cookies } = req const cartId = cookies[config.cartCookie] try { if (!cartId) { return res.status(404).end() } const { data } = await config.storeApiFetch( `/v3/carts/${cartId}/redirect_urls`, { method: 'POST', } ) if (fullCheckout) { res.redirect(data.checkout_url) return } // TODO: make the embedded checkout work too! const html = ` Checkout
` res.status(200) res.setHeader('Content-Type', 'text/html') res.write(html) res.end() } catch (error) { console.error(error) const message = error instanceof BigcommerceApiError ? 'An unexpected error ocurred with the Bigcommerce API' : 'An unexpected error ocurred' res.status(500).json({ data: null, errors: [{ message }] }) } } export default createApiHandler(checkoutApi, {}, {})