Display Local Pricing using Pricing API

Overview

This guide shows you how integrate Pricing API to your frontend to include local pricing.

The result:

Implement Pricing API

Before you start

To integrate the Pricing API into your frontend, you'll need:

  1. CleverAPI Script.
  2. Sample CSS.

Clever API Script

/*! integrationJquery - v2.0.1 - 2018-01-10 */
/* updated 2019-03-28 for monthly prices */

"use strict";

(function(factory) {
    if (typeof define === "function" && define.amd) {
        define([ "jquery" ], factory);
    } else if (typeof exports === "object") {
        module.exports = factory(require("jquery"));
    } else {
        factory(jQuery || Zepto);
    }
})(function($) {
    var settings = {};
    var defaults = {
        verbose: false,
        productIDs: [],
        version: "2.0.1",
        useBrowserLanguage: false,
        browserLanguage: window.navigator.userLanguage || window.navigator.language || "en",
        currency: null,
        country: null,
        price_rule: null,
        client_id: null,
        coupon: null,
        delay: 0,
        debug: true,
        endpoint: "//pricingapi.cleverbridge.com/prices",
        product_id_property: "product_id",
        fragments: {
            notFound: '<span style="background:red;color:white">cannot find product with ID: {{cleverApi-pid}}</span>',
            unknownTag: '<span style="background:red;color:white">unknown css class: {{cleverApi-tag}}</span>',
            loading: '<div class="clever-bounce1"></div><div class="clever-bounce2"></div><div class="clever-bounce3"></div>',
            loadingRemove: ".clever-bounce1,.clever-bounce2,.clever-bounce3"
        },
        cleverTags: {
            name: "product.name",
            clientProductId: "product.client_product_id",
            additionalName: "product.additional_name",
            description: "product.description",
            shortDescription: "product.short_description",
            operatingSystem: "product.operating_system",
            systemRequirements: "product.system_requirements",
            currency: "currency.iso",
            currencySymbol: "currency.symbol",
            priceNet: "price.net.value",
            priceNetLocalized: "price.net.localized",
            priceGross: "price.gross.value",
            priceGrossLocalized: "price.gross.localized",
            vatRate: "vat_rate.value",
            vatRateLocalized: "vat_rate.localized",
            priceVat: "price.vat.value",
            priceVatLocalized: "price.vat.localized",
            listprice: "list_price.value",
            listpriceLocalized: "list_price.localized",
            discountAbsolute: "discount.absolute.value",
            discountAbsoluteLocalized: "discount.absolute.localized",
            discountPercentage: "discount.percentage.value",
            discountPercentageLocalized: "discount.percentage.localized",
			monthlyPriceNet: "monthly_price.net.value",
            monthlyPriceNetLocalized: "monthly_price.net.localized",
            monthlyPriceGross: "monthly_price.gross.value",
            monthlyPriceGrossLocalized: "monthly_price.gross.localized",
        },
        selector: {
            base: "cleverApi",
            classLoaded: "cleverApi-loaded",
            classLoadedFailed: "cleverApi-loaded-failed",
            tag: '[class*="cleverApi-"]',
            regex: /cleverApi-(\d+)-(\w+)/i
        }
    };
    var data = {
        productIDs: [],
        products: false
    };
    function getQueryParameter(name) {
        var results = new RegExp("[?&amp;]" + name + "=([^&amp;#]*)").exec(window.location.href);
        return results !== null ? results[1] : null;
    }
    var plugin = {};
    plugin.checkJquery = function() {
        if (!$) {
            console.log("cleverbridge cleverApi needs jQuery to run - http://code.jquery.com/ ");
            return false;
        }
        return true;
    };
    plugin.verbose = function(msg) {
        if (settings.verbose) {
            arguments[0] = "[cleverApi] " + arguments[0];
            console.info.apply(console, arguments);
        }
    };
    plugin.wait = function() {
        plugin.verbose("waiting for " + settings.delay + "ms");
        var defered = $.Deferred();
        setTimeout(function() {
            plugin.verbose("waiting end ");
            return defered.resolve();
        }, settings.delay || 0);
        return defered;
    };
    plugin.setupLoadingIndicator = function() {
        plugin.verbose("prepare loading indicators");
        $("." + settings.selector.base).html(settings.fragments.loading);
        return $.Deferred().resolve();
    };
    plugin.removeLoadingIndicator = function() {
        plugin.verbose("remove loading indicators");
        $(settings.fragments.loadingRemove).remove();
        return $.Deferred().resolve();
    };
    plugin.storeData = function(pdata) {
        plugin.verbose("store received data", pdata);
        data.products = pdata;
        return $.Deferred().resolve();
    };
    plugin.getData = function() {
        plugin.verbose("return price data");
        return $.Deferred().resolve(data.products);
    };
    plugin.request = function(params) {
        plugin.verbose("start request:", settings.endpoint + "?" + params);
        return $.ajax({
            timeout: 1e4,
            url: settings.endpoint + "?" + params,
            type: "GET",
            dataType: "json",
            beforeSend: function(xhr) {
                if (settings.useBrowserLanguage) {
                    plugin.verbose("setting browserLanguage", settings.browserLanguage);
                    xhr.setRequestHeader("accept-language", settings.browserLanguage);
                }
            }
        }).done(function(data) {
            plugin.verbose("got data:", data);
        }).fail(function(err) {
            console.log("error:", settings.endpoint, "- code:", err.status, err.statusText);
        });
    };
    plugin.processData = function(requestData) {
        var data = {};
        function addData(items) {
            var i;
            for (i = 0; i < items.length; i++) {
                if (!Array.isArray(items[i])) {
                    data[items[i][settings.product_id_property]] = items[i];
                } else {
                    addData(items[i]);
                }
            }
        }
        addData(requestData);
        return data;
    };
    plugin.whenAll = function(promises) {
        var i;
        var data = [];
        var deferedAll = $.Deferred();
        for (i = 0; i < promises.length; i++) {
            promises[i].done(function(newData) {
                data.push(newData);
                if (data.length == promises.length) {
                    deferedAll.resolve(data);
                }
            }).fail(function() {
                data.push("NO DATA");
                if (data.length == promises.length) {
                    deferedAll.resolve(data);
                }
            });
        }
        return deferedAll.promise();
    };
    plugin.getProductData = function() {
        var requests = [];
        plugin.verbose("collect product IDs from settings.productIDs", settings.productIDs);
        data.productIDs = $.merge(data.productIDs, settings.productIDs);
        for (var i = 0; i < data.productIDs.length; i++) {
            var p = {};
            p.product_id = data.productIDs[i];
            p.client_id = settings.client_id;
            if (settings.country !== null) {
                p.country = settings.country;
            }
            if (settings.price_rule !== null) {
                p.price_rule = settings.price_rule;
            }
            if (settings.currency !== null) {
                p.currency = settings.currency;
            }
            var coupon = getQueryParameter("coupon") || settings.coupon;
            if (coupon !== null) {
                p.coupon = coupon;
            }
            requests.push(plugin.request($.param(p)));
        }
        return plugin.whenAll(requests).then(plugin.processData);
    };
    plugin.collectProductIDs = function() {
        $(settings.selector.tag).each(function(index, element) {
            var match = settings.selector.regex.exec(element.className);
            if (match) {
                data.productIDs.push(match[1]);
            }
        });
        $.unique(data.productIDs);
        plugin.verbose("collecting product IDs from CSS", data.productIDs);
        return $.Deferred().resolve();
    };
    plugin.getJsonData = function(data, path) {
        if (!path) {
            return false;
        }
        var parts = path.split(".");
        $.each(parts, function(index, part) {
            data = data && data[part];
        });
        if (!data && data !== 0) {
            return undefined;
        }
        if (typeof data === "object") {
            return null;
        }
        return data;
    };
    plugin.parsePlaceholder = function() {
        var tagInfos, tagValue;
        $(settings.selector.tag).each(function(index, element) {
            tagInfos = settings.selector.regex.exec($(element).attr("class"));
            if (!tagInfos) {
                return;
            }
            tagValue = plugin.getJsonData(data.products[tagInfos[1]], settings.cleverTags[tagInfos[2]]);
            if (tagValue === null || tagValue === undefined) {
                $("." + tagInfos[0].replace(settings.selector.base, settings.selector.base + "-hide")).css("display", "none");
            }
            $(element).addClass(settings.selector.classLoaded);
            if (tagValue || tagValue === 0) {
                $(element).append(tagValue);
            } else if (tagValue === undefined) {
                $(element).html(settings.fragments.notFound.replace("{{cleverApi-pid}}", tagInfos[1]));
                $(element).addClass(settings.selector.classLoadedFailed);
            } else if (tagValue === false) {
                $(element).html(settings.fragments.unknownTag.replace("{{cleverApi-tag}}", tagInfos[0]));
                $(element).addClass(settings.selector.classLoadedFailed);
            }
        });
        return $.Deferred().resolve();
    };
    if (!plugin.checkJquery) {
        return;
    }
    $.extend({
        cleverApi: {
            methods: plugin,
            settings: settings,
            defaults: defaults,
            data: data,
            version: defaults.version,
            get: function(options) {
                settings = $.extend(defaults, options);
                if (settings.verbose) {
                    console.info("Verbose mode: ON");
                }
                return plugin.setupLoadingIndicator().then(plugin.collectProductIDs).then(plugin.getProductData).then(plugin.storeData).then(plugin.wait).then(plugin.removeLoadingIndicator).then(plugin.parsePlaceholder).then(plugin.getData);
            }
        }
    });
});

