diff options
| author | Joe Carstairs <65492573+Sycamost@users.noreply.github.com> | 2023-08-12 12:27:17 +0100 |
|---|---|---|
| committer | Joe Carstairs <65492573+Sycamost@users.noreply.github.com> | 2023-08-12 12:27:17 +0100 |
| commit | 841e02c14234430e70a967e042ed23a5f00ca04e (patch) | |
| tree | 04963b5ba0bcd52230a75f59d6c3353587359141 /api/order.ts | |
| parent | f213dbaf806f6b614770efab5d1aa21d621cdcef (diff) | |
Parses PayPal create order response with approval link
Diffstat (limited to 'api/order.ts')
| -rw-r--r-- | api/order.ts | 26 |
1 files changed, 25 insertions, 1 deletions
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}`); |
