Title: Extension module with API request
Last modified: October 7, 2024

---

# Extension module with API request

 *  [piquepique](https://wordpress.org/support/users/piquepique/)
 * (@piquepique)
 * [1 year, 8 months ago](https://wordpress.org/support/topic/extension-module-with-api-request/)
 * Hello
 * I’m using the DIVI, in DIVI i’ve added a “Code” block with the following code:
 *     ```wp-block-code
       async function fetchExchangeRate() {  const apiKey = ''; // Ta clé API  const response = await fetch(https://api.exchangerate.host/live?access_key=${apiKey}&source=CHF&currencies=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 :
 *     ```wp-block-code
       <?php/*Plugin Name: API Taux de ChangeDescription: Plugin pour récupérer le taux de change CHF/EUR.Version: 1.0Author: Ton Nom*/// Fonction pour récupérer le taux de changefunction 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&currencies=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 JavaScriptfunction 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é serveuradd_action('wp_ajax_get_exchange_rate', 'get_exchange_rate');add_action('wp_ajax_nopriv_get_exchange_rate', 'get_exchange_rate');
       ```
   
 * script.js :
 *     ```wp-block-code
       // script.jsasync 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 saisiedocument.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
 *     ```wp-block-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)

 *  Moderator [t-p](https://wordpress.org/support/users/t-p/)
 * (@t-p)
 * [1 year, 8 months ago](https://wordpress.org/support/topic/extension-module-with-api-request/#post-18059051)
 * Since that is a commercial theme (Divi), we ask that you please go to their official
   support channel, so you can get support from the people who know it best.
 * [https://www.elegantthemes.com/gallery/divi/](https://www.elegantthemes.com/gallery/divi/)
 * Forum volunteers are also not given access to commercial products, so they would
   not know why it is not working properly. Other community members who may have
   faced your issue might be able to help you but your best bet is your product’s
   developer. Keep in mind we encourage you to use the official support venues, 
   as it allows the developers to be aware of issues with their code and gives back
   to the community in a more robust way.
 *  Moderator [threadi](https://wordpress.org/support/users/threadi/)
 * (@threadi)
 * [1 year, 8 months ago](https://wordpress.org/support/topic/extension-module-with-api-request/#post-18059058)
 * What _exactly _is not working? You have included some debug lines – do they give
   output?

Viewing 2 replies - 1 through 2 (of 2 total)

The topic ‘Extension module with API request’ is closed to new replies.

## Tags

 * [ajaxurl](https://wordpress.org/support/topic-tag/ajaxurl/)
 * [api](https://wordpress.org/support/topic-tag/api/)

 * In: [Developing with WordPress](https://wordpress.org/support/forum/wp-advanced/)
 * 2 replies
 * 3 participants
 * Last reply from: [threadi](https://wordpress.org/support/users/threadi/)
 * Last activity: [1 year, 8 months ago](https://wordpress.org/support/topic/extension-module-with-api-request/#post-18059058)
 * Status: not resolved

## Topics

### Topics with no replies

### Non-support topics

### Resolved topics

### Unresolved topics

### All topics
