Shopify - Headless Integration Guide

Adding the donation widget to an e-commerce experience

👍

Who should read this:

The webmaster or developer with HTML/CSS -level access to the Shopify Plus e-commerce website.

A complete implementation of the ShoppingGives App technology involves adding the donation widget to an e-commerce experience in the following places:

  1. Global Tracking

  2. Product Detail Page (PDP) Widget

  3. Shopping Cart Page Widget

  4. Checkout Page Widget

  5. Styling and Customization

  6. Testing – Final step after the above pieces of code are added to the store

Global Tracking Script

Make sure the following script section is included on every page in the header tag of your site:

<script type="text/javascript" src="https://cdn.shoppinggives.com/cc-utilities/sgloader.js?sid=XXXXXXXXXX&test-mode=true"></script>

The parameters available for the "sgloader.js" script are:

ParamTypeDescriptionRequiredDefault
sidtextStore ID - Provided by ShoppingGivesYesn/a
test-modeboolToggles test mode on, turn to true while testingNofalse

Persist Tracking Id

In order for a seamless transition between your frontend and Shopify Checkout, it is require for the Tracking Id to be set to the Shopify Cart Attributes.

  1. Retrieve Tracking Id You can retrieve the Tracking Id using the following function:

🗒️

Note:

The Tracking Id is stored in sessionStorage, the following function requires only your StoreId to retrieve the value.

 let trackingId = atob(sessionStorage.getItem('sg.sid-' + {storeId}));
 let trackingId = atob(sessionStorage.getItem('sg.sid-' + A53bd95b000011112222f762bb80014d));
  1. Passing the Tracking Id to the Shopify Cart Attributes.
  • The following Shopify Storefront API call can be used to accomplish this. GraphQL Mutation
ParamDescription
keyShoppingGives Donation Tracking ID
valuetracking id e.g: e0a95a54052c47238ea2d2d9817c42e0

Product Detail Page (PDP) Widget

ShoppingGives allows merchant the ability to customize where our Product Detail Page widget appears on their store and how it is displayed.

  1. Choose your widget style

To customize the widget Go to the Customize widget theme section of the ShoppingGives app under “Campaigns > Widget Settings > Select "Manual Placement” scroll down to "Widget Scripts" and select "Product Page" tab. Select which widget style, and copy and past the JS for the applicable widget.

Here you are able to choose between three different widget themes:

Compact:

Contained:

Full:

  1. Craft the Widget's URL Parameters
ParamTypeDescriptionRequiredDefault
sidtextStore ID - provided by ShoppingGivesYesn/a
pricetextPrice of the current subitemYesn/a
subitem-idtextIdentifier of the current subitemYesn/a
target-elementtextCSS Selector value where you want the widget to be placed.NoIf none is provided, it replaces the script tag with the widget HTML
afterboolAppend after target-elementNofalse
beforeboolAppend before target-elementNofalse
debugboolAllows to turn on debug logging for the widgetNofalse

🚧

Reminder

Remove all optional URL Params that are not being used.

  1. Place the widget on the product pages
<!-- TEMPLATE -->

<script type="text/javascript" src="https://cdn.shoppinggives.com/cc-utilities/{product-widget-style}.js?sid={store-id-provided}&price={price-of-item}&subitem-id={identifier-for-specific-product-variant}"></script>
<!-- EXAMPLE -->

<script type="text/javascript" src="https://cdn.shoppinggives.com/cc-utilities/contained-product.js?sid=ab123456-c78d-9ef0-g1h2-345i678j90k1&price=98.76&subitem-id=SUBITEM123"></script>

📘

Note

If a product has multiple variants (e.g. size, color, etc.) but the subitem ID is not defined yet, populate the “subitem-id” parameter with the first variant’s ID.

  1. Handle updating of sub-item on the page

a. On subitem change, run:

window.sgProductControllers[0].setSubitem('{subitem-id}', {price});
window.sgProductControllers[0].setSubitem('SUBITEM123', 98.76);

👍

Confirm Dynamic Donation Amount

Confirm that the donation amount shown on product pages changes dynamically based on the product value.

Cart Page Widget

Similar to the Product Page widget the merchant has the ability to customize where our Cart and Checkout Page widget appears on their store and how it is displayed.

  1. Choose your widget style

To customize the widget Go to the Customize widget theme section of the ShoppingGives app under “Campaigns > Widget Settings > Select "Manual Placement” scroll down to "Widget Scripts" and select "Cart Page" tab. Select which widget style, and copy and past the JS for the applicable widget.

Here you are able to choose between three different widget themes:

  1. Craft URL Params
ParamTypeDescriptionRequiredDefault
sidtextStore ID - Provided by ShoppingGivesYesn/a
target-elementtextCSS Selector value where you want the widget to be placed.NoReplaces script tag with widget HTML
afterboolAppend after target-elementNofalse
beforeboolAppend before target-elementNofalse
debugboolAllows to turn on debug logging for the widgetNofalse

🚧

Reminder

