Automate Exchange Rates with HTTP Callout

Automate Exchange Rates with HTTP Callout

Update: Thanks to a great tip from Flowfest winner Yumi Ibrahimzade, this post has been updated to make it even simpler and I managed to eliminate a couple of steps. Thanks Yumi!

Update (2 Feb): I just fixed an error where the URL path was not passed when creating the HTTP Callout – thanks to Matt Suellentrop for helping to find my mistake! (See the correction in step 5).

Update (18 Feb) – Håkon Dieset helped find another mistake, I had one of the parameters named base instead of source. This caused all conversions to be done using USD as the main currency. Corrected now in Step 5.

If your Salesforce environment is using multiple currencies, one of the painful admin tasks is to upload the new exchange rates every day/week/month. If you have many currencies to manage this gets even more painful.

You can now (in Spring ’23) say goodbye to manually entering these dated exchange rates!

Using the new HTTP Callout feature (Spring ’23) in flow to look up the current rates on the Internet and automatically create new dated exchange rate records in Salesforce.

Automate Exchange Rates with HTTP Callout - dated exchange rates


Currency Data API provides exchange rates for 168 currencies.

Spot exchange rate data is retrieved from several major forex data providers in real-time, validated, processed and delivered hourly, every 10 minutes, or even within the 60-second market window.

Providing the most representative forex market value available (“midpoint” value) for every API request, the Currency Data API API powers currency converters, mobile applications, financial software components and back-office systems all around the world.

Using a FREE account from the Currency Data API gives you 100 transactions per month – more than enough to schedule this to run once every day. Simply set up the flow to run overnight and the next day your rates will be loaded and ready to go!

Automate Exchange Rates with HTTP Callout - currency data api


Before you start

Before you can Automate Exchange Rates with HTTP Callout, you need to have multi-currency enabled in your Salesforce org before you start or you will not have the object: Dated Conversion Rate which is used in the flow.

As the HTTP Callout is a beta feature only available in Spring ’23 organizations you need a sandbox on this release level to implement this.


Automate Exchange Rates with HTTP Callout

Step 1: Get your free account at Currency Data API

A free account from APILayer will give you 100 requests per month. More than enough to do a daily update of your exchange rates. One request can return multiple rates so you should only use 28-31 requests per month, regardless of how many currencies you need exchange rates for.

Go here to get your FREE account:

https://apilayer.com/marketplace/currency_data-api

subscribe to currency data API


Once you have subscribed, you will receive an API Key – copy this to your clipboard for the next step.

Step 2: Create a Custom Label to store your new API Key

The API Key is like a password to use the API service. Store it in a Custom Label so you can easily access it via your flow using the global variable $Label.

Paste the API Key into the value field shown below:

Salesforce -> Setup -> Custom Labels -> New

Automate Exchange Rates with HTTP Callout - custom label


Step 3: Add a Named Credential for the API

The Named Credential will be used as the destination for the request (HTTP Callout) from Salesforce.

For this API, we will be using: https://api.apilayer.com/currency_data/

Salesforce -> Setup -> Named Credentials -> New Legacy

*** Make sure you select “New Legacy” not “New” when creating this ***

named credentials


Give the new credential a label, click the tab key to automatically create the name and then enter the URL.

https://api.apilayer.com/currency_data/

Tick the remaining three checkboxes and then save.

named credentials image


Step 4: Create a Scheduled Flow to perform the update

Problem: When a scheduled flow runs, Salesforce opens a DML transaction. Even though you do not specify an object in the start criteria, it still opens a transaction. An HTTP Callout cannot be performed when there is an open DML transaction. (I learned this the hard way).

Solution: Thanks to a tip from Yumi Ibrahimzade, you can just add a pause element before the HTTP Callout and this problem will be solved.

Create a new flow and select Schedule-Triggered Flow.

Automate Exchange Rates with HTTP Callout - create a flow


Set a schedule for when to run the flow:


Add a Pause element to the flow to solve the HTTP Callout problem described above.



Set the Pause Condition to Always Pause Flow:


On the second tab of the pause element (Resume Event), set the resume time:

Automate Exchange Rates with HTTP Callout -  resume event

Add an action and select Create HTTP Callout (Beta)


Step 5: Create the new HTTP Callout action

Configure the new HTTP Callout action as follows:

The Named Credential uses the one you configured earlier.


Click Next

