Last active
March 29, 2016 06:37
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function main() { | |
var fromCurrency = 'GBP'; //3 letter currency code for base currency | |
var toCurrency = 'USD'; //3 letter currency code for counter currency | |
var customDate = '2012-01-30'; //Date of exchange rate in form 'yyyy-MM-dd'. Leave as blank string for current exchange rates. Dates for fixer.io are valid from 2000 onwards only | |
var exchangeRate = GetExchangeRate(fromCurrency,toCurrency,customDate); | |
Logger.log(exchangeRate); | |
} | |
function GetExchangeRate(fromCurrency,toCurrency, customDate) { | |
if (fromCurrency==toCurrency) { | |
return 1; | |
} | |
var url = ConstructUrl(fromCurrency,toCurrency,customDate); | |
try { | |
var jsonResponseString = UrlFetchApp.fetch(url).getContentText(); | |
} | |
catch(err) { | |
var errorMessage = "Error has occurred. Unable to Access URL. Please check input parameters"; | |
Logger.log (errorMessage); | |
return errorMessage; | |
} | |
var jsonResponseObject = JSON.parse(jsonResponseString); | |
var exchangeRate = jsonResponseObject['rates'][toCurrency]; | |
exchangeRate = parseFloat(exchangeRate); | |
return exchangeRate; | |
} | |
function ConstructUrl(fromCurrency,toCurrency,customDate) { | |
var baseUrl = 'http://api.fixer.io/'; | |
if (customDate === '') { | |
customDate = 'latest'; | |
} | |
var finalUrl = baseUrl + customDate; | |
finalUrl = finalUrl + '?base=' + fromCurrency; | |
finalUrl = finalUrl + '&symbols=' + toCurrency; | |
return finalUrl; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment