feat: add apilayer as provider for fixer api (#127)

feat: add apilayer as provider for fixer api
feat: update exchange rate when saving api key
This commit is contained in:
Miguel Ribeiro 2024-02-20 00:37:38 +01:00 committed by GitHub
parent e726b5c0bf
commit 0f19dd688f
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
17 changed files with 142 additions and 31 deletions

View File

@ -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)]);

View File

@ -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 ($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;
}
}
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];

View File

@ -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();
}
?>
?>

View File

@ -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",

View File

@ -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" => "Υπολογισμός και εμφάνιση της μηνιαίας τιμής για όλες τις συνδρομές",

View File

@ -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",

View File

@ -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",

View File

@ -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",

View File

@ -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" => "すべての定期購入の月額料金を計算して表示する",

View File

@ -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",

View File

@ -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" => "ık / Koyu Temayı Değiştir",
"calculate_monthly_price" => "Tüm aboneliklerin aylık fiyatını hesaplayın ve gösterin",

View File

@ -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" => "计算并显示所有订阅的月价格",

View File

@ -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" => "計算並顯示所有訂閱的每月價格",

View File

@ -1,3 +1,3 @@
<?php
$version = "v1.2.5";
$version = "v1.3.0";
?>

12
migrations/000006.php Normal file
View File

@ -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');
}

View File

@ -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;

View File

@ -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>
<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>
</div>
<div class="buttons">
<input type="submit" value="<?= translate('save', $i18n) ?>" id="addFixerKey" onClick="addFixerKeyButton()"/>