Creating an "Add-to-cart" button from a category page for the Recharge Checkout on BigCommerce

An add to cart button from a category page can be useful when customers are ready to add a subscription to cart without clicking all the way into the product page.

This guide provides a high-level overview for adding an item to cart from a category page.

🚧

Note: As part of Recharge's ongoing efforts to streamline and enhance its platform, Recharge plans to discontinue support for BigCommerce by December 31, 2025. Recharge strongly recommends that all merchants currently using BigCommerce begin the process of migrating to Shopify, which Recharge will continue to support moving forward. See Shopify’s guide on Migrating to Shopify.

📘

Platform:

  • Recharge Checkout on BigCommerce

Before you start

This guide assumes you've already built a frequency selector drop down as part of the category page (shown below) and modified the templates > components > products > card.html BigCommerce theme file. See Editing Stencil theme files for details.

Example code on card.html

<button type="button" class="button button--small card-figcaption-button" id="testing" onclick="ajax_add_to_cart({{id}})"> {{lang 'products.add_to_cart'}} </button>

<select id="product_{{id}}_frequency" class="rca-subscription-form__frequency-selector" style={{ marginTop: ".5em", marginBottom: ".5em", display: "none" }}></select>


Step 1 - Create a BigCommerce Cart

You must create a BigCommerce cart with the desired product before you can add it as a subscription product. This should be done before adding the subscription product.

Use the BigCommerce Storefront Cart API to create a cart.

Example create a cart code

createCart(`/api/storefront/carts`, {
   "lineItems": [
   {
       "quantity": 1,
       "productId": 86
    }
   ]}
)
.then(data => console.log(JSON.stringify(data)))
.catch(error => console.error(error));

Example response

{
 "id": "d4e978c2-bdcf-41b0-a49b-fecf4f5223c1",
 "customerId": 0,
 "email": "",
 "currency": {
   "name": "US Dollars",
   "code": "USD",
   "symbol": "$",
   "decimalPlaces": 2
 },
 "isTaxIncluded": false,
 "baseAmount": 274.5,
 "discountAmount": 0,
 "cartAmount": 274.5,
 "coupons": [],
 "discounts": [
	...
 ],
 "lineItems": {
   "physicalItems": [
     {
       "id": "57a877e0-d898-47d0-910d-88656e8dee0c",
       "parentId": null,
       "variantId": 66,
       "productId": 86,
       "sku": "ABS",
       "name": "[Sample] Able Brewing System",
       "url": "https://{store_url}/all/able-brewing-system/",
       "quantity": 1,
		...
       "extendedSalePrice": 225,
       "isShippingRequired": true,
       "type": "physical",
       "giftWrapping": null
     },
     {
       "id": "22c461a2-eff9-4b72-8d22-7c2792ce2c2d",
       "parentId": null,
       "variantId": 67,
       "productId": 88,
       "sku": "CC3C",
       "name": "[Sample] Chemex Coffeemaker 3 Cup",
       "url": "https://{store_url}/all/chemex-coffeemaker-3-cup/",
       "quantity": 1,
		...
       "extendedSalePrice": 49.5,
       "isShippingRequired": true,
       "type": "physical",
       "giftWrapping": null
     }
   ],
  ...
 },
 ...
}


Step 2 - Create Recharge subscriptions

Once your code has added the desired item to cart, you can create the Recharge subscription.

const subscriptionProducts = RCA_DATA.RCA_PRODUCT_DATA.filter(x => x?.subscriptions?.length);
for (const product of subscriptionProducts) {
  const subscriptionData = product.subscriptions[0];
  const element = document.querySelector(`#product_${product.id}_frequency`);
  if (element) {
    const options = [];
    for (const frequency of subscriptionData.order_interval_frequency_options) {
      let unit = subscriptionData.order_interval_unit.replace(
        /\b([a-z])/g,
        function(_, initial) {
          return initial.toUpperCase();
        }
      );
      options.push(`<option value=${frequency}> Ship Every ${frequency} ${unit}${frequency > 1 ? "s":""} </option>`);
    }
    element.innerHTML = options.join("");
    element.style.display = "inherit";
  }
}

function ajax_add_to_cart(product_id) {
  fetch(`/cart.php?action=add&product_id=${product_id}`).then(response => {
    if (!response.ok) {
      throw new Error(response.status);
    }
    const subscriptionData = RCAInterface.bigcommerce.cart.findProductInRcaData(product_id);
    const variantId = subscriptionData.variants[0].id;
    const element = document.querySelector(`#product_${product_id}_frequency`);
    if(subscriptionData){
      RCAInterface.bigcommerce.cart.addSubscriptionByProduct(product_id, variantId, Number(element.value)).then(
        () => {
          window.location = "/cart.php";
        }
      )
    }
    else {
      window.location = "/cart.php";
    }
  });
}


Step 3 - Adding script to BigCommerce

There are three ways to add JavaScript to BigCommerce:

  • Wrap the code in a <script> tag and add it to your store using the Script Manager. Select Footer as the location for the script.
  • Place the script at the bottom of the product-view Stencil template file where you placed the HTML element from Step 1.
  • For advanced builds and optimized load times consider bundling JavaScript into the theme.