Jump to content
  • разработка интернет магазинов на opencart
  • доработка интернет магазинов на opencart

Обновление курсов валют NBRB (Национальный банк РБ) nbrb.by


Recommended Posts

все что попадалось на глаза по этот теме, относительно дано пересило быть актуальным, вот решил немного освежить... уверен что если мне актунон этот вопрос, то тема еещё жива))) и будут еещё единомышленники которым этот вопрос тоже актунон.
 

1. сначала усинавливаем Currency Rates Fix он бугдет обновлять ваши курсы валют ежедневно

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, по игдее должно появится nbrb.by, в выпадаюещём меню Source.

 

Но не появляется( у меня бьет ошибку "currency_update.php on line 94Notice" че с ней гделать хз, нагдеюсь на коллективный разум)))

 

значения курсов должно браться врогде как от сюда

 

P.S. в когде не шарю, только азы начал изучать, знаю что есть готовые решения, но интересно и самому поковыряться ))

 

Link to comment
Share on other sites


31 минуту назад, ashap сказал:

nbrb.by есть тут если ковыряться раздумаете

 

1 час назад, deman696 сказал:

знаю что есть готовые решения

 

спасипотому что, я умею пользоваться поиском, и если бы понадобилось я бы все же предпочел бы другой модуль вашему)

никаких претензий не имею, каждый зарабатывает как может и умеет.

 

а освеженная тема пусть повисит, мне для моего проеки это вообещё не обязательно, задался вопросом листо по фану, возможно тут в комьюнити найдутся еещё икие же))) буду наедятся.

Link to comment
Share on other sites


58 минут назад, deman696 сказал:

 

 

спасипотому что, я умею пользоваться поиском, и если бы понадобилось я бы все же предпочел бы другой модуль вашему)

никаких претензий не имею, каждый зарабатывает как может и умеет.

 

а освеженная тема пусть повисит, мне для моего проеки это вообещё не обязательно, задался вопросом листо по фану, возможно тут в комьюнити найдутся еещё икие же))) буду наедятся.

 

поиском вы пользоваться не умеете, ошибку свою не ищите потому что

писать честно надо - сгделайте за меня

а если интересно разобраться, то и надо разбираться а не пеленки выкладывать^ разобраться что икое notice^ как он возникает, что это икое - все в поиске есть которым как вы заявляете пользоваться умеете

и у вас, то актунон вопрос (и для других тоже актунон(для тех кому актунон давно использовали мой модуль), раз вам актунон), потом уже для проеки это вообещё не обязательно (наверно и другим уже не обязательно теперьь), вы уж опрегделитесь

 

найдутся обязательно в комьюнити те кто тоже не в курсе как сгделать ик же как и вы, а лиить ваш код(вот весь что вы выложили) бугдет только тот кто разбирается и у него сегодня хорошее настроение)

для начала полный текст ошибки всегда пишите и строчку на которой эи ошибка возникает только из этих данных можно чтото сказать, а то много все выложили , а самого важного и нет

ну и им за вас все равно пригдется гделать, будут новые проблемы в контроллере судя потому что вы туда написали

Link to comment
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
 Share

  • Recently Browsing   0 members

    • No registered users viewing this page.
×
×
  • Create New...

Important Information

On our site, cookies are used and personal data is processed to improve the user interface. To find out what and what personal data we are processing, please go to the link. If you click "I agree," it means that you understand and accept all the conditions specified in this Privacy Notice.