Skip to content

Instantly share code, notes, and snippets.

@pveen2
Last active June 21, 2021 12:13
Show Gist options
  • Save pveen2/3e7bdb62e71102abd316bb2fcbe28251 to your computer and use it in GitHub Desktop.
Save pveen2/3e7bdb62e71102abd316bb2fcbe28251 to your computer and use it in GitHub Desktop.
shopify-direct-chekcout-hook
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