Currency Conversion Function

Viewing 0 reply threads
  • Author
    Posts
  • July 21, 2019 at 9:44 PM #36005

    Sam Moffatt
    Participant

    Every so often I buy something that isn’t directly in USD and want to have a quick way of converting it back to USD. I ended up using a free currency converter API which requires a simple registration to get an API key (replace the string PUT_YOUR_API_KEY_HERE with the API key they assign you). Apart from that it has a reasonably generous amount of requests (100 an hour).

    Here’s the script, intended to be saved as a form script named ‘Currency Converter’ in a form named ‘Script Manager’ similar to the logger module:

    // ========== convertCurrency Start ========== //
    // NAME: Convert Currency
    // VERSION: 1.1
    // CHANGES:
    //  1.1: Add options for different API, update to v7.
    
    document.getFormNamed('Script Manager').runScriptNamed('Logger');
    
    /**
     * Convert from one currency to another using a free web serive.
     *
     * source_currency: 		The source currency to convert from (e.g. CAD).
     * destination_currency:	The destination currency to convert into (e.g. USD).
     * amount:					The amount in the source currency to convert into destination currency.
     *
     * return: float value of converted currecny or false on error.
     */
    function convertCurrency(source_currency, destination_currency, amount)
    {
    	var services = { "free" : "https://free.currconv.com", 
    						"prepaid": "https://prepaid.currconv.com",
    						"premium": "https://api.currconv.com"
    					};
    					
    	var apiKey = 'PUT_YOUR_API_KEY_HERE';
    	var currency_key = source_currency + "_" + destination_currency;
    	var url = `${services['free']}/api/v7/convert?compact=ultra&apiKey=${apiKey}&q=${currency_key}`;
    	
    	logger.logMessage(`Requesting from URL: ${url}`);
    
    	// Make the request.
    	var forex = Utils.getJsonFromUrl(url);
    			
    	// Check the response matches.
    	if (forex && forex[currency_key])
    	{
    		logger.logMessage(`Conversion for ${source_currency} to ${destination_currency} is ${forex[currency_key]}`);
    		return forex[currency_key] * amount;
    	}
    	else
    	{
    		logger.logMessage("Unknown response received from URL: " + JSON.stringify(forex));
    		return false;
    	}
    }
    // ========== convertCurrency End ========== //
    

    That one is simple: put in the currency you start with and the currency you want to land in and the amount. The API could do the amount calculation itself but I find it interesting to see what the raw value is and handle the multiplication in my own code.

    In my case this is then connected to a field script that looks at a total field and a currency field to populate a USD total field. It’s a little more complicated because I do some math to get the total (shipping fee, taxes and total cost).

    Simple example:

    document.getFormNamed('Script Manager').runScriptNamed('Currency Converter');
    convertCurrency('CAD', 'USD', '123.45');
    
Viewing 0 reply threads

You must be logged in to reply to this topic.