Обновления валют РБ OpenCart 3.0.2

Обновления валют РБ OpenCart Хотим поделиться с вами накопленным опытом и рассказать, как получить обновления валют OpenCart 3.0.2 Национального Банка Беларуси. Все предельно просто: Ставим этот модуль и он будет обновлять ваши курсы валют ежедневно,  https://www.opencart.com/index.p...

Обновления валют РБ OpenCart


Хотим поделиться с вами накопленным опытом и рассказать, как получить обновления валют OpenCart 3.0.2 Национального Банка Беларуси. Все предельно просто:
  1. Ставим этот модуль и он будет обновлять ваши курсы валют ежедневно,  https://www.opencart.com/index.php?route=marketplace/extension/info&extension_id=32352
  2. Далее, заменяем один из методов источника получения курсов на свой nbrb.by
    admin/view/template/extension/module/currency_update.twig
    
    {{ header }}{{ column_left }}
    <div id="content">
      <div class="page-header">
        <div class="container-fluid">
          <div class="pull-right">
            <a href="{{ update }}" onClick="$(this).text('{{ text_loading }}');" data-toggle="tooltip" title="{{ button_update }}" class="btn btn-warning"><i class="fa fa-refresh"></i></a>
            <button type="submit" form="form-module" data-toggle="tooltip" title="{{ button_save }}" class="btn btn-primary"><i class="fa fa-save"></i></button>
            <a href="{{ cancel }}" data-toggle="tooltip" title="{{ button_cancel }}" class="btn btn-default"><i class="fa fa-reply"></i></a>
          </div>
          <h1>{{ heading_title }}</h1>
          <ul class="breadcrumb">
            {% for breadcrumb in breadcrumbs %}
              <li><a href="{{ breadcrumb.href }}">{{ breadcrumb.text }}</a></li>
            {% endfor %}
          </ul>
        </div>
      </div>
      <div class="container-fluid">
        {% if error_success %}
          <div class="alert alert-success alert-dismissible"><i class="fa fa-exclamation-circle"></i> {{ error_success }}
            <button type="button" class="close" data-dismiss="alert">&times;</button>
          </div>
        {% endif %}
        {% if error_warning %}
          <div class="alert alert-danger alert-dismissible"><i class="fa fa-exclamation-circle"></i> {{ error_warning }}
            <button type="button" class="close" data-dismiss="alert">&times;</button>
          </div>
        {% endif %}
        <div class="panel panel-default">
          <div class="panel-heading">
            <h3 class="panel-title"><i class="fa fa-pencil"></i> {{ text_edit }}</h3>
          </div>
          <div class="panel-body">
            <form action="{{ action }}" method="post" enctype="multipart/form-data" id="form-module" class="form-horizontal">
              <div class="form-group">
                <label class="col-sm-2 control-label" for="entry-autoupdate"><span data-toggle="tooltip" title="{{ help_autoupdate }}">{{ entry_autoupdate }}</span></label>
                <div class="col-sm-10">
                  <select name="module_currency_update_autoupdate" id="input-autoupdate" class="form-control">
                    <option value="1"{{ module_currency_update_autoupdate ? ' selected="selected"' : '' }}>{{ text_enabled }}</option>
                    <option value="0"{{ module_currency_update_autoupdate ? '' : ' selected="selected"' }}>{{ text_disabled }}</option>
                  </select>
                </div>
              </div>
              <div class="form-group">
                <label class="col-sm-2 control-label" for="entry-comission"><span data-toggle="tooltip" title="{{ help_comission }}">{{ entry_comission }}</span></label>
                <div class="col-sm-10">
                  <input name="module_currency_update_comission" id="input-comission" value="{{ module_currency_update_comission }}"  class="form-control" />
                  {% if error_comission %}
                    <div class="text-danger">{{ error_comission }}</div>
                  {% endif %}
                </div>
              </div>
              <div class="form-group">
                <label class="col-sm-2 control-label" for="entry-source"><span data-toggle="tooltip" title="{{ help_source }}">{{ entry_source }}</span></label>
                <div class="col-sm-10">
                  <select name="module_currency_update_source" id="input-source" class="form-control">
                    <option value="alphavantage.co"{{ module_currency_update_source == 'alphavantage.co' ? ' selected="selected"' : '' }}>{{ text_source_alphavantage }}</option>
                    <option value="fixer.io"{{ module_currency_update_source == 'fixer.io' ? ' selected="selected"' : '' }}>{{ text_source_fixer }}</option>
                    <option value="xe.com"{{ module_currency_update_source == 'xe.com' ? ' selected="selected"' : '' }}>{{ text_source_xe }}</option>
                    <option value="nbrb.by"{{ module_currency_update_source == 'nbrb.by' ? ' selected="selected"' : '' }}>{{ text_source_nbrb }}</option>
                  </select>
                </div>
              </div>
              <div class="form-group optional" data-source="alphavantage.co"{{ module_currency_update_source == 'alphavantage.co' ? '' : ' style="display:none;"' }}>
                <label class="col-sm-2 control-label" for="input-alphavantage-api-key"><span data-toggle="tooltip" title="{{ help_alphavantage_api_key }}">{{ entry_alphavantage_api_key }}</span></label>
                <div class="col-sm-6">
                  <input name="module_currency_update_alphavantage_api_key" value="{{ module_currency_update_alphavantage_api_key }}" id="input-alphavantage-api-key" class="form-control" />
                  {% if error_alphavantage_api_key %}
                    <div class="text-danger">{{ error_alphavantage_api_key }}</div>
                  {% endif %}
                </div>
                <div class="col-sm-4">
                  <div class="alert alert-info alert-dismissible" style="margin:0;padding:8px 10px 8px 10px;"><i class="fa fa-exclamation-circle"></i> {{ text_alphavantage_api_key }}</div>
                </div>
              </div>
              <div class="form-group optional" data-source="fixer.io"{{ module_currency_update_source == 'fixer.io' ? '' : ' style="display:none;"' }}>
                <label class="col-sm-2 control-label" for="input-fixer-api-key"><span data-toggle="tooltip" title="{{ help_fixer_api_key }}">{{ entry_fixer_api_key }}</span></label>
                <div class="col-sm-6">
                  <input name="module_currency_update_fixer_api_key" value="{{ module_currency_update_fixer_api_key }}" id="input-fixer-api-key" class="form-control" />
                  {% if error_fixer_api_key %}
                    <div class="text-danger">{{ error_fixer_api_key }}</div>
                  {% endif %}
                </div>
                <div class="col-sm-4">
                  <div class="alert alert-info alert-dismissible" style="margin:0;padding:8px 10px 8px 10px;"><i class="fa fa-exclamation-circle"></i> {{ text_fixer_api_key }}</div>
                </div>
              </div>
              <div class="form-group">
                <label class="col-sm-2 control-label" for="input-debug">{{ entry_debug }}</label>
                <div class="col-sm-10">
                  <select name="module_currency_update_debug" id="input-debug" class="form-control">
                    <option value="1"{{ module_currency_update_debug ? ' selected="selected"' : '' }}>{{ text_enabled }}</option>
                    <option value="0"{{ module_currency_update_debug ? '' : ' selected="selected"' }}>{{ text_disabled }}</option>
                  </select>
                </div>
              </div>
              <div class="form-group">
                <label class="col-sm-2 control-label" for="input-status">{{ entry_status }}</label>
                <div class="col-sm-10">
                  <select name="module_currency_update_status" id="input-status" class="form-control">
                    <option value="1"{{ module_currency_update_status ? ' selected="selected"' : '' }}>{{ text_enabled }}</option>
                    <option value="0"{{ module_currency_update_status ? '' : ' selected="selected"' }}>{{ text_disabled }}</option>
                  </select>
                </div>
              </div>
            </form>
          </div>
        </div>
      </div>
    </div>
    <script type="text/javascript">
      $('select[name="module_currency_update_source"]').on('change', function() {
        var sel = $('option:selected', $(this)).val();
        $('.optional[data-source!="'+sel+'"]').hide();
        $('.optional[data-source="'+sel+'"]').show();
      });
    </script>
    {{ footer }}
    admin/language/en-gb/extension/module/currency_update.php
    <?php
    // Heading
    $_['heading_title']           = 'Currency Update';
    
    // Text
    $_['text_extension']          = 'Extensions';
    $_['text_success']            = 'Success: You have modified currency update module!';
    $_['text_update_success']        = 'Success: You have updated currencies!';
    $_['text_update_error']          = 'Warning: Currency update failed!';
    $_['text_edit']               = 'Edit Currency Update Module';
    $_['text_source_alphavantage']   = 'alphavantage.co';
    $_['text_source_fixer']         = 'fixer.io (recommended)';
    $_['text_source_xe']            = 'xe.com';
    $_['text_source_nbrb']              = 'nbrb.by';
    $_['text_alphavantage_api_key']  = 'Get the API key <a target="_blank" href="https://www.alphavantage.co/support/#api-key">here</a>.';
    $_['text_fixer_api_key']  = 'Get the API key <a target="_blank" href="https://www.fixer.co/support/#api-key">here</a>.';
    
    // Entry
    $_['entry_status']               = 'Status';
    $_['entry_source']               = 'Source';
    $_['entry_autoupdate']           = 'Auto Update';
    $_['entry_comission']            = 'Exchange Comission';
    $_['entry_debug']                = 'Debug';
    $_['entry_alphavantage_api_key'] = 'API key';
    $_['entry_fixer_api_key'] = 'API key';
    
    // Help
    $_['help_source']                = 'Source of the currency information. If one isnt working, try another';
    $_['help_autoupdate']            = 'Enable to update automatically once a day when you login to admin.';
    $_['help_comission']             = 'Apply comission to exchange rate, value represents percentage.';
    $_['help_fixer_api_key']  = 'The service is free but you must get an API key to use it.';
    $_['help_alphavantage_api_key']  = 'The service is free but you must get an API key to use it.';
    
    // Button
    $_['button_update']              = 'Update Currencies Now';
    
    // Error
    $_['error_permission']           = 'Warning: You do not have permission to modify currency update module!';
    $_['error_fixer_api_key'] = 'You must set the API key!';
    $_['error_alphavantage_api_key'] = 'You must set the API key!';
    $_['error_comission']            = 'Comission must be a percentage value, example : 2.5';
    admin/model/extension/module/currency_update.php
    <?php
    class ModelExtensionModuleCurrencyUpdate extends Model {
    
        protected $log_instance;
    
        public function __construct($registry) {
            parent::__construct($registry);
    
            error_reporting(-1);
            ini_set('display_errors', 1);
            $this->log_instance = new Log('currency_update.log');
        }
    
        public function update($force = false) {
    
            if ($this->config->get('module_currency_update_status') == 0) {
                return false;
            }
    
            if ($this->config->get('module_currency_update_autoupdate') == 1 || $force) {
    
                $comission = $this->config->get('module_currency_update_comission') > 0 ? (float) $this->config->get('module_currency_update_comission') / 100 : false;
                $base_currency = $this->config->get('config_currency');
    
                $sql = "SELECT * FROM " . DB_PREFIX . "currency WHERE code != '" . $this->db->escape($this->config->get('config_currency')) . "'";
    
                if (!$force) {
                    $sql .= " AND date_modified < '" .  $this->db->escape(date('Y-m-d H:i:s', strtotime('-1 day'))) . "'";
                }
    
                $query = $this->db->query($sql);
    
                $currency_codes = array();
                $rates = array();
    
                foreach ($query->rows as $result) {
                    $currency_codes[] = $result['code'];
                    $rates[$result['code']] = 1;
                }
    
    
                // nbrb.by
                if ($this->config->get('module_currency_update_source') == 'nbrb.by') {
    
    
                    $d = new DateTime();
                    $response = $this->curlRequest("http://www.nbrb.by/Services/XmlExRates.aspx?ondate=" . $d->format('m/d/Y'));
    
                    if ($response) {
                        $currenciesRF = simplexml_load_string($response);
    
                        /* Ошибка выходим */
                        if (!$currenciesRF || count($currenciesRF) == 0) {
                            return false;
                        }
    
    
                        foreach ($currenciesRF as $currency) {
                            $rates[(string)$currency->CharCode] = (string)$currency->Rate / (string)$currency->Scale;
                        }
    
    
                        foreach ($rates as $code => $val) {
                            if ($code != $base_currency) {
                                $rates[$code] = $rates[$base_currency] / $val;
                            }
                        }
                        foreach ($rates as $code => $value) {
                            $value_ = $comission ? (float)$rates[$code] + ((float)$rates[$code] * $comission) : $rates[$code];
                            $this->db->query("UPDATE " . DB_PREFIX . "currency SET value = '" . $this->db->escape($value_) . "', date_modified = '" . $this->db->escape(date('Y-m-d H:i:s')) . "' WHERE code = '" . $this->db->escape($code) . "'");
                        }
    
    
    
                        //$this->db->query("UPDATE " . DB_PREFIX . "currency SET value = '1.00000', date_modified = '" . $this->db->escape(date('Y-m-d H:i:s')) . "' WHERE code = '" . $this->db->escape($base_currency) . "'");
                    } else {
                        return false;
                    }
                }
    
    
    
    
                // fixer.io
                if ($this->config->get('module_currency_update_source') == 'fixer.io') {
    
                    $api_key = $this->config->get('module_currency_update_fixer_api_key');
                    $response = $this->curlRequest('http://data.fixer.io/api/latest?access_key='.$api_key.'&base='.$base_currency.'&symbols='.implode(',', $currency_codes));
    
                    if ($response) {
                        $json = json_decode($response);
    
                        foreach ($currency_codes as $code) {
                            $value = $comission ? (float) $json->rates->{$code} + ((float) $json->rates->{$code} * $comission) : $json->rates->{$code};
                            $this->db->query("UPDATE " . DB_PREFIX . "currency SET value = '" . $this->db->escape($value) . "', date_modified = '" .  $this->db->escape(date('Y-m-d H:i:s')) . "' WHERE code = '" . $this->db->escape($code) . "'");
                        }
    
                        $this->db->query("UPDATE " . DB_PREFIX . "currency SET value = '1.00000', date_modified = '" .  $this->db->escape(date('Y-m-d H:i:s')) . "' WHERE code = '" . $this->db->escape($base_currency) . "'");
                    } else {
                        return false;
                    }
    
                    // alphavantage.co
                } elseif ($this->config->get('module_currency_update_source') == 'alphavantage.co') {
    
                    $api_key = $this->config->get('module_currency_update_alphavantage_api_key');
    
                    foreach ($currency_codes as $code) {
                        $response = $this->curlRequest('https://www.alphavantage.co/query?function=CURRENCY_EXCHANGE_RATE&from_currency='.$base_currency.'&to_currency='.$code.'&apikey='.$api_key);
    
                        if ($response) {
                            $json = json_decode($response);
    
                            if (@is_null($json->{"Error Message"})) {
                                $value = (float) $json->{"Realtime Currency Exchange Rate"}->{"5. Exchange Rate"};
                                $value = $comission ? $value + ($value * $comission) : $value;
                                $this->db->query("UPDATE " . DB_PREFIX . "currency SET value = '" . $this->db->escape($value) . "', date_modified = '" .  $this->db->escape(date('Y-m-d H:i:s')) . "' WHERE code = '" . $this->db->escape($code) . "'");
                            } else {
                                $this->log('alphavantage error : '.$json->{"Error Message"});
                                return false;
                            }
                        } else {
                            return false;
                        }
                    }
    
                    $this->db->query("UPDATE " . DB_PREFIX . "currency SET value = '1.00000', date_modified = '" .  $this->db->escape(date('Y-m-d H:i:s')) . "' WHERE code = '" . $this->db->escape($base_currency) . "'");
    
                    // xe.com
                } elseif ($this->config->get('module_currency_update_source') == 'xe.com') {
    
                    foreach ($currency_codes as $code) {
                        $response = $this->curlRequest('http://xe.com/currencyconverter/convert.cgi?template=pca-new&Amount=1&From='.$base_currency.'&To='.$code.'&image.x=64&image.y=8&image=Submit');
    
                        if ($response) {
                            $dom = new DomDocument();
                            $internalErrors = libxml_use_internal_errors(true);
                            $dom->loadHTML($response);
                            $xpath = new DomXPath($dom);
                            $nodes = $xpath->query('//span[@class="XEenlarge"]');
    
                            $value = (float) trim(str_replace(array($code, ','), '', $nodes->item(2)->nodeValue));
    
                            $value = $comission ? $value + ($value * $comission) : $value;
                            $this->db->query("UPDATE " . DB_PREFIX . "currency SET value = '" . $this->db->escape($value) . "', date_modified = '" .  $this->db->escape(date('Y-m-d H:i:s')) . "' WHERE code = '" . $this->db->escape($code) . "'");
    
                            libxml_use_internal_errors($internalErrors);
                        } else {
                            $this->log('xe.com error : no response from curl');
                            return false;
                        }
                    }
    
                    $this->db->query("UPDATE " . DB_PREFIX . "currency SET value = '1.00000', date_modified = '" .  $this->db->escape(date('Y-m-d H:i:s')) . "' WHERE code = '" . $this->db->escape($base_currency) . "'");
                } else {
                    return false;
                }
    
                $this->cache->delete('currency');
    
                return true;
            }
        }
    
        private function curlRequest($url, $options = array()) {
    
            $this->log('Curl init : '.$url);
    
            $ch = curl_init();
    
            curl_setopt($ch, CURLOPT_URL, $url);
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    
            $result = curl_exec($ch);
            $info = curl_getinfo($ch);
    
            if (curl_error($ch)) {
                $this->log('Curl error : '.curl_error($ch));
                return false;
            }
    
            if (in_array($info['http_code'], array(401,403,404))) {
                $this->log('Curl error : '.$info['http_code'].' header status');
                return false;
            }
    
            return $result;
        }
    
        private function log($str) {
            if ($this->config->get('module_currency_update_debug') == 1) {
                $this->log_instance->write($str);
            }
        }
    
    }
    
    3. Создаем нашу валюту BYN в настройках валют "Система-Локализация-Валюта" и включаем ее:
4. Настраиваем модуль CurrencyUpdate OpenCart 3.0.2:

5. Жмем кнопку "Обновить" валюта обновиться, и 1 раз в день валюта будет обновляться автоматически по правилам модуля CurrencyUpdate. В зависимости от выбранной валюты по умолчанию курс пересчитывается. Вот так выглядят курсы в нац банке http://www.nbrb.by/Services/XmlExRates.aspx?ondate=07/05/2019


Создаем сайты и работаем с модулями на любых CMS. Вы всегда можете воспользоваться нашими услугами и заказать сайт в Минске, Бресте, в любом городе и стране!

Есть вопросы? Давайте, мы перезвоним Вам в течение 40 секунд!

ЗАКАЗАТЬ ЗВОНОК
Создание сайтов в Бресте, заказать сайт или интернет-магазин| Брест Веб-студия Юникодинг г. Брест ул. Воровского, 31 +375(29)793-67-92
Наверх