Add a Label (1)

Select the GET method (2)

Enter a description (3)

Add the URL Path (4) to use the live rates function from this API service

Click Add Key (5)


Add these three keys (all of the type string):

Note the correction to the name of the 2nd key (18 Feb).

Automate Exchange Rates with HTTP Callout - add query params


Before clicking Save, you need to provide a sample JSON response.

Go back to the API Layer website in a new browser tab:

(don’t close the Salesforce tab – you will come back to it)

https://apilayer.com/marketplace/currency_data-api

Make sure you are still logged in to this website. (or the run code button will not work).

Click the Live Demo button:

Select the GET /live option (1) on the left (you may need to collapse the currently open option)

Enter the currencies you want to be converted to (2) – these equal the “symbols” parameter you configured earlier. If you need multiple currencies, separate them with commas.

Enter the source (3) – this equals the “source” currency you configured earlier.

Click the Run Code button (4)

Copy the text that is returned including the braces (5)


Return to Salesforce to finish configuring the HTTP Callout:

Click New to create a sample response:


Paste in the response (on the left panel) and click Review to verify it is correct:


If you get a Data Structure like shown on the right (above) then all is good and you can click done.

In the background, Salesforce has done all the hard work for you in creating an external service and the Apex data type to handle the response plus making it available as an invocable action for use by the flow.


Step 6: Configure your flow to use the new HTTP Callout

Now your new action has been created (and is available for other flows too) it’s time to configure it for use in this flow: You need to pass it the apikey, source currency, and symbols (rates you are converting to).

Add a Label (1)

Select the API key you created a label for back at the start (via the global $Label variable) (2)

Enter your source currency (3)

Enter a comma-delimited list of currencies you want to convert to (4)


Step 7: Create formula fields to store the results from the HTTP Callout

The results coming back from the HTTP callout don’t seem to play nicely with flow so we need to assign them to a formula field so we can use them in flow.

Create a new formula field for each returned currency value:

Note the use of 6 decimal places.

Drill into the results of our action to get the returned values:

Select > beside the Outputs from your Get_FX_Rates action:

Choose > beside the 2XX value:

Select > beside quotes:

Select the value you want to be assigned to the formula:

Repeat this process for all other currencies (eg the GBP currency):

The completed EURRate formula:

The completed GBPRate formula:

Automate Exchange Rates with HTTP Callout - edit formula


Step 8: Create the new Dated Exchange Records

Add a Create Records element for each currency you need and populate the fields as shown.

Create the EUR record:


Add another Create Records for the GBP record:

Automate Exchange Rates with HTTP Callout - create records


Your final flow should look like this:



Save and activate your flow.

Automate Exchange Rates with HTTP Callout -  save the flow


Double-check your flow is now active.


When the time schedule passes you should have new entries in your Managed Currencies!

(If not, check your email for an error!)

Setup -> Manage Currencies -> Manage Dated Exchange Rates

Automate Exchange Rates with HTTP Callout -


Running the flow multiple times per day

If you have a business requirement to run this flow multiple times per day to update your rates then this is possible but adds some complexity.

  1. Salesforce only allows one Dated Exchange Rate to be added per day so you will need to adjust the flow to check if the record already exists for that currency for today and to update it rather than creating a new record. Do a Get Records and if it returns a result, edit the record, otherwise create a new one.
  2. You will likely run out of API calls (100 on the free subscription) – you could probably do 3 per day but beyond that, you will need a paid subscription.
  3. You will need to find a new way to run the scheduled task as Scheduled Flows can only be set to run on a daily/weekly schedule. (you could just duplicate the flow and have several copies running at different times).



Need Flow Training?

Like what you see but need some training on flow? My Learning Salesforce Flow course is designed for beginners to get started with building flows. I will take you step-by-step through building 25 flows that cover all of the key elements available. You get 24 x 7 access to the course with a lifetime subscription.

Similar Posts

