By default a headless store will only work once a storefront token has been added in PreProduct and the redirect has been set to an isolated mode. These are required because PreProduct can’t automatically determine your cart URL endpoint in a headless setup. If you need to accept mixed-carts of buy-now and pre-order items, then read the below doc to understand the process.
If you’d prefer to isolate your pre-order orders or your store is not headless then the below process isn’t needed.
To accept headless mixed-cart orders, you’ll need to:
- Listen for PreProduct’s
ppConvertingButtonClicked
event - Stop PreProduct’s default behavior
- Handle the cart addition with your own API calls
Here’s how to implement this:
window.addEventListener('ppConvertingButtonClicked', (e) => {
e.detail.handled = true; // stop PreProduct requesting or redirecting
addPreOrderToCart() // your custom function
}, false);
The above code interrupts PreProduct’s standard flow, allowing you to:
- Make requests to your own server
- Use Shopify’s Storefront API directly
- Implement custom cart logic
All PreProduct variables and functions are available on the window object for your implementation.
function addPreOrderToCart(){
let url = `https://${ preproduct.shopify_domain }/api/${ PP_STOREFRONT_API_VERSION }/graphql.json`
fetch(url, {
'async': true,
'crossDomain': true,
'method': 'POST',
'headers': {
'X-Shopify-Storefront-Access-Token': {{ shopify storefront token goes here }},
'Content-Type': 'application/graphql'
},
'body': CustomCreateCart() // create the cart
// 'body': CustomUpdateCart(cartId) // or update an existing cart
})
.then(res => res.json())
.then(parsedRes => {
window.res = parsedRes;
console.log(`see the response at window.res`);
setTimeout(() => {
// redirect or let the user know the carts been added too.
})
})
}
function CustomCreateCart(){
return `
mutation {
cartCreate(
input: {
lines: [ ${ PPgraphqlLineItems() } ],
note: ""
}
) {
cart {
id
checkoutUrl
}
userErrors {
field
message
}
}
}
`
}
function CustomUpdateCart(cartId){
return `
mutation {
cartLinesAdd(
cartId: "${ cartId }",
lines: [ ${ PPgraphqlLineItems() } ]
) {
cart {
id
checkoutUrl
lines(first: 10) {
edges {
node {
id
quantity
}
}
}
}
userErrors {
field
message
}
}
}
`
}
window.addEventListener('ppConvertingButtonClicked', (e) => {
e.detail.handled = true;
addPreOrderToCart()
}, false);
Instead of using the window
defined variables, you can use the data available on the PPcartSession
object, namely items
, asAJAXLineItems(itemSelection={})
or asGraplLineItems(itemSelection={})