Browser-based user interaction tracking can potentially be blocked by ad blocking software installed on customer’s computers. As an alternative, you may consider using Google Measurement Protocol (GMP) to track user interactions on the back-end (i.e., on your own server).

When using GMP to track user interactions on the back-end, your server must generate a “client ID” for each customer who lands on your website and persist that ID, so it is tracked throughout your site. For more information, see Google Measurement Protocol.

When the customer initiates a purchase, you can pass the client ID to FastSpring along with any other order data, as an order tag. You can find more information about passing order tags in our article Passing and Capturing Custom Order Tags and Product Attributes.

If you do not already subscribe to the order.completedorder.failed, and order.canceled server webhook events, you should do that, and create a script to parse the posts sent by FastSpring for each order. Upon order completion, the JSON order data sent via the webhooks includes the order tags containing the client ID. You can use the client ID to update your records with order information. You can complete the process by sending the tracking request for the client ID from your server. See Webhooks for more information.

 Tip

You can optionally subscribe to the return.created webhook event to tie return/refund information to the tracking client ID. Subscription lifecycle tracking can also be tied to the tracking client ID by subscribing to the subscription.activatedsubscription.deactivated, and subscription.canceled webhook events, all of which include order tags for the order that created the subscription.

In this way, the customer’s web browser is not directly involved in the tracking process. By bypassing the browser, you can bypass ad blocking software and ensure that tracking and reporting occur for all customers.

FastSpring works with a trusted partner, Impact, to provide affiliate marketing solutions for our clients.

For more information about setting up an account with Impact, please contact FastSpring Support.

Set Up Automatic Integration with Impact

FastSpring offers an automated solution to help you set up integration with Impact. This process implements it automatically; you only need to copy and paste the details from your Impact account when prompted.

  1. From the Integrations menu of the FastSpring App, select the Webhooks tab.
  2. Click Add Webhook.
  3. In the Name field, enter Impact Sales Tracking.
  4. Click Add.
  5. Inside the newly created Impact Sales Tracking webhook configuration, click Add Browser Script.
  6. A new browser script appears, and a dialog opens to let you configure the browser script.
  7. In the Name field of the new browser script, enter Impact Sales Tracking – <id>.
  8. Still in the Name field, use your keyboard to replace <id> with your Impact Sales Tracker ID.
    See Finding Your Impact Sales Tracker ID for a visual walkthrough.
  9. Under Events, select the checkbox next to browser.order.completed.
  10. Using your mouse, select all of the placeholder text in the Function field, and then press Delete or Backspace on your keyboard to delete it.
  11. Copy the following JavaScript function and paste it into the Function field:
    JavaScript function for Impact tracking
    function (event) {
        this.load('https:{{{Universal Tracking Tag Script URL}}}', function() {
            
            var trackingObject = {};
            
            trackingObject.orderId = event.data.reference;
            trackingObject.customerId = event.data.account;
            trackingObject.currencyCode = 'USD';
            trackingObject.items = [];
            
            if (event.data.coupons && event.data.coupons[0]) trackingObject.orderPromoCode = event.data.coupons[0];
            
            event.data.items.forEach(function(item){
                trackingObject.items.push({
                    subTotal: item.subtotalInPayoutCurrency,
                    category: "digital",
                    sku: item.product,
                    quantity: item.quantity
                });
            });
            
            ire('trackConversion', {{{Universal Tracking Action ID}}}, trackingObject);
        });
    }
    
  12. In the Function field, select the {{{Universal Tracking Tag Script URL}}} and replace it with the “General Tracking Settings URL” from your Impact account. See Finding your General Tracking Settings URL for a visual walkthrough.
  13. Scroll down to the bottom of the Function field. Then, select the {{{Universal Tracking Action ID}}} and replace it with your Sales Tracking ID; that is, the same value you used in the Name field above to replace <id>.
  14. Click Add.

Within the FastSpring App, you can enable or disable extensions for additional services, including:

Click on the extensions below for instructions configuring them in the FastSpring App, and additional resources.

AdRoll

Configure AdRoll integration

  1. Navigate to Integrations > Extensions > AdRoll.
  2. In the AdRoll window appears, click Setup.
  3. In the AdRoll Advertiseable ID field, enter the AdRoll Advertiseable ID that was generated during SmartPixel setup in your AdRoll account.
  4. In the AdRoll Pixel ID field, enter your AdRoll Pixel ID that was generated during SmartPixel setup in your AdRoll account.
  5. Click Enable.

Bing Ads

Configure Bing Ads integration

  1. Navigate to Integrations > Extensions > Bing Ads.
  2. In the Bing Ads window appears, click Setup.
  3. In the Bing Ads Tag ID field, enter or paste your account’s Bing Ads Tag ID, which you can obtain from the Campaigns, Goals and Conversions page in your Bing Ads account.
  4. Click Enable.

Constant Contact

Configure Constant Contact integration

  1. Navigate to Integrations > Extensions > Constant Contact.
  2. In the Constant Contact window, click Setup.
  3. In the API Key field, enter or paste the API Key provided by Constant Contact for your account.
  4. In the Access Token field, enter or paste the access token for your Constant Contact account.
  5. Click Enable.

Google AdWords

Configure Google AdWords integration

  1. Navigate to Integrations > Extensions > Google AdWords.
  2. In the Google AdWords window, click Setup.
  3. In the Google Adwords Conversion ID field, enter or paste the Google Adwords Conversion ID that was generated during the remarketing setup.
  4. In the Google Adwords Label field, you can optionally enter the Conversion Label from the Event Snippet in your Adwords account.
  5. Click Enable.

Google Analytics

Google Tag Manager

Impact

MailChimp

UpSellit

Configure UpSellit integration

  1. Navigate to Integrations > Extensions > UpSellit.
  2. In the UpSellit window, click Setup.
  3. Enter the “usi_launch_code” provided by UpSellit after the registration.
  4. Click Enable.

DevMate

If you use Google Tag Manager to manage Google Analytics, do not integrate Google Analytics with your FastSpring Storefront. Instead, follow instructions to integrate Google Tag Manager.

Set up Google Analytics in the FastSpring App and configure Google Analytics settings for time zone, ecommerce, cross-domain tracking, and referral exclusions.

Prerequisites

Set up Google Analytics Integration

For all Storefronts:

  1. In the FastSpring App, navigate to Integrations > Extensions > Google Analytics.
  2. Click Setup.
  3. Enter your Google Analytics Tracking ID in the Google Analytics Property ID field and click Enable.

For Individual Storefronts:

