Skip to main content

Multiple currencies

The best way to handle a website which has multiple currencies but no common URL pathing that explains which currency is used is to convert the currency before sending the info to the tracker. An example for when you do NOT need to handle multiple currencies is when you have a website with a single currency, like example.com = USD example.se = SEK example.de = EUR.

If you do have a website which handles multiple currencies but no URL to sort them the best way forward is to choose a single currency that you would like to measure everything in and then convert the customers purchase to this common currency before sending the data to the e-commerce tracker. This way you can compare all the data in a simple and easy way.

The ecommerce tracker api consists of 6 input parameters and if we are using the e-commerce tracker to measure how much of an increase the ImBox product has on our website we want to send a complete customer transaction as one entry into the tracker. To do this we need to combine the total cost of the purchase (totalCostOfCart) as well as all items into a single string (productsInCart).

_imbox.push([
"insertTrans",
id,
affiliation,
totalCostOfCart,
productsInCart,
custom1,
custom2
])

But if we were to send totalCostOfCart with different currencies we would not be able to compare the results as it’s not possible to filter or sort on currency alone. And this is where you need to convert the currency before sending it to the tracker.

In this example, we’re using an API from https://exchangerate-api.com/ which updates the value of (at the time of writing this guide) 161 currencies once a day on the free plan. While this wont be 100% accurate, for the purpose of measuring the success of deploying ImBox, this is totally acceptable.

So what happens in the below code is that we fetch the JSON from our API and compare the currency the customer has made their purchase in and then convert it to the currency we would like to compare everything in, which in this example is SEK. After it’s been converted we send the converted values along with what currency the customer originally made the purchase in. Using affiliating we’re also sending along which website the customer made the purchase on. Useful when your website has multiple URL paths but also multiple currencies within all URL:s.

Get the current exchangerate

async function getExchangeRatesToSEK() {
try {
// You need to change the API key to your own
const response = await fetch(
"https://v6.exchangerate-api.com/v6/7e15bb9d1180s7d3ca216aff93s425fb/latest/SEK"
)
if (response.ok) {
const data = await response.json()
return data.conversion_rates
} else {
throw new Error("Failed to fetch exchange rates")
}
} catch (err) {
console.error("Error fetching exchange rates:", err)
return null
}
}

confirmPurchase function

async function confirmPurchase() {
const rates = await this.getExchangeRatesToSEK()
if (!rates) {
console.error("Couldn't fetch the exchange rates. Aborting purchase.")
return
}

// Checking which url is affiliated with the purchase, make changes depending on your websites URL structure
const aff = window.location.pathname.slice(1).split("/")
const string = aff[0]
const affiliation = string[0].toUpperCase() + string.slice(1).toLowerCase()

// This is just how we fetch the current cart, you probably have a function similar to getCart() you can use
const currentCart = JSON.parse(localStorage.getItem("demosite.cart") ?? "[]")
let cartTotalCost = ""
let productsInCart = ""
let currencyToUse = Math.random() * 3 // Here you need to fetch the actual currency the customer is making their purchase in. In this example we’re just randomising one currency

let currency = ""
for (let i = 0; i < currentCart.length; i++) {
let productPrice = Number.parseFloat(currentCart[i].price)

if (currencyToUse < 1) {
currency = "SEK"
} else if (currencyToUse < 2) {
currency = "USD"
} else {
currency = "EUR"
}

if (currency !== "SEK") {
const rate = rates[currency]
if (!rate) {
console.error(
`Exchange rate for ${currency} not found. Skipping product.`
)
continue
}
productPrice /= rate // Convert the currency to the common one: SEK
}

// below is just for the sake of this example
if (cartTotalCost === "") {
cartTotalCost = 0
}
cartTotalCost += productPrice

let space = ""
if (i !== currentCart.length - 1) {
space = ", "
}

productsInCart += currentCart[i].name + space
}

// lastly when we’re converted and created all the variables we would like to measure we send the data using the e-commerce tracker API to ImBox Admin where we then can view the results as well as compare.
_imbox.push([
"insertTrans",
Math.floor(Math.random() * 100_000), // this is just a random number, but usually should be replaced with the customers order number
affiliation, // in this example it will print ecommerce / hotel depending on which URL the customer is making their purchase on
Math.floor(cartTotalCost), // The total price after exchange rate conversion and the rounded
productsInCart, // which products did the customer buy
"", // an empty input parameter where you could input whatever else you would like to know about this particular transaction
currency // here  we insert the original currency the customer made their purchase in.
])
}

What it could look like inside the tracker

Multiple currencies