From b796e625df35cb870c437ec6ae766054f4119f3f Mon Sep 17 00:00:00 2001 From: Luis Alvarez Date: Wed, 14 Oct 2020 17:53:50 -0500 Subject: [PATCH] Embedded checkout --- lib/bigcommerce/api/catalog/products.ts | 7 +-- lib/bigcommerce/api/checkout.ts | 69 +++++++++++++++++++++++++ pages/api/bigcommerce/checkout.ts | 3 ++ 3 files changed, 74 insertions(+), 5 deletions(-) create mode 100644 lib/bigcommerce/api/checkout.ts create mode 100644 pages/api/bigcommerce/checkout.ts diff --git a/lib/bigcommerce/api/catalog/products.ts b/lib/bigcommerce/api/catalog/products.ts index 6732066a4..591dff029 100644 --- a/lib/bigcommerce/api/catalog/products.ts +++ b/lib/bigcommerce/api/catalog/products.ts @@ -29,11 +29,8 @@ const cartApi: BigcommerceApiHandler< if (!isAllowedMethod(req, res, METHODS)) return try { - // Return current cart info - if (req.method === 'GET') { - const body = req.query - return await handlers['getProducts']({ req, res, config, body }) - } + const body = req.query + return await handlers['getProducts']({ req, res, config, body }) } catch (error) { console.error(error) diff --git a/lib/bigcommerce/api/checkout.ts b/lib/bigcommerce/api/checkout.ts new file mode 100644 index 000000000..79405434f --- /dev/null +++ b/lib/bigcommerce/api/checkout.ts @@ -0,0 +1,69 @@ +import isAllowedMethod from './utils/is-allowed-method' +import createApiHandler, { + BigcommerceApiHandler, +} from './utils/create-api-handler' +import { BigcommerceApiError } from './utils/errors' + +const METHODS = ['GET'] + +// 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', + } + ) + 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, {}) diff --git a/pages/api/bigcommerce/checkout.ts b/pages/api/bigcommerce/checkout.ts new file mode 100644 index 000000000..0f6456c73 --- /dev/null +++ b/pages/api/bigcommerce/checkout.ts @@ -0,0 +1,3 @@ +import checkoutApi from '@lib/bigcommerce/api/checkout' + +export default checkoutApi()