Build a headless storefront with a Shopify backend using Recharge
You can use Recharge as part of a headless Shopify integration to offer subscription products with your own custom front end experience. In this use case, Shopify serves as the place you store all product information, and Recharge is where you'll setup subscriptions for any recurring products. This guide demonstrates one way to achieve this.
Prerequisites
- This example assumes the front end of your store is hosted outside of Shopify.
- You will need a back end environment to send and receive product data from our API. Due to CORS you can't query our API via the front end. Here is an example for creating a hosting a React app with AWS.
- You need to install React.js as part of your application for the following code to work.
NoteThe code below is an example demonstrating one way to achieve this use case. It is meant to serve as a reference and is not intended for use in a production environment.
Get data
First, call the Shopify API to obtain Shopify product information. Then call the Recharge Selling Plan API to obtain the corresponding selling plan data. This is how you display the correct selling plan information for each product.
const [products,setProducts]=React.useState([]); //Products State
const classes = useStyles();
const requestMetadata = {
method: 'GET',
headers: {
'Content-Type': 'application/json',
'X-Recharge-Access-Token':'your token' //X-Recharge Token
},
};
useEffect(() => {
fetch("https://your-store.myshopify.com/products.json",requestMetadata) //List of products
.then(res => res.json())
.then(
(result) => {
console.log(result);
fetch("https://api.rechargeapps.com/selling_plan_groups",requestMetadata) //Get selling plans from Recharge API
.then(res => res.json())
.then(
(plans) => {
console.log(plans);
var keyArray={}; //mapping key array on the basis of external product id : selling plans for that group
plans?.selling_plan_groups?.forEach(element => { //iterating over each item in selling plan group
keyArray[element.external_product_id]=element.selling_plans; //mapping key array on the basis each external product id with its selling plan group
});
result.products.forEach(element => { // Loop For Mapping each Product with its selling plans
element.flag="1";
element.selling_plans=keyArray[element.id]; //getting each product's selling plans on the basis of product id
element.selling_plan_id='';
element.variantId='';
});
setProducts(result.products) //updating products Array
},
(error) => { //catching error if any
}
)
Setup cart data
Create a const
to include all values you will show in the Shopify slider cart. You will pass these values as parameters to Shopify’s cart page. This is an example that shows the delivery frequency only for the products that have a selling plan.
const [cart,setCart]=React.useState([]);
const addCartToItem=(id,quantity,selling_plan_id,selling_plan_name,title)=>{
console.log(selling_plan_id);
if(selling_plan_id===undefined)
{
setCart([...cart,{
id:id,
quantity:quantity,
selling_plan:"No",
name:selling_plan_name,
title:title
}])
}
else{
setCart([...cart,{
id:id,
quantity:quantity,
selling_plan:selling_plan_id,
name:selling_plan_name,
title:title
}])
}
Redirect to checkout
Next, redirect the user to checkout and populate the above parameters in the URL
const checkout=()=>{
const myLink = 'https://your-store.myshopify.com/cart/'
let apiUrl = `${myLink}?`;
cart.forEach((x,index) => {
apiUrl += `&id${index}=${x.id}&quantity${index}=${x.quantity}&selling_plan${index}=${x.selling_plan}`;
});
apiUrl += `&length=${cart.length}`;
console.log(apiUrl);
window.location.href = apiUrl;
}
Modifying Shopify theme cart page
In your Shopify theme.js
file add the following code to receive the data and display it on the cart page.
var data=[];
var parameters = getQueryStringParameters();
console.log(parameters);
if(isEmpty(parameters) == false) {
console.log(parameters);
Object.keys(parameters).forEach(function(element){
console.log(element);
data.push({
[element]:parameters[element]})
});
var itemsArray=[];
console.log(parameters['length']);
for(var n=0;n<parameters['length'];n++){
if(parameters['selling_plan'+n]=="No")
{
itemsArray.push({
'id': parameters['id'+n],
'quantity': parameters['quantity'+n],
})
}
else{
itemsArray.push({
'id': parameters['id'+n],
'quantity': parameters['quantity'+n],
'selling_plan':parameters['selling_plan'+n],
})}
}
let formData = {
'items': itemsArray
};
console.log(formData);
fetch('/cart/add.js', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify(formData)
})
.then(response => {
window.location.href = '/cart';
})
.catch((error) => {
console.error('Error:', error);
});
}
(Optional) Redirect to checkout
You can redirect the user directly to checkout and bypass the cart all together. See this [article}(https://support.rechargepayments.com/hc/en-us/articles/360006332733-Redirect-to-subscription-checkout-) for details on redirecting to Shopify Checkout, or Redirect to Recharge-hosted checkout .
Updated 3 months ago