Sample CSS

.cleverApi {
  min-width: 3em;
  text-align: center;
}
.cleverApi > div {
  width: 8px;
  height: 8px;
  background-color: #333;
  border-radius: 100%;
  display: inline-block;
  -webkit-animation: bouncedelay 1.4s infinite ease-in-out;
  animation: bouncedelay 1.4s infinite ease-in-out;
  -webkit-animation-fill-mode: both;
  animation-fill-mode: both;
}
.cleverApi .clever-bounce1 {
  -webkit-animation-delay: -0.32s;
  animation-delay: -0.32s;
}
.cleverApi .clever-bounce2 {
  -webkit-animation-delay: -0.16s;
  animation-delay: -0.16s;
}
@-webkit-keyframes bouncedelay {
  0%,
  80%,
  100% {
    -webkit-transform: scale(0);
  }
  40% {
    -webkit-transform: scale(1);
  }
}
@keyframes bouncedelay {
  0%,
  80%,
  100% {
    transform: scale(0);
    -webkit-transform: scale(0);
  }
  40% {
    transform: scale(1);
    -webkit-transform: scale(1);
  }
}

Parameters

ParameterTypeRequiredExample
client_idstringYes864
product_idstringYes97771

Example request

curl --request GET \
     --url 'https://pricingapi.cleverbridge.com/prices?client_id=864&product_id=97771&currency=USD&country=US&coupon=BD3-1KK-UN3' \
     --header 'Accept-Language: en-US' \
     --header 'accept: application/json'