17 Comments

  1. Pingback: Highlights from the Spring ’23 Release Flow Preview - The Flow Architect
    1. Looks like you may have forgotten to configure the pause element properly. On the element there is a tab named “Resume Event”.
      Select Pause until – Specified time, then base time = {!Flow.CurrentDateTime} – note these are braces not brackets, Offset number = 0 and Offset Unit = Hours (capital H).
      This sets the pause to be zero hours after the currenct date time store in the flow variable. It will (depending on load) resume the flow almost immediately.

  2. Hi Daryl!
    I’m pretty sure I have set up this flow correctly and amended it so that it works with EUR instead of USD, but I still get an error (I’ve also attached Sample Response and Input from Action. Do you have any idea on where this goes wrong?
    Error:
    “Create one DatedConversionRate record where
    ConversionRate = {!NOKRate} (null)
    IsoCode = NOK
    StartDate = {!$Flow.CurrentDate} (14. February 2023)
    Result: Failed to create record.
    Error Occurred: This error occurred when the flow tried to create records: INVALID_CURRENCY_CONV_RATE: The conversion rate has to be positive. You can look up ExceptionCode values in the SOAP API Developer Guide.

    Sample Response:
    {
    “quotes”: {
    “EURDKK”: 7.45094,
    “EURNOK”: 10.838224,
    “EURSEK”: 11.099227,
    “EURUSD”: 1.07475
    },
    “source”: “EUR”,
    “success”: true,
    “timestamp”: 1676365143
    }

    Input from Action:
    apikey = {!$Label.Currency_Data_API_Key} (*My API key*)
    base = EUR
    symbols = NOK,SEK,DKK,USD
    Outputs
    2XX (CurrencyDataAPIV3_Getx20FXx20Ratesx203_OUT_2XX : { “timestamp_set” : true, “timestamp” : 1676365443, “success_set” : true, “success” : true, “source_set” : true, “source” : “USD”, “quotes_set” : true, “quotes” : { } })
    responseCode (200)

    1. Did you do step 7 and then use those new values? It looks like the value you are trying to use is Null:

      ConversionRate = {!NOKRate} (null)

      A few other things to check: make sure the currencies you are using are active currencies. Try just doing one currency eg EUR to USD.

      1. Yes, I’ve created the formula fields
        NOKRate: {!Get_FX_Rates.2XX.quotes.EURNOK}
        And yes the currencies are active.

        The weird thing is that in the Input from the action it says that the Source is “USD”. But the Sample Code i supplied was with EUR as source.

        1. I’ve seen some strange behaviour similar to this. You may need to delete the flow, delete the external service created (setup -> external services, scroll to the right and select delete) then recreate the HTTP callout from scratch.

          1. I tried deleting the external services, named credential and custom label and start all from scratch but still I get the same error. null value in the rate formula and the source says USD.

          2. Finally found the problem. Where I configure the three params, I had apikey, base and synbols. It should be “source” not base and as this was wrong it was ignored and the USD always used by default. I have corrected the blog article now and credited you with helping identify this problem. Thanks for finding this!

  3. Hi Daryl,
    I have implemented the flow, but getting below error while it runs.

    Error element Create_GBP_Fx_Records (FlowRecordCreate).
    This error occurred when the flow tried to create records: INVALID_CURRENCY_CONV_RATE: The conversion rate has to be positive.

    In my Org, USD is corporate currency and GBP, EUR have been added as active currency as well.

    1. Another user had a similar problem earlier with this. Make sure the Key field is named “Source” in Step 5. (I corrected this in the blog post on 18 Feb).
      If this does not correct the problem, you may have to delete the external services, named credential and custom label and start all from scratch.

  4. Would it not be better to create a loop to collect the exchange rate data for all desired currencies in a variable, then assign the data to data exchange records for the relevant currencies and then use just one create records element at the end (outside the loop)

      1. Apologies. Perhaps then it would be better to perform a series of assignments, adding the exchange rates in one assignment element, then the new Dated Conversion Rate records can be assigned in a collection, before finishing with a single create records element?

  5. Hey Daryl,

    This is great and I am hoping to get it working however I am stuck on step 4:

    https://apilayer.com/marketplace/currency_data-api
    Make sure you are still logged in to this website. (or the run code button will not work).
    Click the Live Demo button:
    Select the GET /live option (1) on the left (you may need to collapse the currently open option)
    Enter the currencies you want to be converted to (2) – these equal the “symbols” parameter you configured earlier. If you need multiple currencies, separate them with commas.
    Enter the source (3) – this equals the “source” currency you configured earlier.
    Click the Run Code button (4)
    Copy the text that is returned including the braces (5)

    When I go to run code it gives me this error:
    {“message”:”You cannot consume this service”}

    I assume maybe they stopped allowing free users this access?

Leave a Reply