diff --git a/README.md b/README.md index 6187f0d..6324834 100644 --- a/README.md +++ b/README.md @@ -1,93 +1,96 @@ -# woocommerce +# 🌟 Платёжный модуль PayAnyWay для [WooCommerce](https://woocommerce.com/) ([WordPress](https://wordpress.org/)) -Платежный модуль WordPress WooCommerce +![WooCommerce](https://img.shields.io/badge/WooCommerce-9.8.x%2B-0070C0?logo=php&logoColor=white) +![WordPress](https://img.shields.io/badge/WordPress-7.0.x%2B-0070C0?logo=php&logoColor=white) +![PHP](https://img.shields.io/badge/PHP-5.6%2B-purple) +![License](https://img.shields.io/badge/License-MIT-green) -## Getting started +> **📦 Версия модуля: 1.5.0** -To make it easy for you to get started with GitLab, here's a list of recommended next steps. +> **ℹ️ Примечание по валюте** +> Данный модуль работает **только с валютой RUB (Российский рубль)**. +> Перед активацией модуля убедитесь, что на сайте в качестве базовой валюты установлен RUB, либо у пользователя выбран счёт в RUB. Использование других валют не поддерживается. -Already a pro? Just edit this README.md and make it your own. Want to make it easy? [Use the template at the bottom](#editing-this-readme)! - -## Add your files - -* [Create](https://docs.gitlab.com/user/project/repository/web_editor/#create-a-file) or [upload](https://docs.gitlab.com/user/project/repository/web_editor/#upload-a-file) files -* [Add files using the command line](https://docs.gitlab.com/topics/git/add_files/#add-files-to-a-git-repository) or push an existing Git repository with the following command: +## 🏗️ Структура модуля ``` -cd existing_repo -git remote add origin https://git.moneta.ru:8000/products/cashier/cms/wordpress/woocommerce.git -git branch -M main -git push -uf origin main +. +├── payanyway/ +│ ├── assets/ +│ │ ├── css/paw-main.css +│ │ └── images/payanyway.png +│ ├── includes/settings/settings-paw.php +│ ├── block-support.php +│ ├── blocks.js +│ └── wc-payanyway.php +└── README.md ``` -## Integrate with your tools +## 🚀 Установка и настройка модуля -* [Set up project integrations](https://git.moneta.ru:8000/products/cashier/cms/wordpress/woocommerce/-/settings/integrations) +1. 📥 [Скачайте архив модуля](https://git.pub.moneta.ru/CMS/WordPress-WooCommerce/releases). +2. 📂 Загрузите плагин через панель управления интернет-магазином. + Выберите раздел **"Плагины"** → **"Добавить плагин"**. Нажмите **"Загрузить плагин"**, выберите скачанный архив и нажмите **"Установить сейчас"**. + Произойдёт установка плагина из загруженного архива. Далее нажмите **"Активировать плагин"**. + В списке найдите плагин **"Монета | PayAnyWay"** и нажмите **"Активировать"**. +3. ⚙️ В разделе **"Платежи"** нажмите **"Включить"** для активации способа оплаты и нажмите **"Править"**. +4. ✏️ Заполните соответствующие поля в настройках способа оплаты: -## Collaborate with your team +| Поле | Описание | +|-------------------------------------|---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| +| **Включить/Выключить** | Включите или выключите модуль оплаты | +| **Название** | `PayAnyWay` | +| **Номер счёта** | Ваш номер расширенного счёта в системе [MONETA.RU](https://moneta.ru/) | +| **Код проверки целостности данных** | Код проверки целостности данных, указанный в настройках расширенного счёта в системе [MONETA.RU](https://moneta.ru/) | +| **Демо режим** | Включите, если используете [демо-площадку](https://demo.moneta.ru/) | +| **Форма оплаты в iframe** | Вместо перехода на платежную форму можно отображать её сразу на странице вашего магазина. В настройках Расширенного счета опцию "Target (возврат для iframe)" обязательно установите в значение: `_top` | +| **Отладка** | Включите или выключите логирование | +| **Описание** | `Приём платежей банковскими картами, через СБП и Pay‑сервисы` | +| **Инструкции** | `Оплата с помощью PayAnyWay` | -* [Invite team members and collaborators](https://docs.gitlab.com/user/project/members/) -* [Create a new merge request](https://docs.gitlab.com/user/project/merge_requests/creating_merge_requests/) -* [Automatically close issues from merge requests](https://docs.gitlab.com/user/project/issues/managing_issues/#closing-issues-automatically) -* [Enable merge request approvals](https://docs.gitlab.com/user/project/merge_requests/approvals/) -* [Set auto-merge](https://docs.gitlab.com/user/project/merge_requests/auto_merge/) +5. Сохраните изменения +--- -## Test and Deploy +## 🔧 Инструкция по настройке счета PayAnyWay -Use the built-in continuous integration in GitLab. +1. 📝 [Зарегистрируйтесь](https://payanyway.ru/partnerRegistration.htm) в платёжной системе PayAnyWay и заполните все необходимые данные. Дождитесь проверки аккаунта и создайте **расширенный счет**. -* [Get started with GitLab CI/CD](https://docs.gitlab.com/ci/quick_start/) -* [Analyze your code for known vulnerabilities with Static Application Security Testing (SAST)](https://docs.gitlab.com/user/application_security/sast/) -* [Deploy to Kubernetes, Amazon EC2, or Amazon ECS using Auto Deploy](https://docs.gitlab.com/topics/autodevops/requirements/) -* [Use pull-based deployments for improved Kubernetes management](https://docs.gitlab.com/user/clusters/agent/) -* [Set up protected environments](https://docs.gitlab.com/ci/environments/protected_environments/) +2. ⚙️ Заполните настройки расширенного счета (раздел **«Мой счет» → «Управление счетами» → «Редактировать счет» → «Показать дополнительные поля»**): -*** +| Параметр | Значение | +|------------------------------------------|--------------------------------------------------------------------------------------------------------------------------| +| **Тестовый режим** | `Нет` | +| **Check URL** | `https://your_site_name/?wc-api=wc_payanyway&payanyway=callback` | +| **Pay URL** | `https://your_site_name/?wc-api=wc_payanyway&payanyway=callback` | +| **HTTP метод (PayUrl, CheckUrl)** | `GET` | +| **Код проверки целостности данных** | `ваш_код` (произвольный набор символов) | +| **Подпись формы оплаты обязательна** | `Да` | +| **Можно переопределять настройки в URL** | `Да` | +| **Success URL** | Оставить пустым | +| **Fail URL** | Оставить пустым | +| **InProgress URL** | Оставить пустым | +| **Return URL** | Оставить пустым | +| **Target (возврат для iframe)** | Если хотите вместо перехода на платёжную форму отображать её сразу на странице вашего магазина выставьте значение `_top` | -# Editing this README +> ⚠️ **Важно!** Для кириллического домена PayURL и CheckURL должны быть указаны в кодировке [Punycode](https://2ip.ru/punycode/). -When you're ready to make this README your own, just edit this file and use the handy template below (or feel free to structure it however you want - this is just a starting point!). Thanks to [makeareadme.com](https://www.makeareadme.com/) for this template. +3. Для фискализации чеков по 54-ФЗ настройте вашу кассу в сервисе https://kassa.payanyway.ru, в настройках Вашего расширенного счёта в системе [MONETA.RU](https://moneta.ru/) + установите Pay URL: `https://kassa.payanyway.ru/index.php?do=invoicepayurl`, а в настройках кассы в https://kassa.payanyway.ru + пропишите ссылку на Pay URL Вашего интернет-магазина. В этом случае будет пробиваться чек + по 54-ФЗ через сервис **kassa.payanyway.ru**, а запрос на Pay URL магазина будет проходить транзитом через сервис + **kassa.payanyway.ru**. +--- -## Suggestions for a good README +## 📚 Полезные ресурсы OpenCart -Every project is different, so consider which of these sections apply to yours. The sections used in the template are suggestions for most open source projects. Also keep in mind that while a README can be too long and detailed, too long is better than too short. If you think your README is too long, consider utilizing another form of documentation rather than cutting out information. +* [Официальный сайт WordPress](https://wordpress.org/) +* [Официальный сайт WooCommerce](http://www.woothemes.com/woocommerce/) +* [WooCommerce GitHub Repositories](https://woocommerce.github.io/) +* [Developer Resources](https://developer.wordpress.org/) +* [WooCommerce Developers Docs](https://developer.woocommerce.com/docs/) -## Name -Choose a self-explaining name for your project. +--- -## Description -Let people know what your project can do specifically. Provide context and add a link to any reference visitors might be unfamiliar with. A list of Features or a Background subsection can also be added here. If there are alternatives to your project, this is a good place to list differentiating factors. +**✅ Модуль настроен, приятных платежей!** 💰🎉 -## Badges -On some READMEs, you may see small images that convey metadata, such as whether or not all the tests are passing for the project. You can use Shields to add some to your README. Many services also have instructions for adding a badge. - -## Visuals -Depending on what you are making, it can be a good idea to include screenshots or even a video (you'll frequently see GIFs rather than actual videos). Tools like ttygif can help, but check out Asciinema for a more sophisticated method. - -## Installation -Within a particular ecosystem, there may be a common way of installing things, such as using Yarn, NuGet, or Homebrew. However, consider the possibility that whoever is reading your README is a novice and would like more guidance. Listing specific steps helps remove ambiguity and gets people to using your project as quickly as possible. If it only runs in a specific context like a particular programming language version or operating system or has dependencies that have to be installed manually, also add a Requirements subsection. - -## Usage -Use examples liberally, and show the expected output if you can. It's helpful to have inline the smallest example of usage that you can demonstrate, while providing links to more sophisticated examples if they are too long to reasonably include in the README. - -## Support -Tell people where they can go to for help. It can be any combination of an issue tracker, a chat room, an email address, etc. - -## Roadmap -If you have ideas for releases in the future, it is a good idea to list them in the README. - -## Contributing -State if you are open to contributions and what your requirements are for accepting them. - -For people who want to make changes to your project, it's helpful to have some documentation on how to get started. Perhaps there is a script that they should run or some environment variables that they need to set. Make these steps explicit. These instructions could also be useful to your future self. - -You can also document commands to lint the code or run tests. These steps help to ensure high code quality and reduce the likelihood that the changes inadvertently break something. Having instructions for running tests is especially helpful if it requires external setup, such as starting a Selenium server for testing in a browser. - -## Authors and acknowledgment -Show your appreciation to those who have contributed to the project. - -## License -For open source projects, say how it is licensed. - -## Project status -If you have run out of energy or time for your project, put a note at the top of the README saying that development has slowed down or stopped completely. Someone may choose to fork your project or volunteer to step in as a maintainer or owner, allowing your project to keep going. You can also make an explicit request for maintainers. +> ⚠️ Рекомендуем сделать платёж на незначительную сумму — 11 руб., чтобы проверить интеграцию. diff --git a/payanyway/assets/css/paw-main.css b/payanyway/assets/css/paw-main.css new file mode 100644 index 0000000..0186435 --- /dev/null +++ b/payanyway/assets/css/paw-main.css @@ -0,0 +1,36 @@ +.annotation { + text-align: center; +} + +.visible { + display: block !important +} + +.content { + max-width: 416px; + min-width: 320px; + margin: auto; + width: 98%; + height: auto +} + +@font-face { + font-family: 'ProximaNova-Regular'; + src: url("https://www.payanyway.ru/w/fonts/ProximaNova/33F824_21_0.eot"); + src: url("https://www.payanyway.ru/w/fonts/ProximaNova/33F824_21_0.eot?#iefix") format("embedded-opentype"), url("https://www.payanyway.ru/w/fonts/ProximaNova/33F824_21_0.woff2") format("woff2"), url("https://www.payanyway.ru/w/fonts/ProximaNova/33F824_21_0.woff") format("woff"), url("https://www.payanyway.ru/w/fonts/ProximaNova/33F824_21_0.ttf") format("truetype"); + font-style: normal +} + +@font-face { + font-family: 'ProximaNova-Semibold'; + src: url("https://www.payanyway.ru/w/fonts/ProximaNova/33F824_28_0.eot"); + src: url("https://www.payanyway.ru/w/fonts/ProximaNova/33F824_28_0.eot?#iefix") format("embedded-opentype"), url("https://www.payanyway.ru/w/fonts/ProximaNova/33F824_28_0.woff2") format("woff2"), url("https://www.payanyway.ru/w/fonts/ProximaNova/33F824_28_0.woff") format("woff"), url("https://www.payanyway.ru/w/fonts/ProximaNova/33F824_28_0.ttf") format("truetype"); + font-style: normal +} + +@font-face { + font-family: 'ProximaNova-Bold'; + src: url("https://www.payanyway.ru/w/fonts/ProximaNova/33F824_C_0.eot"); + src: url("https://www.payanyway.ru/w/fonts/ProximaNova/33F824_C_0.eot?#iefix") format("embedded-opentype"), url("https://www.payanyway.ru/w/fonts/ProximaNova/33F824_C_0.woff2") format("woff2"), url("https://www.payanyway.ru/w/fonts/ProximaNova/33F824_C_0.woff") format("woff"), url("https://www.payanyway.ru/w/fonts/ProximaNova/33F824_C_0.ttf") format("truetype"); + font-style: normal +} \ No newline at end of file diff --git a/payanyway/assets/images/payanyway.png b/payanyway/assets/images/payanyway.png new file mode 100644 index 0000000..38e07e6 Binary files /dev/null and b/payanyway/assets/images/payanyway.png differ diff --git a/payanyway/block-support.php b/payanyway/block-support.php new file mode 100644 index 0000000..9da4a77 --- /dev/null +++ b/payanyway/block-support.php @@ -0,0 +1,41 @@ +settings = get_option('woocommerce_payanyway_settings', []); + } + + public function get_payment_method_script_handles() { + wp_register_script( + 'payanyway-blocks-integration', + plugin_dir_url(__FILE__) . 'blocks.js', + [ + 'wc-blocks-registry', + 'wc-settings', + 'wp-element', + 'wp-html-entities', + 'wp-i18n', + ], + null, + true + ); + + return ['payanyway-blocks-integration']; + } + + public function get_payment_method_data() { + $gateway = WC()->payment_gateways()->payment_gateways()['payanyway']; + + return [ + 'title' => $gateway->settings['title'], + 'description' => $gateway->settings['description'], + 'icon' => $gateway->icon + ]; + } +} diff --git a/payanyway/blocks.js b/payanyway/blocks.js new file mode 100644 index 0000000..17c25e7 --- /dev/null +++ b/payanyway/blocks.js @@ -0,0 +1,33 @@ +const payanywaySettings = window.wc.wcSettings.getSetting('payanyway_data', {}); +const payanywaySettingsLabel = window.wp.htmlEntities.decodeEntities(payanywaySettings.title) || window.wp.i18n.__('Оплата через PayAnyWay', 'payanyway') + +const PayanywayContent = () => { + return window.wp.htmlEntities.decodeEntities(payanywaySettings.description || ''); +}; + +const PayanywayLabel = () => { + return window.wp.element.createElement( + 'span', + {style: {width: '100%'}}, + payanywaySettingsLabel, + window.wp.element.createElement('img', { + src: payanywaySettings.icon, + style: {float: 'right', marginRight: '20px'}, + alt: payanywaySettings.title, + }) + ); +}; + +const Payanyway_Block_Gateway = { + name: 'payanyway', + label: window.wp.element.createElement(PayanywayLabel), + content: window.wp.element.createElement(PayanywayContent), + edit: window.wp.element.createElement(PayanywayContent), + canMakePayment: () => true, + ariaLabel: payanywaySettingsLabel, + supports: { + features: payanywaySettings.supports, + }, +}; + +window.wc.wcBlocksRegistry.registerPaymentMethod(Payanyway_Block_Gateway); diff --git a/payanyway/includes/settings/settings-paw.php b/payanyway/includes/settings/settings-paw.php new file mode 100644 index 0000000..e8a98b9 --- /dev/null +++ b/payanyway/includes/settings/settings-paw.php @@ -0,0 +1,83 @@ + array( + 'title' => __('PayAnyWay', 'woocommerce_gateway_payanyway'), + 'type' => 'title', + 'description' => __('Настройка приёма электронных платежей через PayAnyWay', 'woocommerce_gateway_payanyway'), + ), + 'enabled' => array( + 'title' => __('Включить/Выключить', 'woocommerce_gateway_payanyway'), + 'type' => 'checkbox', + 'label' => __('Включен', 'woocommerce_gateway_payanyway'), + 'default' => 'yes', + ), + 'title' => array( + 'title' => __('Название', 'woocommerce_gateway_payanyway'), + 'type' => 'text', + 'description' => __('Это название, которое пользователь видит во время проверки', 'woocommerce_gateway_payanyway'), + 'default' => __('PayAnyWay', 'woocommerce_gateway_payanyway'), + ), + 'MNT_ID' => array( + 'title' => __('Номер счёта', 'woocommerce_gateway_payanyway'), + 'type' => 'text', + 'description' => __('Ваш номер расширенного счёта в системе MONETA.RU', 'woocommerce_gateway_payanyway'), + 'default' => '99999999', + ), + 'MNT_DATAINTEGRITY_CODE' => array( + 'title' => __('Код проверки целостности данных', 'woocommerce_gateway_payanyway'), + 'type' => 'password', + 'description' => __('Код проверки целостности данных, указанный в настройках расширенного счёта в системе MONETA.RU', 'woocommerce_gateway_payanyway'), + 'default' => '******', + ), + 'demo_mode' => array( + 'title' => __('Демо режим', 'woocommerce_gateway_payanyway'), + 'type' => 'checkbox', + 'label' => __('Включен', 'woocommerce_gateway_payanyway'), + 'description' => __('Включите, если используете демо-площадку (demo.moneta.ru)', 'woocommerce_gateway_payanyway'), + 'default' => 'no', + ), + 'iniframe' => array( + 'title' => __('Форма оплаты в iframe', 'woocommerce_gateway_payanyway'), + 'type' => 'checkbox', + 'label' => __('Встроить форму оплаты в страницу сайта', 'woocommerce_gateway_payanyway'), + 'description' => __('Форма оплаты, предоставляемая PayAnyWay, будет встроена в страницу вашего сайта. Автоотправка невозможна. Покупатель сможет выбрать желаемый способ оплаты', 'woocommerce_gateway_payanyway'), + 'default' => 'no', + ), + 'debug' => array( + 'title' => __('Отладка', 'woocommerce_gateway_payanyway'), + 'type' => 'checkbox', + 'label' => __('Включить логирование', 'woocommerce_gateway_payanyway'), + 'description' => sprintf( + __('Для просмотра перейдите в WooCommerce → Статус → Журналы и выберите payanyway', 'woocommerce_gateway_payanyway'), + admin_url('admin.php?page=wc-status&tab=logs&source=payanyway&paged=1') + ), + 'default' => 'no', + ), + 'description' => array( + 'title' => __('Описание', 'woocommerce_gateway_payanyway'), + 'type' => 'textarea', + 'description' => __('Описанием метода оплаты которое клиент будет видеть на вашем сайте', 'woocommerce_gateway_payanyway'), + 'default' => 'Приём платежей банковскими картами, через СБП и Pay‑сервисы', + ), + 'instructions' => array( + 'title' => __('Инструкции', 'woocommerce_gateway_payanyway'), + 'type' => 'textarea', + 'description' => __('Инструкции, которые будут добавлены на страницу благодарностей', 'woocommerce_gateway_payanyway'), + 'default' => 'Оплата с помощью PayAnyWay', + ), + 'empty' => array( + 'title' => __('', 'woocommerce_gateway_payanyway'), + 'type' => 'title', + 'description' => __('', 'woocommerce_gateway_payanyway'), + ), +); + +return apply_filters('woocommerce_payanyway_settings', $settings); diff --git a/payanyway/wc-payanyway.php b/payanyway/wc-payanyway.php new file mode 100644 index 0000000..f7df7b9 --- /dev/null +++ b/payanyway/wc-payanyway.php @@ -0,0 +1,1246 @@ +id = 'payanyway'; + $this->method_title = 'Монета | PayAnyWay'; + $this->method_description = 'PayAnyWay - универсальный платежный агрегатор для интернет-магазинов и сервисов'; + $this->icon = plugin_dir_url(dirname(__FILE__)) . 'payanyway/assets/images/payanyway.png'; + $this->has_fields = false; + + // Load the settings + $this->init_form_fields(); + $this->init_settings(); + + // Define user set variables + $this->MNT_ID = (int)$this->get_option('MNT_ID'); + $this->MNT_DATAINTEGRITY_CODE = $this->get_option('MNT_DATAINTEGRITY_CODE'); + $this->MNT_TEST_MODE = 0; + $this->demo_mode = $this->get_option('demo_mode'); + $this->title = $this->get_option('title'); + $this->iniframe = $this->get_option('iniframe'); + $this->debug = $this->get_option('debug'); + $this->description = $this->get_option('description'); + $this->instructions = $this->get_option('instructions'); + + // Logs + if ($this->debug === 'yes') { + $this->logger = wc_get_logger(); + } + + // Actions + add_action('woocommerce_receipt_payanyway', array($this, 'receipt_page')); + + // Save options + add_action('woocommerce_update_options_payment_gateways_payanyway', array($this, 'process_admin_options')); + + // Payment listener/API hook + add_action('woocommerce_api_wc_payanyway', array($this, 'check_assistant_response')); + + if (!$this->is_valid_for_use()) { + $this->enabled = false; + } + } + + /** + * Check if this gateway is enabled and available in the user's country + */ + function is_valid_for_use() { + if (!in_array(get_option('woocommerce_currency'), array('RUB'))) { + return false; + } + + return true; + } + + /** + * Admin Panel Options + * - Options for bits like 'title' and availability on a country-by-country basis + * + * @since 0.1 + **/ + public function admin_options() { + if ($this->is_valid_for_use()) { + $this->generate_settings_html(); + } else { +?> +
+

