Extension module with API request
-
Hello
I’m using the DIVI, in DIVI i’ve added a “Code” block with the following code :
async function fetchExchangeRate() {
const apiKey = ''; // Ta clé API
const response = await fetch(https://api.exchangerate.host/live?access_key=${apiKey}&source=CHF¤cies=EUR&format=1
);
const data = await response.json();
if (data.success) {
return data.quotes['CHFEUR']; // Retourne le taux CHF/EUR
} else {
console.error('Error fetching exchange rate:', data.error);
return null;
}
}
<style>
#currency-converter {
font-family: 'Arial', sans-serif;
font-weight: normal;
}
#currency-converter label,
#currency-converter input,
#currency-converter p {
font-family: 'Verdana', sans-serif;
}
</style>
<div id="currency-converter">
<label for="chf-input">Entrez le montant en CHF :</label>
<input type="number" id="chf-input" placeholder="0" />
<p id="exchange-rate">Taux de change CHF/EUR : <span id="rate-value"></span></p>
<p id="bank-result">Banques : <span id="bank-value"></span></p>
<p id="provider1-result">Prestataire 1 : <span id="provider1-value"></span></p>
<p id="provider2-result">Prestataire 2 : <span id="provider2-value"></span></p>
</div>
<script>
document.addEventListener('DOMContentLoaded', function() {
const inputField = document.getElementById('chf-input');
const rateField = document.getElementById('rate-value');
const bankResultField = document.getElementById('bank-value');
const provider1ResultField = document.getElementById('provider1-value');
const provider2ResultField = document.getElementById('provider2-value');
// Appel de la fonction pour récupérer le taux de change
async function fetchExchangeRate() {
try {
const response = await fetch(fetchExchangeRate.ajax_url + '?action=get_exchange_rate');
const data = await response.json();
if (data.rate) {
console.log('Taux de change:', data.rate); // Log pour vérifier le taux
return data.rate; // Retourne le taux CHF/EUR
} else {
console.error('Error fetching exchange rate:', data.error);
return null;
}
} catch (error) {
console.error('Fetch Error:', error); // Log pour les erreurs de fetch
}
}
async function convertCurrency() {
const chfAmount = parseFloat(inputField.value);
if (isNaN(chfAmount) || chfAmount <= 0) {
clearResults();
return;
}
const exchangeRate = await fetchExchangeRate();
if (exchangeRate) {
rateField.textContent = exchangeRate.toFixed(4); // Affichage du taux de change
// Calcul des résultats avec les pourcentages modifiés
const bankRate = exchangeRate * (1 - 0.02);
bankResultField.textContent = (chfAmount * bankRate).toFixed(2).replace(/\B(?=(\d{3})+(?!\d))/g, ' ');
// Calcul pour provider 1 en fonction des plages de montants
let provider1Rate;
let adjustedAmount = chfAmount;
if (adjustedAmount < 5000) {
adjustedAmount -= 5; // Retirer 5 CHF du montant saisi
provider1Rate = exchangeRate * (1 - 0.05);
} else if (adjustedAmount >= 5000 && adjustedAmount <= 49999) {
provider1Rate = exchangeRate * (1 - 0.005);
} else if (adjustedAmount >= 50000 && adjustedAmount <= 99999) {
provider1Rate = exchangeRate * (1 - 0.004);
} else if (adjustedAmount >= 100000 && adjustedAmount <= 249999) {
provider1Rate = exchangeRate * (1 - 0.0025);
} else if (adjustedAmount >= 250000 && adjustedAmount <= 1000000) {
provider1Rate = exchangeRate * (1 - 0.0012);
}
if (provider1Rate) {
provider1ResultField.textContent = (adjustedAmount * provider1Rate).toFixed(2).replace(/\B(?=(\d{3})+(?!\d))/g, ' ');
} else {
provider1ResultField.textContent = '';
}
// Calcul pour provider 2 (0.25% peu importe le montant)
const provider2Rate = exchangeRate * (1 - 0.0025);
provider2ResultField.textContent = (chfAmount * provider2Rate).toFixed(2).replace(/\B(?=(\d{3})+(?!\d))/g, ' ');
}
}
function clearResults() {
rateField.textContent = '';
bankResultField.textContent = '';
provider1ResultField.textContent = '';
provider2ResultField.textContent = '';
}
inputField.addEventListener('input', convertCurrency);
});
</script>This works perfectly. But if you inspect the code, of course, we found the API key that’s not clean
I’ve tried to create a WordPress extension, i’ve created a folder /wp-content/plugins/fetch-exchange-rate with 2 files
fetch-exchange-rate-api.php :
<?php
/*
Plugin Name: API Taux de Change
Description: Plugin pour récupérer le taux de change CHF/EUR.
Version: 1.0
Author: Ton Nom
*/
// Fonction pour récupérer le taux de change
function get_exchange_rate() {
error_log('get_exchange_rate function called'); // Log pour vérifier l'appel
$apiKey = '';
$apiUrl = "https://api.exchangerate.host/live?access_key={$apiKey}&source=CHF¤cies=EUR&format=1";
// Effectuer la requête à l'API
$response = wp_remote_get($apiUrl);
if (is_wp_error($response)) {
error_log('API Request Error: ' . $response->get_error_message());
echo json_encode(['error' => 'Failed to retrieve exchange rate']);
wp_die();
}
// Récupérer et retourner le taux de change
$body = wp_remote_retrieve_body($response);
$data = json_decode($body, true);
if (isset($data['success']) && $data['success']) {
$rate = $data['quotes']['CHFEUR'];
echo json_encode(['rate' => $rate]);
} else {
error_log('Invalid API Response: ' . print_r($data, true));
echo json_encode(['error' => 'Failed to retrieve valid data']);
}
wp_die(); // Arrêter l'exécution après l'envoi de la réponse
}
// Enqueue le script JavaScript
function fetch_exchange_rate_enqueue_scripts() {
wp_enqueue_script('fetch-exchange-rate-script', plugin_dir_url(__FILE__) . 'script.js', array(), '1.0', true);
wp_localize_script('fetch-exchange-rate-script', 'fetchExchangeRate', array(
'ajax_url' => admin_url('admin-ajax.php'), // Vérifiez cette ligne
));
}
add_action('wp_enqueue_scripts', 'fetch_exchange_rate_enqueue_scripts');
// Ajouter une route AJAX pour l'appel c?té serveur
add_action('wp_ajax_get_exchange_rate', 'get_exchange_rate');
add_action('wp_ajax_nopriv_get_exchange_rate', 'get_exchange_rate');script.js :
// script.js
async function fetchExchangeRate() {
try {
const response = await fetch(fetchExchangeRate.ajax_url + '?action=get_exchange_rate');
const data = await response.json();
if (data.rate) {
console.log('Taux de change:', data.rate); // Log pour vérifier le taux
return data.rate; // Retourne le taux CHF/EUR
} else {
console.error('Error fetching exchange rate:', data.error);
return null;
}
} catch (error) {
console.error('Fetch Error:', error); // Log pour les erreurs de fetch
}
}
// écouteur d'événement pour le champ de saisie
document.getElementById('chf-input').addEventListener('input', async function() {
const amount = parseFloat(this.value);
if (isNaN(amount) || amount <= 0) {
console.error('Montant invalide');
return;
}
const rate = await fetchExchangeRate();
if (rate) {
console.log('Montant en CHF:', amount);
const convertedAmount = (amount * rate).toFixed(2);
console.log('Montant converti en EUR:', convertedAmount);
// Ici, tu pourrais mettre à jour un élément de la page pour afficher le montant converti
}
});The goal is to change the function fetchExchangeRate from my frist code to something like following code
try {
const response = await fetch(fetchExchangeRate.ajax_url + '?action=get_exchange_rate');
const data = await response.json();
if (data.rate) {
console.log('Taux de change:', data.rate); // Log pour vérifier le taux
return data.rate; // Retourne le taux CHF/EUR
} else {
console.error('Error fetching exchange rate:', data.error);
return null;
}
} catch (error) {
console.error('Fetch Error:', error); // Log pour les erreurs de fetch
}
}Sadly it doesn’t work. What is wrong ? What should i fix ?
Thanks a lot
Viewing 2 replies - 1 through 2 (of 2 total)
Viewing 2 replies - 1 through 2 (of 2 total)
- You must be logged in to reply to this topic.