Skip to content

Commit

Permalink
feat: add apilayer as provider for fixer api (#127)
Browse files Browse the repository at this point in the history
feat: add apilayer as provider for fixer api
feat: update exchange rate when saving api key
  • Loading branch information
ellite committed Feb 19, 2024
1 parent e726b5c commit 0f19dd6
Show file tree
Hide file tree
Showing 17 changed files with 141 additions and 30 deletions.
22 changes: 19 additions & 3 deletions endpoints/currency/fixer_api_key.php
Original file line number Diff line number Diff line change
Expand Up @@ -5,16 +5,32 @@
if (isset($_SESSION['loggedin']) && $_SESSION['loggedin'] === true) {
if ($_SERVER["REQUEST_METHOD"] === "POST") {
$newApiKey = isset($_POST["api_key"]) ? $_POST["api_key"] : "";
$provider = isset($_POST["provider"]) ? $_POST["provider"] : 0;

$removeOldKey = "DELETE FROM fixer";
$db->exec($removeOldKey);
$testKeyUrl = "http://data.fixer.io/api/latest?access_key=$newApiKey";
$response = file_get_contents($testKeyUrl);

if ($provider == 1) {
$testKeyUrl = "https://api.apilayer.com/fixer/latest?base=USD&symbols=EUR";
$context = stream_context_create([
'http' => [
'method' => 'GET',
'header' => 'apikey: ' . $newApiKey,
]
]);
$response = file_get_contents($testKeyUrl, false, $context);
} else {
$testKeyUrl = "http://data.fixer.io/api/latest?access_key=$newApiKey";
$response = file_get_contents($testKeyUrl);
}

$apiData = json_decode($response, true);
if ($apiData['success'] && $apiData['success'] == 1) {
if (!empty($newApiKey)) {
$insertNewKey = "INSERT INTO fixer (api_key) VALUES (:api_key)";
$insertNewKey = "INSERT INTO fixer (api_key, provider) VALUES (:api_key, :provider)";
$stmt = $db->prepare($insertNewKey);
$stmt->bindParam(":api_key", $newApiKey, SQLITE3_TEXT);
$stmt->bindParam(":provider", $provider, SQLITE3_INTEGER);
$result = $stmt->execute();
if ($result) {
echo json_encode(["success" => true, "message" => translate('api_key_saved', $i18n)]);
Expand Down
48 changes: 33 additions & 15 deletions endpoints/currency/update_exchange.php
Original file line number Diff line number Diff line change
Expand Up @@ -2,30 +2,36 @@
require_once '../../includes/connect_endpoint.php';

$shouldUpdate = true;
$query = "SELECT date FROM last_exchange_update";
$result = $db->querySingle($query);

if ($result) {
$lastUpdateDate = new DateTime($result);
$currentDate = new DateTime();
$lastUpdateDateString = $lastUpdateDate->format('Y-m-d');
$currentDateString = $currentDate->format('Y-m-d');
$shouldUpdate = $lastUpdateDateString < $currentDateString;
}
if (isset($_GET['force']) && $_GET['force'] === "true") {
$shouldUpdate = true;
} else {
$query = "SELECT date FROM last_exchange_update";
$result = $db->querySingle($query);

if (!$shouldUpdate) {
echo "Rates are current, no need to update.";
exit;
if ($result) {
$lastUpdateDate = new DateTime($result);
$currentDate = new DateTime();
$lastUpdateDateString = $lastUpdateDate->format('Y-m-d');
$currentDateString = $currentDate->format('Y-m-d');
$shouldUpdate = $lastUpdateDateString < $currentDateString;
}

if (!$shouldUpdate) {
echo "Rates are current, no need to update.";
exit;
}
}

$query = "SELECT api_key FROM fixer";
$query = "SELECT api_key, provider FROM fixer";
$result = $db->query($query);

if ($result) {
$row = $result->fetchArray(SQLITE3_ASSOC);

if ($row) {
$apiKey = $row['api_key'];
$provider = $row['provider'];

$codes = "";
$query = "SELECT id, name, symbol, code FROM currencies";
Expand All @@ -41,8 +47,20 @@
$mainCurrencyCode = $row['code'];
$mainCurrencyId = $row['main_currency'];

$api_url = "http://data.fixer.io/api/latest?access_key=". $apiKey . "&base=EUR&symbols=" . $codes;
$response = file_get_contents($api_url);
if ($provider === 1) {
$api_url = "https://api.apilayer.com/fixer/latest?base=EUR&symbols=" . $codes;
$context = stream_context_create([
'http' => [
'method' => 'GET',
'header' => 'apikey: ' . $apiKey,
]
]);
$response = file_get_contents($api_url, false, $context);
} else {
$api_url = "http://data.fixer.io/api/latest?access_key=". $apiKey . "&base=EUR&symbols=" . $codes;
$response = file_get_contents($api_url);
}

$apiData = json_decode($response, true);

$mainCurrencyToEUR = $apiData['rates'][$mainCurrencyCode];
Expand Down
27 changes: 20 additions & 7 deletions endpoints/user/save_user.php
Original file line number Diff line number Diff line change
Expand Up @@ -5,14 +5,15 @@
session_start();

function update_exchange_rate($db) {
$query = "SELECT api_key FROM fixer";
$query = "SELECT api_key, provider FROM fixer";
$result = $db->query($query);

if ($result) {
$row = $result->fetchArray(SQLITE3_ASSOC);

if ($row) {
$apiKey = $row['api_key'];
$provider = $row['provider'];

$codes = "";
$query = "SELECT id, name, symbol, code FROM currencies";
Expand All @@ -29,8 +30,20 @@ function update_exchange_rate($db) {
$mainCurrencyCode = $row['code'];
$mainCurrencyId = $row['main_currency'];

$api_url = "http://data.fixer.io/api/latest?access_key=". $apiKey . "&base=EUR&symbols=" . $codes;
$response = file_get_contents($api_url);
if ($provider === 1) {
$api_url = "https://api.apilayer.com/fixer/latest?base=EUR&symbols=" . $codes;
$context = stream_context_create([
'http' => [
'method' => 'GET',
'header' => 'apikey: ' . $apiKey,
]
]);
$response = file_get_contents($api_url, false, $context);
} else {
$api_url = "http://data.fixer.io/api/latest?access_key=". $apiKey . "&base=EUR&symbols=" . $codes;
$response = file_get_contents($api_url);
}

$apiData = json_decode($response, true);

$mainCurrencyToEUR = $apiData['rates'][$mainCurrencyCode];
Expand Down Expand Up @@ -125,9 +138,9 @@ function update_exchange_rate($db) {
if ($result) {
$cookieExpire = time() + (30 * 24 * 60 * 60);
$oldLanguage = isset($_COOKIE['language']) ? $_COOKIE['language'] : "en";
$root = str_replace('/endpoints/user', '', dirname($_SERVER['PHP_SELF']));
$root = $root == '' ? '/' : $root;
setcookie('language', $language, $cookieExpire, $root);
$root = str_replace('/endpoints/user', '', dirname($_SERVER['PHP_SELF']));
$root = $root == '' ? '/' : $root;
setcookie('language', $language, $cookieExpire, $root);
if ($username != $oldUsername) {
$_SESSION['username'] = $username;
if (isset($_COOKIE['wallos_login'])) {
Expand Down Expand Up @@ -168,4 +181,4 @@ function update_exchange_rate($db) {
echo json_encode($response);
exit();
}
?>
?>
3 changes: 3 additions & 0 deletions includes/i18n/de.php
Original file line number Diff line number Diff line change
Expand Up @@ -118,8 +118,11 @@
"currency_performance" => "Aus Gründen der Performance wähle bitte ausschließlich die genutzen Währungen.",
"fixer_api_key" => "Fixer API Key",
"api_key" => "API Key",
"provider" => "Anbieter",
"fixer_info" => "Falls du mehrere Währungen nutzt und genaue Statistiken und die Sortierungsfunktion nutzen möchtest, wird ein kostenfreier API Key von Fixer benötigt.",
"get_key" => "Erhalte deinen key bei",
"get_free_fixer_api_key" => "Erhalte deinen kostenfreien Fixer API Key",
"get_key_alternative" => "Alternativ können Sie einen kostenlosen Fixer-Api-Schlüssel erhalten von",
"display_settings" => "Display-Einstellungen",
"switch_theme" => "Light / Dark Theme umschalten",
"calculate_monthly_price" => "Berechne und zeige monatlichen Preis für alle Abonnements an",
Expand Down
3 changes: 3 additions & 0 deletions includes/i18n/el.php
Original file line number Diff line number Diff line change
Expand Up @@ -118,8 +118,11 @@
"currency_performance" => "Για βελτιωμένη απόδοση κράτησε μόνο τα νομίσματα που χρησιμοποιείς.",
"fixer_api_key" => "Fixer API κλειδί",
"api_key" => "API κλειδί",
"provider" => "Πάροχος",
"fixer_info" => "Εάν χρησιμοποιείς πολλαπλά νομίσματα και θέλεις ακριβή στατιστικά στοιχεία και ταξινόμηση των συνδρομών, είναι απαραίτητο ένα ΔΩΡΕΑΝ κλειδί API από το Fixer.",
"get_key" => "Απόκτησε το κλειδί στο",
"get_free_fixer_api_key" => "Απόκτησε ΔΩΡΕΑΝ Fixer API κλειδί",
"get_key_alternative" => "Εναλλακτικά, μπορείτε να λάβετε ένα δωρεάν κλειδί api fixer από το",
"display_settings" => "Ρυθμίσεις εμφάνισης",
"switch_theme" => "Διακόπτης Light / Dark Theme",
"calculate_monthly_price" => "Υπολογισμός και εμφάνιση της μηνιαίας τιμής για όλες τις συνδρομές",
Expand Down
3 changes: 3 additions & 0 deletions includes/i18n/en.php
Original file line number Diff line number Diff line change
Expand Up @@ -118,8 +118,11 @@
"currency_performance" => "For improved performance keep only the currencies you use.",
"fixer_api_key" => "Fixer API Key",
"api_key" => "API Key",
"provider" => "Provider",
"fixer_info" => "If you use multiple currencies, and want accurate statistics and sorting on the subscriptions, a FREE API Key from Fixer is necessary.",
"get_key" => "Get your key at",
"get_free_fixer_api_key" => "Get free Fixer API Key",
"get_key_alternative" => "Alternatively, you can get a free fixer api key from",
"display_settings" => "Display Settings",
"switch_theme" => "Switch Light / Dark Theme",
"calculate_monthly_price" => "Calculate and show monthly price for all subscriptions",
Expand Down
3 changes: 3 additions & 0 deletions includes/i18n/es.php
Original file line number Diff line number Diff line change
Expand Up @@ -118,8 +118,11 @@
"currency_performance" => "Para un rendimiento mejorado, guarda solo las monedas que uses.",
"fixer_api_key" => "API Key de Fixer",
"api_key" => "API Key",
"provider" => "Proveedor",
"fixer_info" => "Si usas varias monedas y deseas estadísticas y orden precisos en las suscripciones, es necesaria una API KEY gratuita de Fixer.",
"get_key" => "Obtén tu clave en",
"get_free_fixer_api_key" => "Obtén una API Key de Fixer gratuita",
"get_key_alternative" => "También puede obtener una clave api gratuita de Fixer en",
"display_settings" => "Configuración de Pantalla",
"switch_theme" => "Cambiar entre Tema Claro / Oscuro",
"calculate_monthly_price" => "Calcular y mostrar el precio mensual de todas las suscripciones",
Expand Down
3 changes: 3 additions & 0 deletions includes/i18n/fr.php
Original file line number Diff line number Diff line change
Expand Up @@ -118,8 +118,11 @@
"currency_performance" => "Pour des performances améliorées, ne conservez que les devises que vous utilisez.",
"fixer_api_key" => "Clé API de Fixer",
"api_key" => "Clé API",
"provider" => "Fournisseur",
"fixer_info" => "Si vous utilisez plusieurs devises et souhaitez des statistiques et un tri précis sur les abonnements, une clé API GRATUITE de Fixer est nécessaire.",
"get_key" => "Obtenez votre clé sur",
"get_free_fixer_api_key" => "Obtenez une clé API Fixer gratuite",
"get_key_alternative" => "Vous pouvez également obtenir une clé api de fixation gratuite auprès de",
"display_settings" => "Paramètres d'affichage",
"switch_theme" => "Basculer entre le thème clair et sombre",
"calculate_monthly_price" => "Calculer et afficher le prix mensuel pour tous les abonnements",
Expand Down
3 changes: 3 additions & 0 deletions includes/i18n/jp.php
Original file line number Diff line number Diff line change
Expand Up @@ -118,8 +118,11 @@
"currency_performance" => "Fパフォーマンスを向上させるには、使用する通貨のみを保持してください。",
"fixer_api_key" => "FixerのAPIキー",
"api_key" => "APIキー",
"provider" => "プロバイダ",
"fixer_info" => "複数の通貨を使用し、定期購入に関する正確な統計と並べ替えが必要な場合は、Fixerからの無料APIキーが必要です。",
"get_key" => "キーを入手する",
"get_free_fixer_api_key" => "無料のFixer APIキーを取得",
"get_key_alternative" => "または、以下のサイトから無料のフィクサーapiキーを入手することもできます。",
"display_settings" => "表示設定",
"switch_theme" => "ライト/ダーク テーマの切り替え",
"calculate_monthly_price" => "すべての定期購入の月額料金を計算して表示する",
Expand Down
3 changes: 3 additions & 0 deletions includes/i18n/pt.php
Original file line number Diff line number Diff line change
Expand Up @@ -118,8 +118,11 @@
"currency_performance" => "Por motivos de desempenho mantenha apenas as moedas que usa.",
"fixer_api_key" => "Fixer API Key",
"api_key" => "API Key",
"provider" => "Fornecedor",
"fixer_info" => "Se usa multiplas moedas e deseja estatísticas correctas é necessário uma API Key grátis do Fixer.",
"get_key" => "Obtenha a sua API Key em",
"get_free_fixer_api_key" => "Obtenha a sua API Key grátis do Fixer",
"get_key_alternative" => "Como alternativa obtenha a sua API Key em",
"display_settings" => "Definições de visualização",
"switch_theme" => "Trocar Tema Claro / Escuro",
"calculate_monthly_price" => "Calcular e mostrar preço mensal para todas as subscrições",
Expand Down
3 changes: 3 additions & 0 deletions includes/i18n/tr.php
Original file line number Diff line number Diff line change
Expand Up @@ -118,8 +118,11 @@
"currency_performance" => "Performansı artırmak için sadece kullandığınız para birimlerini tutun.",
"fixer_api_key" => "Fixer API Anahtarı",
"api_key" => "API Anahtarı",
"provider" => "Sağlayıcı",
"fixer_info" => "Birden fazla para birimi kullanıyorsanız ve aboneliklerde doğru istatistikler ve sıralama istiyorsanız, Fixer'dan ÜCRETSİZ bir API Anahtarı gereklidir.",
"get_key" => "Anahtarınızı şuradan alın",
"get_free_fixer_api_key" => "Ücretsiz Fixer API Anahtarı alın",
"get_key_alternative" => "Alternatif olarak, şu adresten ücretsiz bir fixer api anahtarı edinebilirsiniz",
"display_settings" => "Görüntüleme Ayarları",
"switch_theme" => "Açık / Koyu Temayı Değiştir",
"calculate_monthly_price" => "Tüm aboneliklerin aylık fiyatını hesaplayın ve gösterin",
Expand Down
3 changes: 3 additions & 0 deletions includes/i18n/zh_cn.php
Original file line number Diff line number Diff line change
Expand Up @@ -125,8 +125,11 @@
"currency_performance" => "为提高性能,建议您只保留常用货币。",
"fixer_api_key" => "Fixer API 密钥",
"api_key" => "API 密钥",
"provider" => "提供商",
"fixer_info" => "如果您使用多种货币,希望统计信息和订阅排序更精确,则需要 Fixer API 密钥来查询汇率(可免费申请)。",
"get_key" => "申请密钥",
"get_free_fixer_api_key" => "申请免费 Fixer API 密钥",
"get_key_alternative" => "或者,您也可以从以下网站获取免费的修复程序 api 密钥",
"display_settings" => "显示设置",
"switch_theme" => "切换浅色/深色主题",
"calculate_monthly_price" => "计算并显示所有订阅的月价格",
Expand Down
3 changes: 3 additions & 0 deletions includes/i18n/zh_tw.php
Original file line number Diff line number Diff line change
Expand Up @@ -125,8 +125,11 @@
"currency_performance" => "為提高性能,建議您只保留常用的貨幣。",
"fixer_api_key" => "Fixer API 密鑰",
"api_key" => "API 密鑰",
"provider" => "提供者",
"fixer_info" => "如果您使用多種貨幣單位,且希望統計資訊和訂閱排序更加精確,則需要 Fixer API 密鑰來查詢匯率(可免費申請)。",
"get_key" => "申請密鑰",
"get_free_fixer_api_key" => "申請免費的 Fixer API 密鑰",
"get_key_alternative" => "或者,您可以從以下網址取得一個免費的修復 api 金鑰",
"display_settings" => "顯示設定",
"switch_theme" => "切換淺色/深色主題",
"calculate_monthly_price" => "計算並顯示所有訂閱的每月價格",
Expand Down
2 changes: 1 addition & 1 deletion includes/version.php
Original file line number Diff line number Diff line change
@@ -1,3 +1,3 @@
<?php
$version = "v1.2.5";
$version = "v1.3.0";
?>
12 changes: 12 additions & 0 deletions migrations/000006.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
<?php
// This migration adds a "provider" column to the fixer table and sets all values to 0.
// It allows the user to chose a different provider for their fixer api keys.

/** @noinspection PhpUndefinedVariableInspection */
$columnQuery = $db->query("SELECT * FROM pragma_table_info('fixer') where name='provider'");
$columnRequired = $columnQuery->fetchArray(SQLITE3_ASSOC) === false;

if ($columnRequired) {
$db->exec('ALTER TABLE fixer ADD COLUMN provider INT DEFAULT 0');
$db->exec('UPDATE fixer SET provider = 0');
}
5 changes: 4 additions & 1 deletion scripts/settings.js
Original file line number Diff line number Diff line change
Expand Up @@ -477,18 +477,21 @@ function addFixerKeyButton() {
document.getElementById("addFixerKey").disabled = true;
const apiKeyInput = document.querySelector("#fixerKey");
apiKey = apiKeyInput.value.trim();
const provider = document.querySelector("#fixerProvider").value;
fetch("endpoints/currency/fixer_api_key.php", {
method: "POST",
headers: {
"Content-Type": "application/x-www-form-urlencoded",
},
body: `api_key=${encodeURIComponent(apiKey)}`,
body: `api_key=${encodeURIComponent(apiKey)} & provider=${encodeURIComponent(provider)}`,
})
.then(response => response.json())
.then(data => {
if (data.success) {
showSuccessMessage(data.message);
document.getElementById("addFixerKey").disabled = false;
// update currency exchange rates
fetch("endpoints/currency/update_exchange.php?force=true");
} else {
showErrorMessage(data.message);
document.getElementById("addFixerKey").disabled = false;
Expand Down

0 comments on commit 0f19dd6

Please sign in to comment.