Purchase Script

Application to send Bold Metrics your Purchase data from the browser.

The Purchase API is designed to collect purchase data as it relates to the usage of the Smart Size Chart & Virtual Sizer API. We log all purchases sent and are able to match them to recommendations to provide additional analysis.

Implementation

Shopify Sites

Please note: there are two paths for Shopify sites: a Checkout Extensibility pixel as well as the Legacy Path which uses the Additional Scripts path.

If you have upgraded to Checkout Extensibility, please follow the first path, otherwise follow the legacy path. If you upgrade to Checkout Extensibility at a later date, please note you will have to add the Extensibility Pixel once you upgrade to Checkout Extensibility to maintain data integrity. IMPORTANT: Choose only one option below that fits your needs. Adding both options at the same time to your Shopify site will result in duplicate purchases and will affect data integrity. If you have questions, please don't hesitate to contact the Bold Metrics Engineering Support team.

OPTION 1: Checkout Extensibility Pixel

  1. Open the Customer Events panel in your Shopify admin. It can be found at this link: https://admin.shopify.com/settings/customer_events

  2. From the Customer Events panel, click the button in the upper right corner of the page which says 'Add Custom Pixel'.

  3. Name the custom pixel: 'Bold Metrics - Purchases'. This will take you to a screen where you can paste in a custom pixel.

  4. Copy and paste the below code in the code block box and then click Save in the upper right corner of the screen. Then, click the Connect button to activate the pixel.

Note: you must fill the client_id field with the value provided to you by the Bold Metrics engineering support team.

(function(d,s){let f=d.getElementsByTagName(s)[0];let j=d.createElement(s);j.async=true;j.src="https://d2yc9u4j5yz48x.cloudfront.net/purchase.pixel.js";f.parentNode.insertBefore(j,f);})(document,'script');
window.bmiFallback=function(e,c,b){return new Promise(function(f,g){b.localStorage.getItem("boldMetricsRecIds").then(function(h){b.cookie.get("bm").then(function(i){var j={rec_ids:JSON.parse(h)||h,user_id:i,transaction_id:e.data.checkout.order.id,client_id:c},k=new XMLHttpRequest;k.open("POST","https://web-api.boldmetrics.io/purchase",!0),k.setRequestHeader("Content-Type","application/json;charset=UTF-8"),k.onload=function(){k.status>=200&&k.status<300?f(k.response):g(k.statusText)},k.onerror=function(){g(k.statusText)},k.send(JSON.stringify(j))}).catch(g)}).catch(g)})}

analytics.subscribe("checkout_completed", async (event) => {
  // note, `browser` is a global variable in Shopify Analytics
  const client_id = 'YOUR BOLDMETRICS CLIENT ID';
  try {
    await window.bmiWriteTransaction(event, client_id, browser);
  } catch (_) {
    await window.bmiFallback(event, client_id, browser)
  }
});
  1. In the options for the pixel, there may be options for Customer Privacy. Under the 'Permission' option, select 'Not Required' (we are not collecting customer data for marketing, analytics or preferences purposes), and under the 'Data Sale' option, select 'Data collected does not qualify as data sale'.

OPTION 2: Legacy Path (Additional Scripts)

  1. Navigate to Settings > Checkout > Additional scripts.

  2. Paste the following scripts into the textfield:

    <script type="text/javascript" src="https://d2yc9u4j5yz48x.cloudfront.net/purchase.js"></script>
    <script>
       const data = {
           client_id: "{{shop.name}}".toLowerCase(),
           transaction_id: "{{ checkout.order_id }}",
           shipping_price: "{{ checkout.shipping_price }}"/100,
           currency: "{{ checkout.currency }}",
           total_price: "{{ checkout.total_price }}"/100,
           city: "{{ checkout.billing_address.city }}",
           postal_code: "{{ checkout.billing_address.zip }}",
           country_code: "{{ checkout.billing_address.country_code }}",
           purchases: []
       };
    
    
       
    {% for line_item in checkout.line_items %}
           data.purchases.push({
               product_name: "{{ line_item.title }}",
               product_id: "{{ line_item.product.title }}",
               product_tags: "{{ line_item.product.tags }}",
               category: "{{ line_item.product.type }}",
               size: "{{ line_item.variant.title }}",
               msrp: "{{ line_item.original_price }}"/100,
               sale_price: "{{ line_item.final_price }}"/100,
               quantity: "{{ line_item.quantity }}",
               variant_id: "{{ line_item.variant.id }}",
               variant_sku: "{{ line_item.variant.sku }}"
           })
       {% endfor %}
    
    
       if (!!window.bmiWriteTransaction && typeof window.bmiWriteTransaction == 'function') {
           window.bmiWriteTransaction(data).then(res => {
               const masthead = `:::::BMI Purchase API:::::`;
               const response = JSON.parse(res);
               if (response.statusCode == 200) {
                   console.log(`%c${masthead} ${response.message}`, 'color: magenta');
               } else {
                   console.error(`%c${masthead} ${response}`, 'color: red');
               }
           });
       }
    </script>
  3. Send your Bold Metrics representative an order confirmation URL for internal testing purposes.

Non-Shopify Sites

The first step is to add a script to your order confirmation page:

<script type="text/javascript" src="https://d2yc9u4j5yz48x.cloudfront.net/purchase.js"></script>

This exposes the window.bmiWriteTransaction function which can be used to pass transaction data to. See the below example:

const data = {
    'client_id': '<STORE NAME>',
    'transaction_id': '<TRANSACTION NUMBER>',
    'shipping_price': '<SHIPPING PRICE>',
    'currency': '<CURRENCY>',
    'total_price': '<TOTAL PRICE>',
    'zip': '<ZIP>',
    'city': '<CITY>',
    'country_code': '<COUNTRY CODE>',
    'purchases': [
        {
            'product_name': '<PRODUCT NAME>',
            'product_id': '<PRODUCT ID>',
            'variant_id': '<VARIANT ID>',
            'variant_sku': '<VARIANT SKU>',
            'category': '<PRODUCT CATEGORY>',
            'size': '<PRODUCT SIZE>',
            'quantity': '<PRODUCT QUANTITY>',
            'msrp': '<MSRP>',
            'sale_price': '<SALE PRICE>',

        },
        {
            ...
        }
    ]
}
window.bmiWriteTransaction(data).then(res => console.log(res))

This function returns a promise and is thenable, which allows the client to get the API response to confirm data has been written. See below for additional information on the Purchase API payload.

This script will also collect a user_id in cookies that the either the analytics script or the SSC script sets .

Purchase API Payload
  • client_id (string): (required) The name of your store. This value will be provided to you by your Bold Metrics representative.

  • transaction_id (string): (required) This is the transaction that just occurred. This allows us to match the purchase transaction to a potential return.

  • shipping_price (string): (required) This is the price of shipping, if applicable.

  • currency (string): (required) This is the type of currency used (e.g. USD).

  • total_price (string): (required) This is the total price of the order.

  • zip (string): (required) This is the shipping zip code.

  • city (string): (required) This is the shipping city.

  • country_code (string): (required) This is the country the purchased items were shipped to (e.g. US)

  • anon_id (string): (required) A anonymous ID to identify a user. PLEASE DO NOT PASS PII.

  • purchases (string): (required) This is an array or list of objects, each object containing a product_id, category, and size. Each object must include these fields or the API call will fail.

    • product_name (string): (required) The name of the product.

    • product_id (string): (required) This is the product id that was purchased. This field should match the title on the PDP and the product_id in the product feed.

    • variant_id (string): (required) The variation id, if applicable.

    • variant_sku (string): (required) The variation sku, if applicable.

    • category (string): (required) This is the category of the product purchased. This field should match the category on the PDP.

    • size (string): (required) This is the size of the product purchased.

    • quantity (string): (required) This is the item count.

    • msrp (string): (required) The MSRP value, if applicable.

    • sale_price (string): (required) This is the price of the individual item.

Send your Bold Metrics representative an order confirmation URL for internal testing purposes.

Purchase Templates

The below sheets contain the data Bold Metrics requires to validate that the above script was implemented correctly. This allows us to do a 'quality check' to verify that we're getting purchase data correctly, so we can provide reporting.

Once you go live with either the API or Smart Size Chart, we'll request 3 days of purchase data to validate that we have parity between your purchase data and our newly collected data coming from the purchase script above.

Bold Metrics will validate this comparison and will report that we are getting the appropriate purchase data.

Logging & Monitoring

It's a recommended best practice to both log and monitor this script. Once data is posted to window.bmiWriteTransaction, Bold Metrics will receive these records if the call was successful, however, we will not receive this data if the call was not successful.

Adding a monitoring utility will help both teams identify purchases that may not have successfully been posted to Bold Metrics.

Troubleshooting

For most issues you may encounter, there is likely an associated error in the console. To open the console in your browser, press Cmd + Alt + i (Firefox & Chrome). If there is an error, the promise will return an error message.

Some common issues are around sending the proper data contract. See the above example for the acceptable data contract. We validate for all of the above fields, so please submit requests as seen above.

In addition, we also validate for a cookie with the name bm and that it has a value. This is automatically set by the Smart Size Chart application if it’s used on your site, and without it, you may need to manually set this cookie during testing to receive a 200 from the API. In order for the Smart Size Chart to set a cookie value, you’ll need to visit the application for the cookie to be set.

Last updated