+ + + : + +

+
+form_fields = include 'includes/settings/settings-paw.php'; + } + + /** + * Дополнительная информация в форме выбора способа оплаты + **/ + function payment_fields() { + echo $this->get_description(); + if (isset($_GET['pay_for_order']) && !empty($_GET['key'])) { + $order = wc_get_order(wc_get_order_id_by_order_key(wc_clean($_GET['key']))); + $this->receipt_page($order->get_id()); + } + } + + /** + * Process the payment and return the result + **/ + function process_payment($order_id) { + /** @var WC_Order $order */ + $order = new WC_Order($order_id); + return array( + 'result' => 'success', + 'redirect' => add_query_arg( + 'order-pay', + $order->get_id(), + add_query_arg( + 'key', + $order->get_order_key(), + $order->get_checkout_payment_url() + ) + ), + ); + } + + private function getPaymentObject($productName) { + if (false !== mb_stripos($productName, 'акциз')) { + $itemPaymentObject = 'excise'; + } elseif (false !== mb_stripos($productName, 'работ')) { + $itemPaymentObject = 'job'; + } elseif (false !== mb_stripos($productName, 'услуг')) { + $itemPaymentObject = 'service'; + } elseif (false !== mb_stripos($productName, 'ставк')) { + $itemPaymentObject = 'gambling_bet'; + } elseif (false !== mb_stripos($productName, 'выигрыш')) { + $itemPaymentObject = 'gambling_prize'; + } elseif (false !== mb_stripos($productName, 'лотере')) { + $itemPaymentObject = 'lottery'; + } elseif (false !== mb_stripos($productName, 'приз')) { + $itemPaymentObject = 'lottery_prize'; + } elseif (false !== mb_stripos($productName, 'интеллект')) { + $itemPaymentObject = 'intellectual_activity'; + } elseif (false !== mb_stripos($productName, 'взнос')) { + $itemPaymentObject = 'payment'; + } elseif (false !== mb_stripos($productName, 'агент')) { + $itemPaymentObject = 'agent_commission'; + } else { + $itemPaymentObject = 'commodity'; + } + + return $itemPaymentObject; + } + + /** + * @param string $data + * @return string + */ + private function getVatTag($data) + { + $vatList = array( + 'none' => '1105', + 'vat0' => '1104', + 'vat5' => '1108', + 'vat105' => '1110', + 'vat7' => '1109', + 'vat107' => '1111', + 'vat10' => '1103', + 'vat110' => '1107', + 'vat20' => '1102', + 'vat120' => '1106', + 'vat22' => '1113', + 'vat122' => '1114', + ); + + return isset($vatList[$data]) ? $vatList[$data] : '1105'; + } + + /** + * @param int|null $rate + * @return string + */ + private function convertVatIdByRate($rate) + { + if ($rate === null) { + return 'none'; + } + + $vatMap = array( + 0 => 'vat0', + 5 => 'vat5', + 7 => 'vat7', + 10 => 'vat10', + 20 => 'vat20', + 22 => 'vat22', + ); + + return isset($vatMap[$rate]) ? $vatMap[$rate] : 'vat' . $rate; + } + + private function getPaymentMethod($productName) { + if (false !== mb_stripos($productName, 'аванс')) { + $itemPaymentMethod = 'advance'; + } elseif (false !== mb_stripos($productName, 'кредит')) { + $itemPaymentMethod = 'credit'; + } else { + $itemPaymentMethod = 'full_prepayment'; + } + + return $itemPaymentMethod; + } + + /** + * Форма оплаты + **/ + function receipt_page($order_id) { + $order = new WC_Order($order_id); + + $amount = $this->formatPrice($order->get_total()); + $test_mode = $this->MNT_TEST_MODE; + $in_iframe = ($this->iniframe === 'yes') ? 1 : 0; + $currency = get_woocommerce_currency(); + if ($currency === 'RUR') $currency = 'RUB'; + + $transactionId = $this->createTransactionId($order_id); + $subscriberId = $this->getSubscriberId($order); + + $signature = md5( + $this->MNT_ID . + $transactionId . + $amount . + $currency . + $subscriberId . + $test_mode . + $this->MNT_DATAINTEGRITY_CODE + ); + + $wcKey = (isset($_GET['key'])) ? $_GET['key'] : ''; + + $args = array( + 'MNT_ID' => $this->MNT_ID, + 'MNT_TRANSACTION_ID' => $transactionId, + 'MNT_AMOUNT' => $amount, + 'MNT_CURRENCY_CODE' => $currency, + 'MNT_TEST_MODE' => $test_mode, + 'MNT_DESCRIPTION' => $this->getDescription($order), + 'MNT_SUBSCRIBER_ID' => $subscriberId, + 'MNT_SIGNATURE' => $signature, + 'MNT_SUCCESS_URL' => get_site_url() . "/?wc-api=wc_payanyway&payanyway=success&key={$wcKey}&order_id={$order_id}", + 'MNT_FAIL_URL' => get_site_url() . "/?wc-api=wc_payanyway&payanyway=fail", + 'MNT_RETURN_URL' => get_site_url() . '/checkout/', + 'MNT_CMS' => $this->getCmsModuleVersion(), + ); + + $form_fields = array(); + foreach ($args as $key => $value) { + $form_fields[] = ''; + } + + wp_enqueue_style('paw_css_main', plugin_dir_url(__FILE__) . 'assets/css/paw-main.css', '', ''); + + $demoMode = ($this->demo_mode === 'yes') ? 1 : 0; + + $this->logger && $this->logger->info('Create payment processed', array( + 'source' => self::MODULE_NAME, + 'form_data' => $args, + )); + + if ($in_iframe) { + $assistantEndpoint = $demoMode ? self::DEMO_IFRAME_ENDPOINT : self::PROD_IFRAME_ENDPOINT; + $form_html = '