Wallos: Open-source, self-hostable personal subscription tracker. Visualize your recurring expenses, manage your budget, and save money.
feat: add apilayer as provider for fixer api (#127)
Miguel Ribeiro0f19dd688fe3
diff --git a/endpoints/currency/fixer_api_key.php b/endpoints/currency/fixer_api_key.phpindex bac1b39..02b7fdd 100644--- a/endpoints/currency/fixer_api_key.php+++ b/endpoints/currency/fixer_api_key.php@@ -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)]);diff --git a/endpoints/currency/update_exchange.php b/endpoints/currency/update_exchange.phpindex fb5a8c0..db3ae19 100644--- a/endpoints/currency/update_exchange.php+++ b/endpoints/currency/update_exchange.php@@ -2,23 +2,28 @@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) {@@ -26,6 +31,7 @@ if ($result) {if ($row) {$apiKey = $row['api_key'];+ $provider = $row['provider'];$codes = "";$query = "SELECT id, name, symbol, code FROM currencies";@@ -41,8 +47,20 @@ if ($result) {$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];diff --git a/endpoints/user/save_user.php b/endpoints/user/save_user.phpindex 94a47bf..38bdfce 100644--- a/endpoints/user/save_user.php+++ b/endpoints/user/save_user.php@@ -5,7 +5,7 @@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) {@@ -13,6 +13,7 @@if ($row) {$apiKey = $row['api_key'];+ $provider = $row['provider'];$codes = "";$query = "SELECT id, name, symbol, code FROM currencies";@@ -29,8 +30,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];@@ -125,9 +138,9 @@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'])) {@@ -168,4 +181,4 @@echo json_encode($response);exit();}-?>+?>diff --git a/includes/i18n/de.php b/includes/i18n/de.phpindex 7322836..f3e08e9 100644--- a/includes/i18n/de.php+++ b/includes/i18n/de.php@@ -118,8 +118,11 @@ $i18n = ["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",diff --git a/includes/i18n/el.php b/includes/i18n/el.phpindex f87082b..50afc29 100644--- a/includes/i18n/el.php+++ b/includes/i18n/el.php@@ -118,8 +118,11 @@ $i18n = ["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" => "Υπολογισμός και εμφάνιση της μηνιαίας τιμής για όλες τις συνδρομές",diff --git a/includes/i18n/en.php b/includes/i18n/en.phpindex 5371fe1..5ef6579 100644--- a/includes/i18n/en.php+++ b/includes/i18n/en.php@@ -118,8 +118,11 @@ $i18n = ["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",diff --git a/includes/i18n/es.php b/includes/i18n/es.phpindex 81630fc..bb3d889 100644--- a/includes/i18n/es.php+++ b/includes/i18n/es.php@@ -118,8 +118,11 @@ $i18n = ["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",diff --git a/includes/i18n/fr.php b/includes/i18n/fr.phpindex c237a07..8e67e28 100644--- a/includes/i18n/fr.php+++ b/includes/i18n/fr.php@@ -118,8 +118,11 @@ $i18n = ["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",diff --git a/includes/i18n/jp.php b/includes/i18n/jp.phpindex da1ac48..7fde90a 100644--- a/includes/i18n/jp.php+++ b/includes/i18n/jp.php@@ -118,8 +118,11 @@ $i18n = ["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" => "すべての定期購入の月額料金を計算して表示する",diff --git a/includes/i18n/pt.php b/includes/i18n/pt.phpindex 7297c8b..1192a33 100644--- a/includes/i18n/pt.php+++ b/includes/i18n/pt.php@@ -118,8 +118,11 @@ $i18n = ["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",diff --git a/includes/i18n/tr.php b/includes/i18n/tr.phpindex 1053b76..e00b752 100644--- a/includes/i18n/tr.php+++ b/includes/i18n/tr.php@@ -118,8 +118,11 @@ $i18n = ["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",diff --git a/includes/i18n/zh_cn.php b/includes/i18n/zh_cn.phpindex ade6f2a..9ec01a5 100644--- a/includes/i18n/zh_cn.php+++ b/includes/i18n/zh_cn.php@@ -125,8 +125,11 @@ $i18n = ["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" => "计算并显示所有订阅的月价格",diff --git a/includes/i18n/zh_tw.php b/includes/i18n/zh_tw.phpindex c17d080..1d751ca 100644--- a/includes/i18n/zh_tw.php+++ b/includes/i18n/zh_tw.php@@ -125,8 +125,11 @@ $i18n = ["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" => "計算並顯示所有訂閱的每月價格",diff --git a/includes/version.php b/includes/version.phpindex 13677d9..c3783e9 100644--- a/includes/version.php+++ b/includes/version.php@@ -1,3 +1,3 @@<?php- $version = "v1.2.5";+ $version = "v1.3.0";?>\ No newline at end of filediff --git a/migrations/000006.php b/migrations/000006.phpnew file mode 100644index 0000000..e52c45e--- /dev/null+++ b/migrations/000006.php@@ -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');+}\ No newline at end of filediff --git a/scripts/settings.js b/scripts/settings.jsindex a09ca56..78446bf 100644--- a/scripts/settings.js+++ b/scripts/settings.js@@ -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;diff --git a/settings.php b/settings.phpindex a8b1ed8..6ac41f4 100644--- a/settings.php+++ b/settings.php@@ -405,12 +405,15 @@<?php$apiKey = "";- $sql = "SELECT api_key FROM fixer";+ $sql = "SELECT api_key, provider FROM fixer";$result = $db->query($sql);if ($result) {$row = $result->fetchArray(SQLITE3_ASSOC);if ($row) {$apiKey = $row['api_key'];+ $provider = $row['provider'];+ } else {+ $provider = 0;}}?>@@ -423,16 +426,32 @@<div class="form-group"><input type="text" name="fixer-key" id="fixerKey" value="<?= $apiKey ?>" placeholder="<?= translate('api_key', $i18n) ?>"></div>+ <div class="form-group">+ <label for="fixerProvider"><?= translate('provider', $i18n) ?>:</label>+ <select name="fixer-provider" id="fixerProvider">+ <option value="0" <?= $provider == 0 ? 'selected' : '' ?>>fixer.io</option>+ <option value="1" <?= $provider == 1 ? 'selected' : '' ?>>apilayer.com</option>+ </select>+ </div><div class="settings-notes"><p><i class="fa-solid fa-circle-info"></i><?= translate('fixer_info', $i18n) ?></p><p><?= translate('get_key', $i18n) ?>:<span>https://fixer.io/- <a href="https://fixer.io/#pricing_plan" title="Get free fixer api key" target="_blank">+ <a href="https://fixer.io/#pricing_plan" title="<?= translate("get_free_fixer_api_key", $i18n) ?>" target="_blank">+ <i class="fa-solid fa-arrow-up-right-from-square"></i>+ </a>+ </span>+ </p>+ <p>+ <?= translate("get_key_alternative", $i18n) ?>+ <span>+ https://apilayer.com+ <a href="https://apilayer.com/marketplace/fixer-api" title="Get free fixer api key" target="_blank"><i class="fa-solid fa-arrow-up-right-from-square"></i></a></span>- </p>+ </p></div><div class="buttons"><input type="submit" value="<?= translate('save', $i18n) ?>" id="addFixerKey" onClick="addFixerKeyButton()"/>