Skip to content

Instantly share code, notes, and snippets.

@gje4
Created April 30, 2024 15:28
Show Gist options
  • Save gje4/33e3bdc3d2f50256c61709d1784c75b9 to your computer and use it in GitHub Desktop.
Save gje4/33e3bdc3d2f50256c61709d1784c75b9 to your computer and use it in GitHub Desktop.
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