from urllib.request import urlopen

url = "https://pricingapi.cleverbridge.com/prices?client_id=864&product_id=97771&currency=USD&country=US&coupon=BD3-1KK-UN3"

response = urlopen(url)
print(response.read().decode('utf-8'))
const https = require('https');

const url = 'https://pricingapi.cleverbridge.com/prices?client_id=864&product_id=97771&currency=USD&country=US&coupon=BD3-1KK-UN3';

https.get(url, (res) => {
  let data = '';
  res.on('data', (chunk) => data += chunk);
  res.on('end', () => console.log(JSON.parse(data)));
}).on('error', (error) => console.error('Error:', error.message));

Example response

[
    {
        "client_id": "864",
        "product_id": "97771",
        "coupon": "BD3-1KK-UN3",
        "locale": "en-US",
        "list_price": {
            "net": {
                "localized": "$5.99",
                "value": 5.99
            },
            "gross": {
                "localized": "$5.99",
                "value": 5.99
            },
            "vat": {
                "localized": "$0.00",
                "value": 0
            }
        },
        "discount": {
            "absolute": {
                "net": {
                    "localized": "$4.99",
                    "value": 4.99
                },
                "tax": {
                    "localized": "$0.00",
                    "value": 0
                },
                "gross": {
                    "localized": "$4.99",
                    "value": 4.99
                },
                "vat": {
                    "localized": "$0.00",
                    "value": 0
                }
            },
            "percentage": {
                "value": 83.31,
                "localized": "83%"
            }
        },
        "currency": {
            "symbol": "$",
            "iso": "USD"
        },
        "price": {
            "net": {
                "localized": "$1.00",
                "value": 1
            },
            "gross": {
                "localized": "$1.00",
                "value": 1
            },
            "vat": {
                "localized": "$0.00",
                "value": 0
            }
        },
        "monthly_price": {
            "net": {
                "localized": "$0.08",
                "value": 0.08
            },
            "gross": {
                "localized": "$0.08",
                "value": 0.08
            },
            "vat": {
                "localized": "$0.00",
                "value": 0
            }
        },
        "product": {
            "name": "Internet Security Basic Extended",
            "additional_name": "For your home",
            "short_description": "Internet Security Basic Extended offers virus protection, anti-phishing tools, mail protection, and identity theft protection. ",
            "description": "Internet Security Basic Extended offers virus protection, anti-phishing tools, mail protection, and identity theft protection. ",
            "system_requirements": "867 MHz or faster processor\r\n512MB of RAM; 1GB recommended",
            "client_product_id": "UUID-YOUR-UNIQUE-ID-1234-5678"
        },
        "price_country": "US",
        "vat_rate": {
            "value": 0,
            "localized": "0%"
        }
    }
]