Only configure custom Google Analytics integration for individual Storefronts if you need to use different IDs for different Storefronts. Otherwise, configure Google Analytics integration for all Storefronts following the steps above.

  1. In the FastSpring App, navigate to Storefront you want to modify and click Settings.
  2. Within the Storefront Settings, click Analytics Integration in the left menu.
  3. In the Google Analytics Integration Behavior drop-down, select Use custom Google Analytics property ID for this storefront.
  4. Enter your Google Analytics Tracking ID in the Google Analytics > Custom Google Analytics property ID for this storefront field and click Save at the top right-hand corner of the page.
If you experience data issues, use Google to Troubleshoot Data in your Reports or Troubleshoot Tag Setup and no-data Issues. Alternatively, use Chrome Extensions Google Analytics Debugger and Tag Assistant.

Ad-blocking tools may cause as many as 10 to 15 percent of transactions to not be reported to Google Analytics. However, ad blockers also similarly impact the traffic reported to Google Analytics. Therefore, relative analyses (such as conversion rates) are unaffected while absolute numbers (such as visitors and pageviews) are affected. Google Measurement Protocol is a server-side tracking alternative to browser-based customer interaction tracking.

Configure Google Analytics Settings

Time Zone

Align the time zone used by FastSpring (GMT +0) with the time zone used by your Google Analytics account to make it easier to compare reports from both sources. Navigate to your Google Analytics View Settings and set the Time zone country or territory to United Kingdom and GMT +00:00.

Ecommerce

  1. Go to Ecomerce Settings for each Google Analytics view in which you want to see data (see Google Analytics instructions to enable ecommerce for a view).
  2. Select On for Enable Ecommerce.
  3. Select On for Enable Enhanced Ecommerce Reporting.
  4. Create the following checkout funnel steps:
  5. Click Save.

Cross-Domain Tracking for Web Storefronts

Cross-domain tracking ensures that tracking is not lost between your site and FastSpring store. Do not complete this step if you are using Google Tag Manager.

Copy and paste the following code in the Google Analytics code placed on your website, replacing both occurrences of ‘yourcompany’ in the code with the base URL for your Web Storefront:

Example of Google Analytics linker plugin code for use on your website

If you are using global site tag (latest) version:

Cross-domain measurement with gtag.js adds a linker parameter to URLs that point to the destination domain. The linker parameter is identified in URL query parameters with the key _gl:

On the destination domain, gtag.js is configured to check for linker parameters in the URL. If a valid linker parameter is found, gtag.js extracts the 1st party measurement cookie and stores it. (https://developers.google.com/gtagjs/devguide/linker)

Example of gtag linker plugin code for use on your website:

Cross-Domain Tracking for Store Builder Library

When using Store Builder Library or a Popup Storefront, include the following attribute in the script that loads the FastSpring library:
data-decorate-callback=”decorateURL”

Example of loading the FastSpring library with the data-decorate attribute included:

Copy and paste the following code into your page:

Set up Referral Exclusions in your Google Analytics Account

Prevent issues with tracking being lost when customers are redirected or referred to other domains.

Follow Google Analytics instructions to set up referral exclusions and add the following domains to the Referral Exclusion list:

If you are using Google Tag Manager to insert your Google Analytics tracking snippet, do not include your Google Analytics tracking ID in the FastSpring App. This could result in double-counting of events and sales. If you do not want to use Google Tag Manager, follow instructions to integrate Google Analytics.

What is Google Tag Manager?

Google Tag Manager is a convenient way to manage snippets, pixels, and scripts on your website. Common examples to use Google Tag Manager include a Facebook or Google Ads conversion pixel or a marketing attribution script such as Marketo or Bizible.

Google Tag Manager can be used together with Google Analytics but is a separate tool. Google Analytics is a platform for collecting website and app data so you can analyze your user experience. You can use Google Tag Manager to inject Google Analytics tracking scripts, but the two can also be used completely separately.

You may need to periodically update your Google Tag Manager settings to stay in compliance with changing browser standards and best practices.

Configuration

You may need to periodically update your Google Tag Manager settings to stay in compliance with changing browser standards and best practices.

Prerequisites

Integration for all Storefronts

To set up Google Tag Manager integration for all storefronts:

  1. In the FastSpring App, navigate to Integrations > Extensions > Google Tag Manager.
  2. Click Setup.
  3. Enter your Google Tag Manager Container ID and click Enable.

Custom Integration for Individual Storefronts

Only configure custom Google Tag Manager integration for individual Storefronts if you need to use different IDs for different Storefronts. Otherwise, configure Google Tag Manager integration for all Storefronts following the steps above.

  1. In the FastSpring App, navigate to Storefront you want to modify and click Settings.
  2. Within the Storefront Settings, click Analytics Integration in the left menu.
  3. In the Google Tag Manager Integration Behavior drop-down, select Use custom Google Tag Manager container ID for this storefront.
  4. Enter your Google Analytics Tracking ID in the Google Tag Manager > Google Tag Manager custom container ID for this storefront field and click Save at the top right-hand corner of the page.

Set Up Variables

Create user-defined variables:

  1. Enter fsc-url as the Variable name.
  2. Choose Data Layer Variable as the Variable Type
  3. Type fsc-url as the Data Layer Variable Name and choose Data Layer Version 2.
  4. Click Save.
  5. Repeat the steps above for the following variables:

Set Up Google Analytics for the Events Tag

Add a Google Universal Analytics tag.

  1. Click Tags > New.
  2. Enter Events as the tag name.
  3. Select Tag Configuration > Google Analytics: Universal Analytics.
  4. Select Event for Track Type.
  5. Enter the following values in the Event Tracking Parameter fields:
  6. Select False for Non-Interaction Hit.
  7. In the Google Analytics Settings drop-down, select New Variable
  8. Enter your Property Name and Tracking ID (from your Google Analytics account).
  9. Expand More Settings > Ecommerce and
  10. Select the checkbox for Enable Enhanced Ecommerce Features and Use data layer.
  11. Expand Fields to Set and add the following fields:
  12. Click Save.
  13. Click within the Triggering area and select New trigger (the plus sign in the top right corner).
  14. Enter the name FastSpring Events.
  15. Click within the Trigger Configuration area and select Other > Custom Event.
  16. Enter .* in the Event name field and select the checkbox for Use regex matching.
  17. Select the radio button for Some Custom Events and then select Event, starts with, and enter FSC-.
  18. Click Save > Save.

Set Up Google Analytics for the Pageview Tag

  1. Click Tags > New.
  2. Enter Pageview as the tag name.
  3. Select Tag Configuration > Google Analytics: Universal Analytics.
  4. Select Page View for Track Type.
  5. In the Google Analytics Settings drop-down, select your Google Analytics variable configured in the previous section.
  6. Click within the Triggering area and select New trigger (the plus sign in the top right corner).
  7. Enter the name fsc-url and click within the Trigger Configuration area.
  8. Select Page View > Page View and select the radio button for Some Page Views.
  9. Select fsc-url, starts with, and enter h.
  10. Click Save > Save.

Fire a Tag on the Order Completion Page

You can optionally fire tags on the order completion page. If you have access to all the order-related variables, you can add a Trigger that only fires on the order completion page:

Add Custom Tags to Google Tag Manager

In addition to the variables listed above, FastSpring populates the Data Layer with additional data that is useful for various custom tags that you can add to the container.

Each event has the following variables and values, in addition to the variables listed for the specific event:

“FSC-checkoutStep1” event

This event fires when a customer starts the payment process by clicking Place your order. This event also contains ecommerce data for the Google Analytics Enhanced Ecommerce report.

“FSC-checkoutStep2” event

This event fires when a customer enters a name in the payment details. No identifiable customer data is passed. This event also contains Ecommerce data for the Google Analytics Enhanced Ecommerce report.

“FSC-checkoutStep3” event

This event fires when a customer enters an email address in the payment details window. No actual customer data is passed. This event also contains ecommerce data for the Google Analytics Enhanced Ecommerce report.

“FSC-checkoutStep4” event

This event fires when a customer enters payment details in the payment window. No actual customer data is passed. This event also contains ecommerce data for the Google Analytics Enhanced Ecommerce report.

“FSC-checkoutStep5” event

This event fires when a customer clicks the “Buy Now” button in the payment window. This event also contains ecommerce data for the Google Analytics Enhanced Ecommerce report.

“FSC-purchaseComplete” event

This event fires when a customer completes the purchase. This event does not contain ecommerce data becasue ecommerce data is passed with the pageview.

“FSC-itemAddedToCart” event

This event fires when a customer adds an item to the cart. It does not fire for items that are already in the cart when the page loads. This event also contains ecommerce data for the Google Analytics Enhanced Ecommerce report.

“FSC-itemRemovedFromCart” event

This event fires when a customer removes an item from the cart. This event also contains ecommerce data for the Google Analytics Enhanced Ecommerce report.

“FSC-detailedItemView” event

This event fires when a customer clicks to see detailed information about an item. This event also contains ecommerce data for the Google Analytics Enhanced Ecommerce report.

“FSC-promotionView” event

This event fires automatically when related offers are loaded on the page, such as cross-sells, upsells, and product options. For Google Analytics Ecommerce Tracking, related offers are labeled as promotions. This event also contains ecommerce data for the Google Analytics Enhanced Ecommerce report.

“FSC-promotionClick” event

This event fires when a customer clicks on a related offer such as cross-sells, upsells, and product options. For Google Analytics Ecommerce Tracking, related offers are labeled as promotions. This event also contains Ecommerce data for the Google Analytics Enhanced Ecommerce report.

Pageview

To comply with Google Tag Manager, pageviews fire without an explicit event field value. This event also contains ecommerce data for the Google Analytics Enhanced Ecommerce report. Purchase completion is fired as a Pageview, but contains these additional fields:

Table of Contents

With Mailchimp, set up automatic emails for consumers who abandon their carts. These emails can incorporate deals such as coupon codes in order to re-attract the consumer to complete their purchase. Utilizing Mailchimp for cart abandonment email retargeting efforts can have a 20-30% recovery rate.

Prerequisites: Before beginning, set up your FastSpring Storefront and a Mailchimp account. The Mailchimp account may be Enterprise, Standard, Essentials, or the Free account.

When a consumer visits your Store and initiates the checkout process without completing it, FastSpring communicates the consumer’s email address (collected during checkout) to your Mailchimp account. Then, Mailchimp adds the email address to an Abandoned Cart Audience list for your account. After the email is added, Mailchimp launches an automation which sends the buyer an email inviting them to complete their purchase.

Please note that this integration does not record general newsletter sign-ups, only Abandoned Cart Opt-Ins.

Connect Your FastSpring Account to Mailchimp

FastSpring has updated the integration with Mailchimp to utilize its version 3.x API. This new version provides an improved user experience, greater cart data, and enhanced security for your Mailchimp account.

Configure Mailchimp 3.x – New Version

  1. In the FastSpring App, navigate to Integrations > Extensions.
  2. Select the Mailchimp (New Version) tile and click Start. A new browser window appears displaying a Mailchimp login screen.
  3. When prompted by Mailchimp, enter your Mailchimp credentials (Username and Password) in the Log in and authorize window and click Log In.
  4. In the Authorize FS Register window, click Allow to authorize FastSpring to have access to your Mailchimp account.
  5. In the Mailchimp Extension window, select an option from the Mailchimp Audience drop-down and click Save and Enable.
  6. Contact FastSpring Support to complete the setup for this extension.
The Mailchimp extension tile will show an “on” indicator but will not work until you contact Support to complete the integration setup.

Configure Mailchimp 2.x – Previous Version

Mailchimp 2.x will only appear as an option if you previously enabled it before the Mailchimp 3.x extension became available.

  1. On the Extensions tab, click the MailChimp logo.
  2. In the MailChimp window, click Setup.
  3. In the API Key field, enter or paste the API Key from your MailChimp account.
  4. In the Unsubscribed List ID field, enter or paste the List ID found in the settings of the unsubscribed customer list from your MailChimp account.
  5. In the Subscribed List ID field, enter or paste the List ID found in the settings of the subscribed customer list from your MailChimp account.
  6. In the Abandonment List ID field, enter or paste the List ID found in the settings of the abandoned visitors’ list from your MailChimp account. This is the list that FastSpring uses for visitors who abandon the Store without completing a purchase.
  7. Click Enable to save your changes.

Configure the FastSpring to Mailchimp Integration

After you connect your FastSpring Account to Mailchimp (see above), Integration is created. The Integration is the connection between FastSpring and Mailchimp, which you can configure to automatically respond to new email addresses collected in your Store.

  1. Log in to your Mailchimp account and click the Integrations link.
  2. In the Integrations page, click the Manage Your Sites button.
  3. For Abandoned Cart Email, click Add. The Abandoned Cart Notification page appears.
  4. Specify various options for sending recovery-targeted emails to potential buyers: when to email buyers, sender details, subject line & body content including layout.
Mailchimp provides a number of themes and layout options so we recommend you take your time designing an email that is actionable and incentivizes buyers to return to your website to complete their purchase.

Verify the Integration

There are multiple ways to verify that the email addresses entered in an abandoned card are being added to your Mailchimp Audience. One way is to navigate to the Integrations page in Mailchimp to confirm that your FastSpring Storefront has been connected to your Mailchimp account. Alternatively, you can test the abandoned cart scenario.

Create an Abandoned Cart Scenario:

  1. Test an Order for the Storefront.
  2. When checking out, enter your email address. Optionally include additional information (name, address, phone number).
  3. After a few minutes, close the browser tab or window. This implies you are abandoning your purchase.
  4. After 45 minutes have passed, log in to your Mailchimp account. Navigate to the Audiences page to verify the email address with which you tested is there.

In the image below, the Mailchimp Audience reflects the 5 timestamped email addresses used to create separate abandoned cart scenarios.

Subscriber Opt-In Configuration Options

The Get updates about our products and offerings checkbox in the checkout process must be checked in order for FastSpring to communicate these email addresses and cart data to Mailchimp.

As a seller, you can choose whether the opting in to seller communications is On or Off by default.

  1. In the FastSpring App, select Storefronts, then click the Settings button on the applicable Storefront.
  2. Under Customer Information, there is a drop-down labeled Newsletter Subscription Checkbox.

Example Email

Pictured below is an example of a retargetting email initiated by Mailchimp. Version 3 of the integration includes elements such as:

Additional Resources

Mailchimp offers additional functionality and advanced features that leverage additional marketing techniques. To better leverage Mailchimp for email marketing, take advantage of external resources, such as Mailchimp Knowledge Base.

Using the Shipping Fee Calculator, you can configure your Store to collect estimated shipping charges from your customers who purchase physical products. There are two ways you can configure the Shipping Fee Calculator:

Please click one of the following links to jump to the corresponding section of the document.

 

Shipping Fee Conditions

FastSpring only collects estimated shipping charges when an order includes products or bundles with a product format of Digital Product and Shipment or Physical Shipment. For orders containing only products whose format is Digital Product or Software as a Service, or containing only subscription products, shipping charges are not collected.

On the detail page for each product or bundle, the product format appears in the Fulfillment section. You change it by clicking Change Product Format.

 

Web Storefront Customer Experience

Here is an illustration of how the estimated shipping charges can appear in your Web Storefront:

 Note

The optional icon for Shipping Charges pictured above is for illustrative purposes only. No icon is provided by default, but you can optionally upload one when enabling shipping fee charges (see below).

 

Enabling Shipping Fee Charges

Shipping fee charges are enabled at the Store level. When you enable the Shipping Fee Calculator, all Storefronts in the Store begin collecting estimated shipping charges for physical products.

To enable the Shipping Fee Calculator

  1. From the FastSpring App, select the Integrations menu. The Extensions tab is selected by default.


     

  2. Click the Shipping Fee Calculator card. A description of the extension appears.


     

  3. Click Setup. The configuration fields appear.


     

  4. Click Enable.

 

Coding Guidelines for the Calculation Script

Here are some essential guidelines for use when creating your shipping fee calculation script.

 

Examples and Resources

Here are some resources that may help you in developing your own customized script. These include an example of the order object, two examples of a useful function for getting the product quantity from the order object, and three example scripts.

The following JSON string is an example of the order object that is passed to the shipping script. Your script can use the data in this object to calculate the amount of estimated shipping charges to be collected for the order. 

Order object example
{
  "order": {
    "currency": "USD",
    "country": "US",
    "taxExemptionAllowed": false,
    "total": "$0.00",
    "totalValue": 0.0,
    "tax": "$0.00",
    "taxValue": 0.0,
    "totalWithTax": "$0.00",
    "totalWithTaxValue": 0.0,
    "discountTotal": "$0.00",
    "discountTotalValue": 0.0,
    "discountTotalPercentValue": 0.0,
    "taxPriceType": "none",
    "taxType": "US",
    "groups": [
      {
        "items": [
          {
            "selected": false,
            "path": "physical",
            "pid": "physical",
            "quantity": 1,
            "price": "$2.00",
            "priceValue": 2.0,
            "priceTotal": "$2.00",
            "priceTotalValue": 2.0,
            "unitPrice": "$2.00",
            "unitPriceValue": 2.0,
            "unitDiscountValue": 0.0,
            "discountPercentValue": 0.0,
            "discountTotal": "$0.00",
            "discountTotalValue": 0.0,
            "total": "$2.00",
            "totalValue": 2.0,
            "quantityEditable": true,
            "removable": true,
            "image": "https://localhost:8443/icon.png",
            "display": "Physical 1",
            "description": {},
            "pricing": {
              "quantity": "allow"
            },
            "groups": [],
            "productFormat": "physical",
            "product": "physical",
            "variation": "physical"
          },
          {
            "selected": false,
            "path": "test3",
            "pid": "test3",
            "quantity": 1,
            "price": "$5.00",
            "priceValue": 5.0,
            "priceTotal": "$5.00",
            "priceTotalValue": 5.0,
            "unitPrice": "$5.00",
            "unitPriceValue": 5.0,
            "unitDiscountValue": 0.0,
            "discountPercentValue": 0.0,
            "discountTotal": "$0.00",
            "discountTotalValue": 0.0,
            "total": "$5.00",
            "totalValue": 5.0,
            "quantityEditable": true,
            "removable": true,
            "image": "https://localhost:8443/icon.png",
            "display": "Physical 2",
            "description": {},
            "pricing": {
              "quantity": "allow"
            },
            "groups": [],
            "productFormat": "physical",
            "product": "test3",
            "variation": "test3"
          }
        ],
        "driver": "demo",
        "required": false,
        "type": "add",
        "selections": false
      },
      {
        "items": [
          {
            "selected": false,
            "path": "test1",
            "pid": "test1",
            "quantity": 1,
            "price": "$4.59",
            "priceValue": 4.59,
            "priceTotal": "$4.59",
            "priceTotalValue": 4.59,
            "unitPrice": "$4.59",
            "unitPriceValue": 4.59,
            "unitDiscountValue": 0.0,
            "discountPercentValue": 0.0,
            "discountTotal": "$0.00",
            "discountTotalValue": 0.0,
            "total": "$4.59",
            "totalValue": 4.59,
            "quantityEditable": false,
            "removable": true,
            "image": "https://localhost:8443/icon.png",
            "display": "Digital 1",
            "description": {
              "summary": "Test",
              "full": "Test"
            },
            "pricing": {
              "quantity": "lock"
            },
            "groups": [],
            "productFormat": "digital",
            "product": "test1",
            "variation": "test1"
          },
          {
            "selected": false,
            "path": "test2",
            "pid": "test2",
            "quantity": 1,
            "price": "$16.99",
            "priceValue": 16.99,
            "priceTotal": "$16.99",
            "priceTotalValue": 16.99,
            "unitPrice": "$16.99",
            "unitPriceValue": 16.99,
            "unitDiscountValue": 0.0,
            "discountPercentValue": 0.0,
            "discountTotal": "$0.00",
            "discountTotalValue": 0.0,
            "total": "$16.99",
            "totalValue": 16.99,
            "quantityEditable": true,
            "removable": true,
            "image": "https://localhost:8443/icon.png",
            "display": "Digital 2",
            "description": {
              "summary": "Test",
              "full": "Test"
            },
            "pricing": {
              "quantity": "allow"
            },
            "groups": [],
            "productFormat": "digital",
            "product": "test2",
            "variation": "test2"
          },
          {
            "selected": false,
            "path": "physical-bundle",
            "pid": "physical-bundle",
            "quantity": 1,
            "price": "$6.00",
            "priceValue": 6.0,
            "priceTotal": "$6.00",
            "priceTotalValue": 6.0,
            "unitPrice": "$6.00",
            "unitPriceValue": 6.0,
            "unitDiscountValue": 0.0,
            "discountPercentValue": 0.0,
            "discountTotal": "$0.00",
            "discountTotalValue": 0.0,
            "total": "$6.00",
            "totalValue": 6.0,
            "quantityEditable": true,
            "removable": true,
            "bundle": true,
            "display": "Physical Bundle",
            "description": {},
            "pricing": {
              "quantity": "allow"
            },
            "groups": [
              {
                "display": "Physical Bundle",
                "items": [
                  {
                    "selected": false,
                    "path": "physical",
                    "pid": "physical",
                    "quantity": 1,
                    "price": "$0.00",
                    "priceValue": 0.0,
                    "priceTotal": "$0.00",
                    "priceTotalValue": 0.0,
                    "unitPrice": "$0.00",
                    "unitPriceValue": 0.0,
                    "unitDiscountValue": 0.0,
                    "discountPercentValue": 0.0,
                    "discountTotal": "$0.00",
                    "discountTotalValue": 0.0,
                    "total": "$0.00",
                    "totalValue": 0.0,
                    "quantityEditable": true,
                    "removable": true,
                    "image": "https://localhost:8443/icon.png",
                    "display": "Physical 1",
                    "description": {},
                    "pricing": {
                      "quantity": "allow"
                    },
                    "groups": [],
                    "productFormat": "physical",
                    "product": "physical",
                    "variation": "physical"
                  },
                  {
                    "selected": false,
                    "path": "test3",
                    "pid": "test3",
                    "quantity": 1,
                    "price": "$0.00",
                    "priceValue": 0.0,
                    "priceTotal": "$0.00",
                    "priceTotalValue": 0.0,
                    "unitPrice": "$0.00",
                    "unitPriceValue": 0.0,
                    "unitDiscountValue": 0.0,
                    "discountPercentValue": 0.0,
                    "discountTotal": "$0.00",
                    "discountTotalValue": 0.0,
                    "total": "$0.00",
                    "totalValue": 0.0,
                    "quantityEditable": true,
                    "removable": true,
                    "image": "https://localhost:8443/icon.png",
                    "display": "Physical 2",
                    "description": {},
                    "pricing": {
                      "quantity": "allow"
                    },
                    "groups": [],
                    "productFormat": "physical",
                    "product": "test3",
                    "variation": "test3"
                  }
                ],
                "driver": "physical-bundle",
                "required": false,
                "type": "bundle",
                "selections": false
              }
            ],
            "productFormat": "digital",
            "product": "physical-bundle",
            "variation": "physical-bundle"
          }
        ],
        "driver": "demo",
        "required": false,
        "type": "add",
        "selections": false
      }
    ],
    "coupons": [],
    "payments": [],
    "selections": false,
    "creationTime": 0
  },
  "messages": [],
  "phrases": {
    "MakeDefault": "Make Default",
    "Store": "Store",
    "Edit": "Edit",
    "SubscriptionAddonTerms.Single": "Renews along with subscription",
    "ChangePlanAndQuantity": "Change Plan & Quantity",
    "ViewDetails": "View Details",
    "Month": "month",
    "NoActiveSubscriptions": "No active subscriptions",
    "AutorenewOffWarning": "If automatic renew is turned off you will be required to enter payment details every time this subscription renews. Turn off automatic renew?",
    "Unexpected": "An unexpected error occurred.  Please try again, or refresh the page in your browser.",
    "BankPaymentWireInstructionTitle": "Bank Transfer Instructions",
    "PaymentVariant.jcb": "JCB",
    "BankPaymentWireInstructionAccountHolder": "Beneficiary/Account Holder",
    "TryAgain": "Try Again",
    "PaymentVariant.visa": "Visa",
    "Weeks": "weeks",
    "ErrorServer": "An unexpected error occurred. Please try again later.",
    "CancelSubscription": "Cancel Subscription",
    "CardDeclined": "Your credit card was declined. Please try another card, or choose a different form of payment.",
    "EnterTaxInformationJp": "Enter National Tax ID",
    "TaxInformationEU": "Includes VAT",
    "CardSecurityCodeHintAmex": "The CID is a 4 digit number printed on the front of your card.",
    "EnterZipToCalculate": "Enter ZIP",
    "FieldErrors": "Please correct the highlighted fields.",
    "DownloadNow": "Download Now",
    "Refunds": "Refunds",
    "Starting": "starting",
    "Close": "Close",
    "Week": "week",
    "Orders": "Orders",
    "PaymentType.ideal": "iDEAL",
    "BillingHistory": "Billing History",
    "ShippingTitle": "Shipping Address",
    "ConfirmCancelSubscription": "Are you sure you want to cancel the subscription?",
    "YouSaved": "You saved",
    "EUVatExemptInvalid": "Your company's VAT identification number could not be validated.",
    "JpConsumptionTaxExemptApplied": "Your company's National Tax ID has been applied, and the Consumption Tax charges have been removed.",
    "CardExpireYearPlaceholder": "YY",
    "Days": "days",
    "TermsOfSale": "Terms of Sale",
    "ShippingCity": "City",
    "WaitRedirectTitle": "Please wait...",
    "PaymentType.card": "Credit / Debit Card",
    "PaymentOption.wire": "Wire Transfer",
    "GetInvoice": "Get Invoice",
    "SavePaymentDetails": "Save Payment Details",
    "FirstName": "First Name",
    "TaxValue": "Tax:",
    "LightBox.UpgradeAvailable": "Upgrade available",
    "BankPaymentWireInstructionIban": "IBAN",
    "WaitRedirectAbout": "We are redirecting your browser, please wait.",
    "BankPaymentWireInstructionDialogTitle": "Bank Transfer Instructions",
    "CouponCode": "Coupon Code",
    "ForFree": "for free",
    "CardInfoBRL": "This purchase is subject to applicable Brazilian laws and rules of an international transaction",
    "Year": "year",
    "BankPaymentWireInstructionBankAddress": "Address",
    "EUVatExemptInfo": "If you are placing an order on behalf of a company in the EU, enter the company's VAT identification number and the VAT charges will be removed.",
    "Footer.ThisPurchase": "This purchase and product fulfillment are through ",
    "YourProfile": "Your Profile",
    "BillDescriptor": "Charges will appear on your bill as",
    "Add": "Add",
    "PaymentOption.sofort": "Sofort",
    "Email": "Email",
    "DeleteItem": "Remove",
    "Pay": "Pay",
    "JpConsumptionTaxAbout": "Prices and order total includes Consumption Tax.",
    "RegionAF": "Africa",
    "VolumeDiscountsAvailable": "Volume Discounts Available",
    "InactiveSubscriptions": "Inactive Subscriptions",
    "ConfirmUpdatePaymentMethod": "Are you sure you want to change your default payment method?",
    "Test": "Test",
    "CardExpired": "Your credit card has expired. Please try another card, or choose a different form of payment.",
    "EUVatExemptApplied": "Your company's VAT identification number has been applied, and VAT charges have been removed.",
    "SavingsTitle": "You Save",
    "Years": "years",
    "Failed": "Failed",
    "CardSecurityCodePlaceholder": "CVC",
    "EnterPaymentDetails": "Enter Payment Details",
    "For": "for",
    "Shipment": "Shipment",
    "Free": "Free",
    "ShippingStreet": "Address",
    "CardExpireMonth": "Card Expire Month",
    "FirstCharge": "First charge:",
    "PlaceYourOrder": "Place Your Order",
    "PaymentDetails": "Payment Details",
    "SubmitLocale": "Submit",
    "LastName": "Last Name",
    "Ending": "Ends on",
    "UnsupportedInTestMode": "Not supported while in testing mode.",
    "UseThis": "Use This",
    "Subscriptions": "Subscriptions",
    "Addons": "Addons",
    "Forbidden": "Could not validate provided information",
    "OrderEmpty": "Your Order Is Empty",
    "Continue": "Continue",
    "CardNumberPlaceholder": "Card Number",
    "BankPaymentWireInstructionDescription": "When paying by bank transfer, your product cannot be delivered until payment is received in full. After we receive payment, please allow 3 business days for processing.",
    "EUVatDialogTitle": "VAT Information",
    "ManageAccount": "Account Management",
    "SubscriptionManagement": "Full Terms and Subscription Management",
    "Abandonment.PurchaseWithDiscount": "Purchase With Discount",
    "Abandonment.CompleteYourOrder": "Complete Your Order",
    "NextCharge": "Next charge:",
    "CardCvvInvalid": "Your credit card security code (CVC) is invalid.",
    "PaymentType.wire": "Wire Transfer",
    "AccountManagement": "Account Management",
    "Coupon": "Coupon Code",
    "CouponCall": "Enter Promotional Code",
    "TaxInformationJp": "Includes Consumption Tax",
    "OrderOn": "Order on",
    "Cancelled": "Cancelled",
    "PaymentPending": "Payment Pending",
    "RegionAS": "Asia",
    "RegionAM": "Americas",
    "Every": "Every",
    "JpNationalTaxId": "National Tax ID",
    "PaymentType.free": "FREE",
    "Address": "Address",
    "ChooseCountry": "Choose Country",
    "AccountDetailsPaymentMethods": "Account Details and Payment Methods",
    "PostOrderExpectationDescription": "We are sending a copy of all important order information to your email address.",
    "Remove": "Remove",
    "OrderSubtotal": "Subtotal",
    "PaymentMethods": "Payment Methods",
    "BankPaymentWireInstructionViewNowButton": "View Instructions Now",
    "ConfirmOk": "Yes",
    "PaymentType.sepa": "Direct Debit",
    "CancelledAtBank": "Payment cancelled.",
    "AutoRenewCollectedInfomarion": "You payment information was securely stored for automatic renewals",
    "Debit": "Debit",
    "OrderSectionTitle": "Your Order",
    "PaymentOption.sepa": "Direct Debit",
    "EditProfile": "Edit Profile",
    "BankTransferNote": "When paying by bank transfer, your product cannot be delivered until payment is received in full. After we receive payment, please allow 3 business days for processing. Payment Instructions",
    "ConfirmCancel": "Cancel",
    "Card": "Card",
    "Calculating": "Calculating",
    "FreeTrialUntil": "Free trial until",
    "ShippingRegion": "State",
    "BankPaymentWireInstructionAccountNo": "Account No",
    "EUVatID": "VAT ID",
    "Next": "Next",
    "ShippingPostalCode": "Postal Code",
    "PaymentInformation": "Payment Information",
    "Country": "Country",
    "PayNow": "Pay Now",
    "Current": "Current",
    "JpConsumptionTaxDialogTitle": "Consumption Tax Information",
    "ActiveSubscriptions": "Active Subscriptions",
    "Complete": "Complete",
    "PaymentOption.giropay": "GiroPay",
    "PaymentType.amazon": "Pay with Amazon",
    "BankPaymentWireInstructionBank": "Bank",
    "JpConsumptionTaxtExemptInvalid": "Your company's National Tax ID could not be validated.",
    "PaymentType.paypal": "PayPal Checkout",
    "RenewsAutomatically": "Renews automatically by the seller",
    "BankPaymentWireInstructionDialogIntroduction": "Initiate a Bank Transfer via your own bank to:",
    "NoInactiveSubscriptions": "No inactive subscriptions",
    "PaymentOption.paypal": "PayPal Account",
    "ConfirmUpdateSubscriptionPaymentMethod": "Are you sure you want to change the default subscription payment method?",
    "EnterEmail": "Please enter your email address to continue",
    "RegionOC": "Oceania",
    "Footer.TrustedReseller": ", a trusted reseller for this store.",
    "PaymentSectionTitle": "Your Payment",
    "HideSubscriptionTerms": "Hide subscription terms",
    "Ended": "Ended",
    "PostOrderExpectationTitle": "Thank you for your order!",
    "YourOrderIs": "Your order is",
    "Manage": "Manage",
    "BankPaymentWireInstructionSwiftCode": "Swift-Code",
    "Default": "Default",
    "PaymentVariant.discover": "Discover",
    "PaymentOption.amazon": "Amazon",
    "LastCharge": "Last charge",
    "ShowHistory": "Show billing history",
    "Day": "day",
    "FailurePayPalCountryUpdate": "Your PayPal account's country was different.  We've updated your order using the country on your PayPal account.  Please review the total and try again.",
    "CardNumber": "Card Number",
    "SubscriptionTerms": "Subscription terms",
    "EnterTaxInformationEU": "Enter VAT ID",
    "PaymentOption.alipay": "Alipay",
    "PaymentVariant.amex": "American Express",
    "ApplyCoupon": "Apply",
    "Tax": "Tax",
    "ErrorChoosePaymentMethod": "Please choose a payment method.",
    "EndingWith": "Ending with",
    "ChooseLanguage": "Choose Language",
    "EmailFormInstructions": "Please enter the email address associated with this account",
    "PaymentType.giropay": "GiroPay",
    "ChooseLocale": "Choose Country / Language...",
    "TaxNotApplicable": "Not Applicable",
    "PaymentType.alipay": "Alipay",
    "BillingPostalCode": "Billing Postal Code",
    "CardSecurityCodeHint": "The CVC Number is a 3 digit number on the back of your card.",
    "PaymentType.sofort": "Sofort",
    "JpConsumptionTaxExemptInfo": "If you are placing an order on behalf of a company in Japan, enter the company's National Tax ID and the Consumption Tax charges will be removed.",
    "MailingListSubscribe": "Get free updates about our products and offerings",
    "RenewEvery": "renew every",
    "Refunded": "Refunded",
    "ShippingPhoneNumber": "Phone Number",
    "AndEndingOn": "and ending on",
    "TaxUS": "Tax",
    "Months": "months",
    "Footer.WeUse": "We use industry-standard encryption to protect the confidentiality of your personal information.",
    "RenewsEvery": "Renews every",
    "City": "City",
    "EUVatAbout": "Prices and order total includes VAT.",
    "CardSecurityCode": "Card Security Code",
    "OrderInvoice": "Order Invoice",
    "ConfirmTitle": "Confirm",
    "Price": "Price",
    "AddPaymentMethod": "Add Payment Method",
    "Save": "Save",
    "FailureRisk": "We regret that your order could not be accepted. We value your business and would like to help you complete this order. Please contact us for assistance.",
    "LightBox.InYourCart": "In your cart",
    "CouponInvalid": "The promotional code you entered does not exist.",
    "OrderContainsAdhoc": "Payment details will be kept for future orders.",
    "CardsAccepted": "We accept",
    "PaymentInformationTitle": "Payment Information",
    "PaymentOption.ideal": "iDEAL",
    "Updating": "Updating",
    "ManageYourOrders": "Manage Your Orders",
    "PaymentOption.card": "Credit / Debit Card",
    "UpdatePaymentMethod": "Update payment method",
    "Credit": "Credit",
    "BankPaymentWireInstructionPaymentReference": "Payment Reference",
    "OrderReference": "Order Reference",
    "Inactive": "Inactive",
    "UpgradeAndContinue": "Upgrade and continue!",
    "TaxInformationUS": "+Tax",
    "on": "on",
    "PaymentVariant.mastercard": "Mastercard",
    "Bundle": "Bundle",
    "PrivacyPolicy": "Privacy Policy",
    "JpNationalTaxIdSubmit": "Submit",
    "Quantity": "Quantity",
    "RegionEUR": "Europe",
    "YourOrders": "Your Orders",
    "DownloadAction": "Download Now",
    "InvoiceLinkText": "View Invoice",
    "Today": "today",
    "CardExpireMonthPlaceholder": "MM",
    "ConfirmRemovePaymentMethod": "Are you sure you want to remove the payment method?",
    "ShippingAddress": "Shipping Address",
    "Total": "Total",
    "FailureGeneric": "An unexpected error occurred, and we are not currently able to accept payment.",
    "EUVatIDSubmit": "Submit",
    "OrderTotal": "Total",
    "On": "on"
  },
  "locks": [],
  "paymentOptions": [],
  "promotionOptions": [],
  "session": {
    "location": "https://localhost:8443/bm-store/demo*/session/demo",
    "sandbox": "https://localhost:8443/bm-store/demo**sandbox",
    "token": "new/1pCZzub0Ti0bVyHM3l337w",
    "primary": "demo",
    "id": "demo",
    "live": false
  },
  "variables": {
    "integrationBehaviourGA": "default",
    "collectingEmailCheckbox": "true",
    "cartCrossSellsPositionProduct": "belowdriver",
    "purchaseBtn": "addToCart",
    "confirmCancelBtnFontSize": "14px",
    "showCouponField": "true",
    "productImageSize": "large",
    "crossSellsPositionProduct": "belowdriver",
    "nortonDisplay": "large",
    "upSellsDisplay": "page",
    "popupHeadingAlign": "left",
    "showCompanyField": "disable",
    "offerTitleSize": "16px",
    "showVatLink": "true",
    "topbarFreezing": "false",
    "listUpSellsDisplay": "page",
    "upSellsPosition": "below",
    "cartUpSellsDisplay": "page",
    "panelHeaderTextColor": "#333",
    "countrySelector": "visible",
    "offerImageSizeInsideCart": "medium",
    "listUpSellsPosition": "below",
    "popupOnWindowClose": "false",
    "integrationBehaviourGTM": "default",
    "productTitle": "showDescription",
    "licenses": "true",
    "cartUpSellsPosition": "below",
    "requireEmail": "false",
    "panelHeaderColorNew": "#f5f5f5",
    "font": "Helvetica-Neue",
    "offerImageSizeOutsideCart": "large",
    "listCrossSellsPositionProduct": "belowdriver",
    "logo": "https://localhost:8443/icon.png"",
    "subscriptionUsePaymentMethodBtnFontSize": "14px",
    "popupTimeout": "10",
    "priceSize": "large",
    "showListCheckbox": "false",
    "textAlign": "left",
    "productTitleSize": "18px",
    "managePaymentMethodBtnFontSize": "14px",
    "popupTextAlign": "left",
    "forcePhoneNumberCollection": "false",
    "couponFieldExpanded": "true",
    "shortCheckout": "true",
    "savePaymentDetailsBtnFontSize": "14px",
    "footer": "© 1999-2020 Acme, Inc.. All rights reserved.",
    "popupOnTimeout": "false",
    "title": "Acme Store",
    "addPaymentMethodBtnFontSize": "12px",
    "forcePhysicalAddressCollection": "false",
    "popupButtonAlign": "left",
    "confirmOkBtnFontSize": "14px",
    "addToCartBtnFontSize": "14px",
    "crossSellsPositionStorefront": "below",
    "showEmailOnCartPage": "both",
    "manageSubscriptionBtnFontSize": "14px"
  },
  "country": "US",
  "countryDisplay": "United States",
  "countryRequiresPostalCode": true,
  "countryRequiresRegion": true,
  "language": "en",
  "languageDisplay": "English",
  "defaultLanguage": true,
  "live": false,
  "hasAccount": false
}

 

Example functions

The following are two variations of a function that calculates the total number of physically shippable items in an order. You can add these functions to any script.

Total quantity of physical items in the order including individual products within any bundle
function getTotalQuantity() {
  // This function gets the total quantity of physical items in the
  // order and it counts the number of products in a bundle.
  var count = 0;
  var groups = order.groups;
  for (var i = 0; i < groups.length; i++) {
    var items = groups[i].items;
    for (var j = 0; j < items.length; j++) {
      if (items[j].selected) {
        if (items[j].bundle) {
          var bundleItems = items[j].groups[0].items;
          for (var k = 0; k < bundleItems.length; k++) {
            if (bundleItems[k].productFormat === 'physical' || bundleItems[k].productFormat === 'digital-and-physical') {
              count += bundleItems[k].quantity;
            }
          }
        } else {
          if (items[j].productFormat === 'physical' || items[j].productFormat === 'digital-and-physical') {
            count += items[j].quantity;
          }
        }
      }
    }
  }
  return count;
}

 

Total quantity of physical items in the order, with bundles treated as a single product
function getTotalQuantity() {
  // This function gets the total quantity of physical items in the
  // order but it only treats bundles as one product.
  var count = 0;
  var groups = order.groups;
  for (var i = 0; i < groups.length; i++) {
    var items = groups[i].items;
    for (var j = 0; j < items.length; j++) {
      if (items[j].selected) {
        if (items[j].bundle) {
          var hasPhysicalProducts = false;
          var bundleItems = items[j].groups[0].items;
          for (var k = 0; k < bundleItems.length; k++) {
            if (bundleItems[k].productFormat === 'physical' || bundleItems[k].productFormat === 'digital-and-physical') {
              hasPhysicalProducts = true;
              break;
            }
          }
          if (hasPhysicalProducts) {
            count += items[j].quantity;
          }
        } else {
          if (items[j].productFormat === 'physical' || items[j].productFormat === 'digital-and-physical') {
            count += items[j].quantity;
          }
        }
      }
    }
  }
  return count;
}

Advanced Example:  Suppose your script calculates the quantity of shippable items in the order, but you need to exclude certain specific physical items from being counted. To do this, you can specify a product attribute and then check for that attribute in your shipping fee calculator script. For example, if you include the cost of shipping in the price of a "CD backup" product–and you do not want to charge shipping for it separately–you might add an attribute with a key such as "cdbackup." The following example function would exclude products with the attribute "cdbackup" from the quantity calculation.

 Note

The product attribute key can be any string you like; "cdbackup" is just an example. As another example, you could set a product attribute with a key of "noshipping" and a value of "true." You would just need to adjust the following example script accordingly.
Example of excluding a physical product from the quantity calculation based on a product attribute
function getTotalQuantity() {
    // This function gets the total quantity of physical items in the
    // order but it only treats bundles as one product.
    var count = 0;
    var groups = order.groups;
    for (var i = 0; i < groups.length; i++) {
        var items = groups[i].items;
        for (var j = 0; j < items.length; j++) {
            if (items[j].selected) {
                if (items[j].bundle) {
                    var hasPhysicalProducts = false;
                    var bundleItems = items[j].groups[0].items;
                    for (var k = 0; k < bundleItems.length; k++) {
                        if (bundleItems[k].productFormat === 'physical' || bundleItems[k].productFormat === 'digital-and-physical') {
                            hasPhysicalProducts = true;
                            break;
                        }
                    }
                    if (hasPhysicalProducts) {
                        count += items[j].quantity;
                    }
                } else {
                    if ((items[j].productFormat === 'physical' || items[j].productFormat === 'digital-and-physical') && ((items[j].attributes && !items[j].attributes.cdbackup ) || !items[j].attributes)) {
                        count += items[j].quantity;
                    }
                }
            }
        }
    }
    return count;
}


var totalQuantity = getTotalQuantity();
if(totalQuantity == 0) {
    return false;
} else {
    return totalQuantity;
}

 

Example scripts

The following are examples of complete shipping fee calculation scripts.

Example Script #1
// Uses a getTotalQuantity function as provided in the examples above.
 
var thisCountry = (typeof order.country === 'undefined') ? 'US' : order.country;
var shippingPrice = {};
if (thisCountry === 'US') {
  shippingPrice.usd = 12;
  shippingPrice.eur = 15;
} else if (thisCountry === 'CA') {
  shippingPrice.usd = 27.99;
  shippingPrice.eur = 29;
} else {
  shippingPrice.usd = 47.99;
  shippingPrice.eur = 49;
}
 
// Add $3 for each addtional unit after the first
var additionalUnitPrice = (3 * (getTotalQuantity() - 1));
shippingPrice.usd += additionalUnitPrice;
shippingPrice.eur += additionalUnitPrice;
 
return shippingPrice;
Example Script #2
// Uses a getTotalQuantity function as provided in the examples above.

var totalQuantity = getTotalQuantity();
if (totalQuantity <= 3) {
  // Charge $10 USD for quantities up to 3
  return 10;
} else if (totalQuantity <= 6) {
  // Charge $15 USD and 20 EUR for quantities 4-6
  return {
    "USD": 15,
    "EUR": 20
  };
} else {
  // Charge $20 USD and 20 EUR for quantities 7 or more
  return {
    "USD": 20,
    "EUR": 20
  };
}
Example Script #3
// Shipping will cost $0 USD when the order is greater than $100 and $7 otherwise
if (order.totalValue > 100) {
  return 0;
} else {
  return 7;
}

Advanced Example: Suppose you want to allow customers to select custom shipping methods, and you need your script to return estimated shipping costs accordingly. If you use Store Builder Library functions to create the shopping cart interface and pre-populate custom order tags (e.g., using fastspring.builder.tag(key,value)), your script can calculate a total estimated shipping cost for all products based on the selected shipping method. The following example would work if you passed a custom order tag with a key of "shipping" and a value of either "UPS," "FedEx," or "USPS" – for example, fastspring.builder.tag("shipping", "USPS");

Example Script #4
if(order.tags.shipping === 'UPS') {
  return 10;
} else if(order.tags.shipping === 'FedEx') {
  return 12;
} else if(order.tags.shipping === 'USPS') {
  return 7;
} else {
  return 5;
}

 

For Stores that have shipping charges enabled and a script with shipping amounts, adding a physical product to the cart via a Popup Storefront causes the shipping charges to be included in the order total automatically.

If you have enabled the optional Popup Storefront cart, the estimated shipping fee charges appear as a separate line item in the cart.

If you opt to create a shopping cart page using the Store Builder Library, you can access and display the shipping charges using the product path SystemExtension.shippingcalculation.

 Tip

When designing a custom shopping cart, bear in mind that the shipping fee charges line item is treated the same as any other product. By default, it would be included in any loop you design to cycle through the order items. If you do not want the shipping charges to be displayed together with each of the order products, you may want to exclude the SystemExtension.shippingcalcultion from your loop explicitly. To create a separate line with the shipping charge amount (e.g., below a subtotal), you can optionally include a separate loop outside the main cart contents area that explicitly excludes everything else except the shipping charges. Then, render only the charge amount (i.e., not the product's display name or a remove control). For an example of how you could code this, please inspect the SBL cart example found at https://fastspringexamples.com/product-type/physical-product/.