Created
April 30, 2024 15:28
-
-
Save gje4/33e3bdc3d2f50256c61709d1784c75b9 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import type { CheckoutEndpoint } from '.' | |
import getCustomerId from '../../utils/get-customer-id' | |
import jwt from 'jsonwebtoken' | |
import { uuid } from 'uuidv4' | |
import { getShopTokenFromRequest } from '@lib/auth/utils' | |
const fullCheckout = true | |
const checkout: CheckoutEndpoint['handlers']['checkout'] = async ({ req, res, config }) => { | |
const { cookies } = req | |
const cartId = cookies[config.cartCookie] | |
// YES! | |
const customerToken = await getShopTokenFromRequest(req) | |
if (!cartId) { | |
res.redirect('/cart') | |
return | |
} | |
const { data } = await config.storeApiFetch(`/v3/carts/${cartId}/redirect_urls`, { | |
method: 'POST', | |
}) | |
const customerId = customerToken && (await getCustomerId({ customerToken, config })) | |
//if there is a customer create a jwt token | |
if (!customerId) { | |
if (fullCheckout) { | |
res.redirect(data.checkout_url) | |
return | |
} | |
} else { | |
const dateCreated = Math.round(new Date().getTime() / 1000) | |
const payload = { | |
iss: config.storeApiClientId, | |
iat: dateCreated, | |
jti: uuid(), | |
operation: 'customer_login', | |
store_hash: config.storeHash, | |
customer_id: customerId, | |
channel_id: config.storeChannelId, | |
redirect_to: data.checkout_url, | |
} | |
let token = jwt.sign(payload, config.storeApiClientSecret!, { | |
algorithm: 'HS256', | |
}) | |
let checkouturl = `${config.storeUrl}/login/token/${token}` | |
if (fullCheckout) { | |
res.redirect(checkouturl) | |
return | |
} | |
} | |
} | |
export default checkout |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment