Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save visar-brainlabs/4ce9c519be3a0cc16238 to your computer and use it in GitHub Desktop.
Save visar-brainlabs/4ce9c519be3a0cc16238 to your computer and use it in GitHub Desktop.
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