Send a product with a Text Modifier option to Checkout

On BigCommerce, text modifiers let customers enter information as a way to customize the product. The main use for this is product personalization, i.e., adding a name or initials to the product. See Text/Number Fields to learn more. This guide explains how to pass this product data from the product display page to a Recharge Checkout.

📘

Platform:

  • Recharge Checkout Integration
  • Custom

Adding script with Page Builder

The code below is meant to be added via Page Builder to a specific subscription product page that has a text modifier.

  1. Navigate to Products and click the three dots
  2. Select View in Page Builder
  3. Select Layers > Product Below Content > Layout > Column 1 > HTML

Passing modifiers to checkout

The script below shows passing text modifiers to checkout along with other product data. Use the example as a blueprint for your own store.

  • Make use of BigCommerce helpers for populating product data in the script. See Handlebars Helpers Reference to see all available product objects.
  • A modifier can be passed to checkout using the Recharge Checkout API line_items.properties. Any key-value pair can be passed to this attribute, allowing for flexibility when passing product data.

Full example code

<div class="modal-body quickView">
    {{> components/custom/product-view/product-view schema=false}}
</div>

<script type="text/javascript"> 
var _learnq = _learnq || []; 

 var item = {
   Name: "{{product.title}}", 
   ProductID: "{{product.id}}",
   ImageURL: "{{getImage product.main_image 'product_size' (cdn theme_settings.default_image_product)}}", 
   URL: "{{product.url}}",
   Brand: "{{product.brand.name}}", 
   Price: "{{product.price.without_tax.value}}",
   CompareAtPrice: "{{product.price.rrp_without_tax.value}}"
  };

_learnq.push(['track', 'Viewed Product', item]); 

_learnq.push(['trackViewedItem', {
   Title: item.Name, 
   ItemId: item.ProductID,
   ImageUrl: item.ImageURL, 
   Url: item.URL,

   Metadata: { 
     Brand: item.Brand,
     Price: item.Price, 
     CompareAtPrice: item.CompareAtPrice
 } 
 }]);
</script>

<script text="text/javascript">
    /**
     * @param {string} htmlString - A string of html.
     * @returns {ChildNode} - The Node created from html string provided.
     */
     function createElementFromHTML(htmlString) {
        const div = document.createElement("div");
        div.innerHTML = htmlString.trim();
        return div.firstChild;
    }
    
    /**
     * Takes in a single BigCommerce product and sends it to ReCharge Checkout. This does not affect
     * the current BigCommerce cart.
     * @param {object} root - The root object passed into the function.
     * @param {number} root.productId - The BigCommerce Product ID for the product.
     * @param {number} root.variantId - The BigCommerce Variant ID for the product.
     * @param {number} root.quantity - The quantity of the product to purchase.
     * @param {number} root.price - The price of a single product in Cents (ie $1.00 => 100).
     * @param {number} root.weight - The weight of the product in grams.
     * @param {string} root.title - The name of the product.
     * @param {string} root.subtitle - A subtitle that will be displayed below the product name on
     * the ReCharge checkout page.
     * @param {'days' | 'weeks' | 'months' | 'years'} root.deliveryUnit - The unit of time used when
     * determining how often to deliver a subscription.
     * @param {number} root.deliveryFrequency - The number used in combination with deliveryUnit to
     * determine how often to deliver a subscription.
     * @param {boolean} root.requiresShipping - Indicator if the product requires physically shipped.
     * @param {string} root.note - An order note to add to the ReCharge order.
     * @param {object} root.extras - An object containing key/value pairs of extra information to
     * attach to the ReCharge order. This object is converted into a
     * [{key: "key1", value: "value1"}, {key: "key2", value: "value2"}] format.
     */
     function singleItemSubscriptionCheckout({
                                                productId,
                                                variantId,
                                                quantity,
                                                price,
                                                weight,
                                                title,
                                                subtitle,
                                                deliveryUnit,
                                                deliveryFrequency,
                                                requiresShipping,
                                                modifier,
                                                note,
                                                extras,
                                            }) {
        const config = {storeDomain: "store-vn0shauajx.mybigcommerce.com"};
        var product = {
            properties: {
              shipping_interval_unit_type: "Months",
              shipping_interval_frequency: "1",
              modifiers:{}
            },
            product_id: productId,
            variant_id: variantId,
            quantity: quantity,
            price: price,
            grams: weight,
            title: title,
            variant_title: subtitle,
            order_interval_unit: deliveryUnit,
            order_interval_frequency: deliveryFrequency,
            requires_shipping: requiresShipping,
        };
        if (modifier!=""){
          product.properties["modifiers"] = modifier;
          product["variant_title"]= "Custom Mssg: "+modifiers[1964];
        console.info(product);
        }
        const cart = {note, note_attributes: [], items: [product]};
        Object.entries(extras || {}).forEach(([name, value]) =>
            cart.note_attributes.push({name, value})
        );
        const checkoutUrl = `https://checkout.rechargeapps.com/r/checkout?domain=${config.storeDomain}`;
        const payload = JSON.stringify(cart);
        const formTemplate = `<form method="post" action="${checkoutUrl}" style="display: none;"><input name="cart_json" type="hidden" value='${payload}'></form>`;
        const $form = createElementFromHTML(formTemplate);
        document.body.appendChild($form);
        $form.submit();
    }
    
    var _learnq = _learnq || [];
    
    if (item.ProductID=="73060") {
        var element= document.querySelector("#form-action-addToCart");
        console.log(element);
        element.value="Join SPREE club";
        element.removeAttribute("data-reveal-id");
        element.addEventListener("click", (e) => {
            e.preventDefault();
            var product_modifier = {"1964": $("input[name='attribute[1964]']").val()};
            singleItemSubscriptionCheckout({
                productId: 73060,
                variantId: 74364,
                quantity: 1,
                price: 4999,
                weight: 0,
                title: "SPREE Club Monthly Subscription Digital",
                subtitle: "Delivery Every 1 Month",
                deliveryUnit: "month",
                deliveryFrequency: 1,
                requiresShipping: false,
                modifier: product_modifier,
            });
        });
    }      
    else if (item.ProductID=="72440"){
        var element= document.querySelector("#form-action-addToCart");
       console.log(element);
       element.value="Join SPREE club";
        element.removeAttribute("data-reveal-id");
        element.addEventListener("click", (e) => {
        e.preventDefault();
        var product_modifier = {"1964": $("input[name='attribute[1964]']").val()};
        singleItemSubscriptionCheckout({
            productId: 72440,
            variantId: 73603,
            quantity: 1,
            price: 7499,
            weight: 0,
            title: "SPREE Club Monthly Subscription",
            subtitle: "Delivery Every 1 Month",
            deliveryUnit: "month",
            deliveryFrequency: 1,
            requiresShipping: false,
            modifier: product_modifier,
        });
    });
    }
    else {
     document.getElementById("form-action-addToCart").addEventListener('click',function (){
       _learnq.push(['track', 'Added to Cart', item]);
     });
    }
</script>

Need Help? Contact Us