Please remove all the optional URL Params that are not being used.

  1. Create a hidden CSS Element “amount” to target for dynamic donation on cart and checkout.

📘

Note

Disregard this section if there is an entity already with a similar calculation or other uses like, for example, affiliate tracking.

The CSS element named “amount” is the term used to describe line items' currency value minus discounts, pre-tax, and pre-shipping (this is the currency value that ShoppingGives calculate donations based on).

For example, with a $100.00 subtotal and 10% off coupon, $4.99 Shipping, and $3.00 tax, the “amount” would be $90.00

  1. Place the widget code on the cart page
<!-- TEMPLATE -->

<script type="text/javascript" src="https://cdn.shoppinggives.com/cc-utilities/{cart-widget-style}.js?sid={store-id-provided}"></script>
<!-- EXAMPLE -->

<script type="text/javascript" src="https://cdn.shoppinggives.com/cc-utilities/contained-cart.js?sid=ab123456-c78d-9ef0-g1h2-345i678j90k1></script>
  1. Add Cart Items

Add cart items to the window.cc_cart_items javascript variable when an item is added. A cart item is a javascript object that includes the following fields: id, price, quantity, and discount.

<!-- TEMPLATE -->

if (!window.cc_cart_items) { window.cc_cart_items = [] }

// Foreach Item
window.cc_cart_items.push({ id: '{itemId}', price: {price}, quantity: {quantity}, discount: {discount} });
<!-- EXAMPLE -->

if (!window.cc_cart_items) { window.cc_cart_items = [] }

// Foreach Item
window.cc_cart_items.push({ id: 'SUBITEM123', price: 98.76, quantity: 3, discount: 10.00 });

a. When adding an item, refresh all the ShoppingGives cart controllers as in the following example.

if (window.sgCartControllers) {
   for (var x = 0; x < window.sgCartControllers.length; x++) {
      window.sgCartControllers[x].refreshCart();
   }
}

b. On a cart item change event (item removed, quantity changed, etc.), refresh all the carts to render the widgets properly.

c. Once the cart page is loaded and the cc_cart_items array javascript window variable is populated, verify the cart controllers have a null value. If any of the cart controllers have a NOT null value, then call the refreshCart() function to update its current state.

d. Handle Cart Discount updates – You can update discounts by applying them to each product and ignoring the cart level discount.

if(window.sgCartControllers) {
   for (var x = 0; x < window.sgCartControllers.length; x++) {              
       window.sgCartControllers[x].setDiscount({cart discount}); 
   }
}

👍

Confirm Donation Amount

Confirm the donation amount shown on the cart and checkout pages is dynamically changing based on the value of the cart, pre-tax, pre-shipping, and post-discounts.

Checkout Page (Billing Page Widget) ShopifyPlus only

📘

Shopify will be migrating merchants to a new checkout experience in September 2023

Check out the ShoppingGives checkout extension widget!
https://faq.shoppinggives.com/hc/en-us/articles/12414842885911-Shopify-Plus-Implementing-a-ShoppingGives-Checkout-Extension

📘

Note

It is advised to duplicate your published theme and add this there so that only you see the changes until you publish.

To place the ShoppingGives widget on the theme’s checkout page you are required to be a Shopify Plus store. You may also be required to request access to the checkout page theme files from Shopify Support. This can be done by accessing support in your store settings.

  1. Ask Shopify Support for access to the checkout.liquid

  2. Access your checkout.liquid: https://help.shopify.com/en/themes/development/layouts/checkout

  3. Place the tag directly where you want it OR choose an element to target and provide after or before URL params (see optional URL params below).

Placing the Checkout Page Widget :

  1. Placing Tracking on Checkout Page

In order to track the cause selection and set tracking across your headless front end and Shopify Checkout, ensure to add the Global Tracking script in the header tag of your checkout:

<script type="text/javascript" src="https://cdn.shoppinggives.com/cc-utilities/sgloader.js?sid=XXXXXXXXXX&test-mode=true"></script>

The parameters available for the "sgloader.js" script are:

ParamTypeDescriptionRequiredDefault
sidtextStore ID - Provided by ShoppingGivesYesn/a
test-modeboolToggles test mode on, turn to true while testingNofalse
  1. Placing the Checkout Widget

To place the widget in checkout, add the following below the {{ content_for_header }} in the checkout.liquid:

    <!-- Start Tracking Script -->
    <script src="https://cdn.shoppinggives.com/cc-utilities/sgloader.js?sid={STORE_ID}"></script>
    <!-- End Tracking Script -->

    <!-- Start Checkout Widget Script -->
    <script src="https://cdn.shoppinggives.com/cc-utilities/shopify-cart.js?store-id={STORE_ID}&template-type=0&target-element=.order-summary__section.order-summary__section--total-lines&before=true"></script>
    <!-- End Checkout Widget Script -->

    <!-- Start Widget Styles -->
    <style>
      .sg-widget {
        margin-top: 1rem;
        border-top: 1px solid rgba(175, 175, 175, 0.34);
        padding-top: 1rem;
        float: left;
      }
      .sg-widget .shoppinggives-tag {
        margin-bottom: 0 !important;
      }
      .sg-widget .main-element.sg-excluded {
        display: none !important;
      }
    </style>
    <!-- End Widget Styles -->