STEP 1: Add sample CSS

To load CSS, enter the following into the head of the HTML page:

<link rel="stylesheet" href="{BASE_API_URL}/cleverApi.css" type="text/css">
<link rel="stylesheet" href="https://pricingapi.cleverbridge.com/cleverApi.css" type="text/css">

STEP 2: Add cleverAPI script

Add cleverAPI script at the bottom of the HTML page. Make sure to set up your Cleverbridgeclient_idand required currency using the corresponding three-letter ISO code:

<script src="//code.jquery.com/jquery-1.11.3.min.js"></script>
<script src="{BASE_API_URL}cleverApi.js"></script>
<script>
  $(document).ready(function() {
  $.cleverApi.get({
    'currency': 'USD',
    client_id: 8
  });
});
</script>

STEP 3: Set Up the API Endpoint

To set up the API endpoint, send the following to the cleverApi script at startup:

$(document).ready(function() {
      $.cleverApi.get({
        'endpoint': {
          URL_TO_API
        }
        /prices'});
      });

STEP 4: Add CSS classes

Add CSS classes to the relevant HTML tags:

<p><label>currency:</label><b class="cleverApi cleverApi-1-currency"></b></p>
<!-- cleverApi Indicates that the price information is used here -->

<p><label>currencySymbol:</label><b class="cleverApi cleverApi-1-currencySymbol"></b></p>
<!-- The currency symbol is displayed  -->

<p><label>priceNetLocalized:</label><b class="cleverApi cleverApi-1-priceNetLocalized"></b></p>
<!-- The net price information is displayed -->

<p><label>discountAbsolute:</label><b class="cleverApi cleverApi-1-discountAbsolute"></b></p>
<!-- The absolute discount is displayed-->

<p><label>discountAbsoluteLocalized:</label><b class="cleverApi cleverApi-1-discountAbsoluteLocalized"></b></p>
<!--The localized absolute discount is displayed -->

<p><label>discountPercentage:</label><b class="cleverApi cleverApi-1-discountPercentage"></b></p>
<!-- The discount percentage is displayed -->

<p><label>discountPercentageLocalized:</label><b class="cleverApi cleverApi-1-discountPercentageLocalized"></b></p>
<!-- The localized discount percentage is displayed -->

List of CSS classes

CSS ClassFunction
cleverApiIndicates that the price information is used here
cleverApi-loadedAfter price loading, the clever CSS class is changed to clever-loaded
cleverApi-{product_id}-listpriceThe list price information is displayed
cleverApi-{product_id}-listpriceLocalizedThe localized list price information is displayed
cleverApi-{product_id}-priceGrossThe gross price information is displayed
cleverApi-{product_id}-priceGrossLocalizedThe localized gross price information is displayed
cleverApi-{product_id}-priceNetThe net price information is displayed
cleverApi-{product_id}-priceNetLocalizedThe localized net price information is displayed
cleverApi-{product_id}-priceVatThe vat price information is displayed
cleverApi-{product_id}-priceVatLocalizedThe localized vat price information is displayed
cleverApi-{product_id}-currencyThe currency ISO code is displayed
cleverApi-{product_id}-currencySymbolThe currency symbol is displayed
cleverApi-{product_id}-vatRateThe VAT rate is displayed
cleverApi-{product_id}-vatRateLocalizedThe localized VAT rate value is displayed
cleverApi-{product_id}-discountAbsoluteThe absolute discount is displayed
cleverApi-{product_id}-discountAbsoluteLocalizedThe localized absolute discount is displayed
cleverApi-{product_id}-discountPercentageThe discount percentage is displayed
cleverApi-{product_id}-discountPercentageLocalizedThe localized discount percentage is displayed
cleverApi-{product_id}-monthlyPriceNetThe net price per month is displayed
cleverApi-{product_id}-monthlyPriceNetLocalizedThe localized net price per month is displayed
cleverApi-{product_id}-monthlyPriceGrossThe gross price per month is displayed
cleverApi-{product_id}-monthlyPriceGrossLocalizedThe localized gross price per month is displayed


Did this page help you?