From 841e02c14234430e70a967e042ed23a5f00ca04e Mon Sep 17 00:00:00 2001 From: Joe Carstairs <65492573+Sycamost@users.noreply.github.com> Date: Sat, 12 Aug 2023 12:27:17 +0100 Subject: Parses PayPal create order response with approval link --- api/order.ts | 26 +++++++++++++++++++++++++- 1 file changed, 25 insertions(+), 1 deletion(-) (limited to 'api') diff --git a/api/order.ts b/api/order.ts index 242f7c3..f90314e 100644 --- a/api/order.ts +++ b/api/order.ts @@ -26,8 +26,32 @@ async function handlePost(request: VercelRequest, response: VercelResponse) { } else { try { const paypalResponse = await paypalCreateOrder({ productDescription, shortDescription, totalPrice }); + + const { id, links } = paypalResponse; + const isApprovalLink = (o: object) => ( + 'rel' in o && + o.rel === 'approve' && + 'href' in o && + typeof(o.href) === 'string' && + o.href.length > 0 + ); + + if (!id || typeof(id) !== 'string' || id.length === 0) { + throw new Error(` + PayPal did not return the created order ID + in an expected format. PayPal returned: ${paypalResponse} + `); + } + if (!links || !('length' in links) || !links.some(isApprovalLink)) { + throw new Error(` + PayPal did not return the order approval link in + an expected format. PayPal returned: ${paypalResponse} + `); + } + response.status(201).json({ - orderId: paypalResponse.id, + orderId: id, + approvalLink: links.find(isApprovalLink).href, }); } catch (err) { response.status(500).send(`Internal server error. ${err}`); -- cgit v1.2.3