Url ParameterDescriptionDefaultOptions
Template-type (Optional)Shopping Gives provides 3 different widget types. By using this you define what widget type to use0 (Compact)0 = compact
1 = contained
2 = full
Target-element
(Required)
Where the widget will be placed, pass a URL encoded CSS selector herenonen/a
After
(Optional)
This is for if you are targeting an element (target-element) and want to append after said elementfalsetrue
false
Before
(Optional)
This is for if you are targeting an element (target-element) and want to append before said elementfalsetrue
false
Debug
(Optional)
If debug logs are neededfalsetrue
false

Optional: Expanding mobile Billing page view to show Checkout page details

To create an optimal experience for mobile users and ensure the users see the option to select a cause on the billing page, you can set the details to expand by default. To do so:

  1. Navigate to “Online Store > theme

  2. In the Live theme section select the drop-down “Actions” and choose “Edit Code”

  3. Find the checkout.liquid

  4. Place the following script:

<!-- Checkout Summary Expansion  -->
    <script>
     
      var interval = setInterval(function() {
        if(typeof Checkout === 'object'){
          if(typeof Checkout.$ === 'function'){ 
            if(Checkout.$('.order-summary-toggle').length > 0) {
            Checkout.$('.order-summary-toggle').trigger("click"); 
            clearInterval(interval);
            }
          }
      }
      }, 50);
      
    </script>
  <!-- End Checkout Summary Expansion  -->

Order Confirmation Screen

Upon an order being placed and a donation being created, a donation confirmation is required on the order confirmation screen. This can either be set as a modal or an embed. To configure your Donation Confirmation:

  1. Visit the ShoppingGives App portal and navigate to "Experience".
  2. Select either "Embedded Confirmation" or "Confirmation Window"
    1. If leveraging "Embedded Confirmation" visit ourFAQ for guidelines on setting placement of your Donation Confirmation.

Additional Scripts

In order to ensure all donations are captured, if you are using any additional payment methods like PayPal “buy it now” or other payment options which skip checkout, ensure you add the following to your additional scripts section under store settings:

  1. Go to settings on in your Shopify Store Admin

  2. Find “Checkout” and scroll down the page to the “additional scripts” section.

  3. Copy and paste the following, ensure you replace the placeholder “{store-id}” with your store’s ID and “{store-domain}” with your store’s Shopify domain.

    a. Your Store’s ID (store-id) can be found by navigating to Settings: Integrations section within the Change Commerce app.

    b. Your store’s Shopify domain (store-domain) can be found by viewing the URL in your browser’s address bar, while logged into Shopify, and taking the value before “.myshopify.com”.

<script src="https://tracking.api.shoppinggives.com/track-sale-pixel?store-id={store-id}&order-id={{ order.name | url_encode }}" /><script type="text/javascript" src="https://cdn.shoppinggives.com/cc-utilities/shopify.js?store-id={store-id}&shop={store-domain}.myshopify.com"></script>

Styles and Customization

You can use the CSS editor to customize the appearance of our widget with any style sheet. It is better to make the customization on the theme’s main style sheet.

To edit the container to add padding, target main-element.

Style Fields for the Compact Widget Style:

  1. To modify the eligibility tag main text, target class id sg-main-text to provide the stylings (don't forget to use !important)

  2. If you have to fix the logo size, target class id powered-by-logo

Style Fields for the Contained Widget Style:

  1. To modify the eligibility tag description, target class id sg-text-wrap to provide the stylings (don't forget to use !important)

  2. To modify the main title, target the id cc-shop-give to provide the stylings (don't forget to use !important)

  3. If you have to fix the logo size, target class id powered-by-logo

Style Fields for the Full Widget Style:

  1. To modify the main title, target the id sg-title to provide the stylings (don't forget to use !important)

  2. To modify the eligibility tag description, target class id sg-text-wrap to provide the stylings (don't forget to use !important)

  3. If you have to fix the logo size, use class id sg-powered-by-wrap

Testing the Integration

  1. Running a test purchase – Expected outcome:

a. Make a Test Purchase: Take note of the donation amount listed and cause supported before checkout.

b. Post-conversion: After a successful conversion the customer will be shown the post-conversion share modal. Use this modal to verify the correct donation amount and cause are displayed.

c. Data on the dashboard: The purchase should also be displayed in your dashboard. (Note: Shopify does not count today in the present date range.)

d. Data on reporting: You will also see a donation created on the donations report page with the order id. Check that the donation and nonprofit chosen is displayed correctly.

📘

Note

Portfolio donations are split into individual Nonprofits and the donation amount split evenly. Orders with Portfolios selected to receive a donation will all share the same order number.

  1. Check for z-index, global typeface, padding settings to ensure that the widget is displayed optimally.