Last active
June 21, 2021 12:13
-
-
Save pveen2/3e7bdb62e71102abd316bb2fcbe28251 to your computer and use it in GitHub Desktop.
shopify-direct-chekcout-hook
This file contains hidden or 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 { decode } from 'shopify-gid'; | |
const shopifyUrl = 'https://askphill.com' | |
export function useDirectCheckoutItems() { | |
// items is [{quantity: quantity, variantId: 'variantId'}] | |
async function checkoutItems(items) { | |
if (items.length < 1) { | |
throw new Error('Must include at least one line item, empty line items found'); | |
} | |
items.forEach(item => { | |
if (item.variantId == null) { | |
throw new Error(`Missing variantId in item`); | |
} | |
if (item.quantity == null) { | |
throw new Error(`Missing quantity in item with variant id: ${item.variantId}`); | |
} else if (typeof item.quantity !== 'number') { | |
throw new Error(`Quantity is not a number in item with variant id: ${item.variantId}`); | |
} else if (item.quantity < 1) { | |
throw new Error( | |
`Quantity must not be less than one in item with variant id: ${item.variantId}` | |
); | |
} | |
}); | |
await setTimeout(() => { | |
const string = items | |
.map(({ variantId, quantity }) => `${decode(variantId).id}:${quantity}`) | |
.join(','); | |
const checkoutUrl = `${shopifyUrl}/cart/${string}`; | |
window.location.replace(checkoutUrl); | |
}, 2000); | |
return 'done'; | |
} | |
return checkoutItems; | |
} | |
export default useDirectCheckoutItems; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment