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

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, i.e. replace the text that says "YOUR CLIENT ID GOES HERE" wioth your actual client id.


(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) => {
  const client_id = "YOUR CLIENT ID GOES HERE";
// Wait for data to be set
  await new Promise((resolve) => {
    setTimeout(() => {
      window.bmiPurchaseData = { event, client_id, browser };
      resolve();
        }, 2000);
    });
  try {
    const { event, client_id, browser
        } = window.bmiPurchaseData;
    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'.

Non-Shopify Sites

The first step is to add the script below to your order confirmation page. Note: It is very important that we receive all of the data listed below.

<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. Please see below, all fields listed below are REQUIRED:

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