Real-time Currency Conversion in Dynamics 365 via FXFeed

Real-time Currency Conversion in Dynamics 365 via FXFeed

Table of Contents

INTRODUCTION

The use-case involves integrating real-time currency conversion functionality into a Dynamics 365 form to streamline financial calculations and improve accuracy. The goal is to automatically calculate the converted amount based on the latest exchange rates fetched from the fxfeed.io API.

This functionality is particularly useful for organizations dealing with international transactions, multi-currency accounting, or financial reporting. By automating the conversion process, users can ensure that currency conversions are always up-to-date and accurate, reducing manual effort and the risk of errors. The solution leverages Dynamics 365’s custom scripting capabilities to call the API, process the response, and update the form fields dynamically during the OnSave event.

ABOUT FXFEED

FXFeed.io is a robust and developer-friendly API platform that delivers real-time and historical foreign currency exchange rate data. Designed with the needs of developers in mind, It offers seamless integration with applications. providing access to reliable data sourced from reliable banks and exchanges. Furthermore, FXFeed.io guarantees swift data retrieval and near 100% uptime.

The platform supports a wide range of functionalities, including retrieving the latest currency rates, historical exchange data, currency conversion, and time series data. FXFeed.io’s API is versatile and easy to integrate, offering responses in standard JSON format. This ensures compatibility across various programming languages and frameworks.

ABOUT FXFEED

FXFeed has Two Subscription Plans:

  • Free: In this plan, a user will have API access, accompanied with 5000 monthly API requests, access to 150+ currencies, updates every 24 hours, and an SSL subscription – all for no charge at all. The same plan is used in the demonstration as well.
  • Pro: In this plan, a user will have API access, accompanied with unlimited API calls, hourly updates, priority email support, and advanced analytics – for $10 per month, or $59 per year.

In order to access the API Key, it is essential to sign-in first. For that, navigate to the login section and create an account

fxfeed currency exchange Sign in page

After successfully creating an account and signing in, you’ll be directed to your dashboard from where you can access your API Key.

After successfully creating an account and signing in, you’ll be directed to your dashboard from where you can access your API Key.

STEP-BY-STEP INTEGRATION OF CURRENCY CONVERTER

The end goal is to implement a custom entity that has an HTML web resource that would update daily, gathering the conversion rate with respect to US Dollar for nine other currencies. Similarly, updates the Converted Amount field with the converted amount after relevant calculations.

STEP-BY-STEP INTEGRATION OF CURRENCY CONVERTER with Dynamics CRM

There are TWO web-resources made with the following purposes:

  • Display Latest Currency Details: An HTML web resource that retrieves the latest currency rate of nine currencies with respect to US Dollar. It appears on the top of the Currency’s main form, and refreshes every time the form opens.
  • Currency Conversion Script: A JavaScript web resource file that comprises a function

convertCurrencyOnSave which runs when the form is saved, and automatically populate the Converted Amount field with regards to the base currency, base amount and derived currency fields.

 TWO web-resources made with the following purposes for Fxfeed to Dynamcis

A currency form is created with five custom fields –

. Description (Single Line of Text)

. Base Currency (Global Option Set)

. Base Amount (Whole Number)

. Derived Currency (Global Option Set)

. Converted Amount(Whole Number)

A currency form is created with five custom fields  in Dynamics CRM

Before saving, the form looks like this:

Before saving, the form looks like this:

After saving the form, the converted amount is automatically populated in the Converted Amount field

After saving the form, the converted amount is automatically populated in the Converted Amount field

CONCLUSION

In conclusion, automating currency conversion within Dynamics 365 significantly enhances efficiency for organizations handling international transactions. By leveraging custom scripting capabilities to call the API and dynamically process and update data during the OnSave event, this solution reduces manual effort and minimizes the risk of errors. Ultimately, this automation not only streamlines financial operations but also ensures that up-to-date and precise conversions are maintained effortlessly, contributing to more reliable financial reporting and decision-making.

GLOSSARY

DisplayLatestCurrencyDetails.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Today's Currency Rates</title>
    <style>
        body {
            font-family: Arial, sans-serif;
            margin: 20px;
        }
        h1 {
            font-size: 18px;
            color: #333;
        }
        ul {
            list-style-type: none;
            padding: 0;
        }
        li {
            margin: 5px 0;
            font-size: 14px;
            color: #555;
        }
    </style>
</head>
<body>
    <h1>Today's Currency Rates (w.r.t USD)</h1>
    <ul id="currency-list">
        <!-- Currency rates will be dynamically populated here -->
    </ul>

    <script>
        // API endpoint and API key
        const apiKey = "fxf_Adp2GHlZnooZ7a7b1IFU"; // Replace with your actual API key
        const currencies = "EUR,GBP,JPY,AUD,CAD,CHF,CNY,SEK,NZD";
        const apiUrl = `https://api.fxfeed.io/v1/latest?base=USD&currencies=${currencies}&api_key=${apiKey}`;

        // Function to fetch currency rates
        async function fetchCurrencyRates() {
            try {
                const response = await fetch(apiUrl);
                const data = await response.json();

                if (data.success) {
                    const rates = data.rates;
                    const currencyList = document.getElementById("currency-list");

                    // Clear any existing list items
                    currencyList.innerHTML = "";

                    // Add each currency rate to the list
                    for (const [currency, rate] of Object.entries(rates)) {
                        const listItem = document.createElement("li");
                        listItem.textContent = `${getCurrencyName(currency)}: ${rate.toFixed(4)} ${getCurrencySymbol(currency)}`;
                        currencyList.appendChild(listItem);
                    }
                } else {
                    console.error("Failed to fetch currency rates:", data);
                }
            } catch (error) {
                console.error("Error fetching currency rates:", error);
            }
        }

        // Helper function to get currency name
        function getCurrencyName(currencyCode) {
            const currencyNames = {
                EUR: "Euro",
                GBP: "UK Pound",
                JPY: "Japanese Yen",
                AUD: "Australian Dollar",
                CAD: "Canadian Dollar",
                CHF: "Swiss Franc",
                CNY: "Chinese Yuan",
                SEK: "Swedish Krona",
                NZD: "New Zealand Dollar"
            };
            return currencyNames[currencyCode] || currencyCode;
        }

        // Helper function to get currency symbol
        function getCurrencySymbol(currencyCode) {
            const currencySymbols = {
                EUR: "€",
                GBP: "£",
                JPY: "¥",
                AUD: "A$",
                CAD: "C$",
                CHF: "CHF",
                CNY: "¥",
                SEK: "kr",
                NZD: "NZ$"
            };
            return currencySymbols[currencyCode] || currencyCode;
        }

        // Fetch currency rates when the page loads
        fetchCurrencyRates();
    </script>
</body>
</html>


CurrencyConversionScript.js

function convertCurrencyOnSave(executionContext) {
    const formContext = executionContext.getFormContext();

    // Get field values
    const baseCurrency = formContext.getAttribute("ssc_basecurrency").getValue();
    const baseAmount = formContext.getAttribute("ssc_baseamount").getValue();
    const derivedCurrency = formContext.getAttribute("ssc_derivedcurrency").getValue();

    // Validate fields
    if (!baseCurrency || !baseAmount || !derivedCurrency) {
        console.error("Base Currency, Base Amount, and Derived Currency are required.");
        return;
    }

    // Map option set values to currency codes
    const currencyMap = {
        924030000: "USD",
        924030001: "EUR",
        924030002: "GBP",
        924030003: "JPY",
        924030004: "AUD",
        924030005: "CAD",
        924030006: "CHF",
        924030007: "CNY",
        924030008: "SEK",
        924030009: "NZD"
    };

    const fromCurrency = currencyMap[baseCurrency];
    const toCurrency = currencyMap[derivedCurrency];

    if (!fromCurrency || !toCurrency) {
        console.error("Invalid currency option set value.");
        return;
    }

    // API endpoint and API key
    const apiKey = "fxf_Adp2GHlZnooZ7a7b1IFU"; // Replace with your actual API key
    const apiUrl = `https://api.fxfeed.io/v1/convert?from=${fromCurrency}&to=${toCurrency}&amount=${baseAmount}&api_key=${apiKey}`;

    // Fetch conversion rate and set converted amount
    fetch(apiUrl)
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                // Use the 'result' field from the API response
                const convertedAmount = data.result;
                formContext.getAttribute("ssc_convertedamount").setValue(Math.round(convertedAmount));
            } else {
                console.error("Failed to convert currency:", data);
            }
        })
        .catch(error => {
            console.error("Error converting currency:", error);
        });
}

Readmore : power virtual agents a game changer for business automation

Frequently Asked Questions (FAQs)

How does the real-time currency conversion work in Dynamics 365?

The integration fetches real-time exchange rates from FXFeed.io and updates the converted amount in Dynamics 365. This ensures accurate and up-to-date currency conversions for financial transactions.

Do I need a paid FXFeed.io subscription to use this integration?

No, the integration works with FXFeed.io’s free plan, which provides access to 150+ currencies, 5,000 monthly API requests,. However, the Pro plan offers additional features such as unlimited API calls and hourly updates.

What happens if the FXFeed API fails to fetch exchange rates?

If the API request fails, the system logs an error and prevents the conversion process from updating the amount field. Users should check API credentials, network connectivity, or retry later if the service is temporarily unavailable.

Picture of SkySoft Connections

SkySoft Connections

SkySoft Connections is a software solution company that was established in 2016. Our quality services begin with experience and end with dedication. Our directors have more than 15 years of IT experience to handle various projects successfully. Our dedicated teams are available to help our clients streamline their business processes, enhance their customer support, automate their day-to-day tasks, and provide software solutions tailored to their specific needs. We are experts in Dynamics 365 and Power Platform services, whether you need Dynamics 365 implementation, customization, integration, data migration, training, or ongoing support.

Conatct us