Files
lulandia.pl/modules/raty/raty/raty.php
2025-04-01 00:38:54 +02:00

522 lines
21 KiB
PHP

<?php
use PrestaShop\PrestaShop\Core\Payment\PaymentOption;
if (!defined('_PS_VERSION_')) {
exit;
}
class Raty extends PaymentModule
{
protected $_html = '';
protected $_postErrors = array();
public $details;
public $owner;
public $address;
public $extra_mail_vars;
public function __construct()
{
$this->name = 'raty';
$this->tab = 'payments_gateways';
$this->version = '1.4.4';
$this->author = 'LogsHub.com';
$this->bootstrap = true;
$this->is_eu_compatible = 1;
$this->controllers = array('payment', 'validation');
$this->is_eu_compatible = 1;
$this->ps_versions_compliancy = array('min' => '1.7', 'max' => '1.7.6.99');
parent::__construct();
$this->displayName = $this->l('Raty');
$this->description = $this->l('Moduł do obsługi rat Alior Banku.');
$this->confirmUninstall = $this->l('Czy jesteś pewien aby odinstalować ten moduł?');
if (!Configuration::get('RATY_NAME')) {
$this->warning = $this->l('No name provided');
}
}
private function createOrderState()
{
// create new order status STATUSNAME
$values_to_insert = [
'invoice' => 0,
'send_email' => 0,
'module_name' => $this->name,
'color' => 'RoyalBlue',
'unremovable' => 0,
'hidden' => 0,
'logable' => 0,
'delivery' => 0,
'shipped' => 0,
'paid' => 0,
'deleted' => 0
];
if (!Db::getInstance()->insert('order_state', $values_to_insert)) {
return false;
}
$id_order_state = (int) Db::getInstance()->Insert_ID();
$languages = Language::getLanguages(false);
foreach ($languages as $language) {
Db::getInstance()->insert('order_state_lang', [
'id_order_state' => $id_order_state,
'id_lang' => $language['id_lang'],
'name' => 'Oczekiwanie na zatwierdzenie umowy ratalnej przez Alior Bank',
'template' => ''
]);
}
if (!@copy(dirname(__FILE__) . DIRECTORY_SEPARATOR . 'alior.gif', _PS_ROOT_DIR_ . DIRECTORY_SEPARATOR . 'img' . DIRECTORY_SEPARATOR . 'os' . DIRECTORY_SEPARATOR . $id_order_state . '.gif')) {
return false;
}
Configuration::updateValue('PS_OS_RATY', $id_order_state);
unset($id_order_state);
return true;
}
public function install()
{
if (Shop::isFeatureActive()) {
Shop::setContext(Shop::CONTEXT_ALL);
}
if (!parent::install()
||
!$this->registerHook('displayHeader') ||
!$this->registerHook('displayProductButtons') ||
!$this->registerHook('displayShoppingCartFooter') ||
!$this->registerHook('payment') ||
!$this->registerHook('paymentOptions') ||
!$this->registerHook('paymentReturn') ||
!$this->createOrderState() ||
!Configuration::updateValue('RATY_NAME', 'Raty') ||
!Configuration::updateValue('RATY_URL', 'https://aliorbank.pl') ||
!Configuration::updateValue('RATY_PARTNERID', '1001') ||
!Configuration::updateValue('RATY_SUBPARTNERID', '') ||
!Configuration::updateValue('RATY_MCC', '') ||
!Configuration::updateValue('RATY_PROMOTION', '') ||
!Configuration::updateValue('RATY_WARTOSC', '') ||
!Configuration::updateValue('RATY_KALKULATOR', '') ||
!Configuration::updateValue('RATY_SALT', 'QWERSJR1234$$%')
) {
return false;
}
return true;
}
public function uninstall()
{
if (!parent::uninstall()||
!Configuration::deleteByName('RATY_NAME') ||
!Configuration::deleteByName('RATY_URL') ||
!Configuration::deleteByName('RATY_PARTNERID') ||
!Configuration::deleteByName('RATY_SUBPARTNERID') ||
!Configuration::updateValue('RATY_MCC', '') ||
!Configuration::updateValue('RATY_PROMOTION', '') ||
!Configuration::updateValue('RATY_WARTOSC', '') ||
!Configuration::updateValue('RATY_KALKULATOR', '') ||
!Configuration::deleteByName('RATY_SALT')
) {
return false;
}
return true;
}
public function hookPaymentOptions($params)
{
if (!$this->active) {
return;
}
if (!$this->checkCurrency($params['cart']) || !$this->checkAmount($params['cart']->getOrderTotal())) {
return;
}
$offlineOption = new PaymentOption();
$offlineOption->setCallToActionText($this->l('Raty - Alior Bank'))
->setAction($this->context->link->getModuleLink($this->name, 'validation', array(), true))
// ->setAdditionalInformation($this->context->smarty->fetch('module:paymentexample/views/templates/front/payment_infos.tpl'))
->setLogo(Media::getMediaPath(_PS_MODULE_DIR_.$this->name.'/alior.gif'));
return [
$offlineOption,
];
}
public function getContent()
{
$output = '';
if (Tools::isSubmit('submitRaty')) {
$error = false;
if (!($raty_url = Tools::getValue('RATY_URL')) || empty($raty_url)) {
$output .= $this->displayError($this->l('Musisz wypełnić pole \'Adres URL\'.'));
$error = true;
} else {
Configuration::updateValue('RATY_URL', $raty_url);
}
if (!($raty_parentid = Tools::getValue('RATY_PARTNERID')) || empty($raty_parentid)) {
$output .= $this->displayError($this->l('Musisz wypełnić pole \'Parent ID\'.'));
$error = true;
} elseif (!$error) {
Configuration::updateValue('RATY_PARTNERID', $raty_parentid);
}
Configuration::updateValue('RATY_SUBPARTNERID', Tools::getValue('RATY_SUBPARTNERID'));
if (!($raty_salt = Tools::getValue('RATY_SALT')) || empty($raty_salt)) {
$output .= $this->displayError($this->l('Musisz wypełnić pole \'Salt\'.'));
$error = true;
} elseif (!$error) {
Configuration::updateValue('RATY_SALT', $raty_salt);
}
Configuration::updateValue('RATY_MCC', Tools::getValue('RATY_MCC'));
Configuration::updateValue('RATY_PROMOTION', Tools::getValue('RATY_PROMOTION'));
Configuration::updateValue('RATY_WARTOSC', $this->changeNumberFormat(Tools::getValue('RATY_WARTOSC')));
Configuration::updateValue('RATY_KALKULATOR', Tools::getValue('RATY_KALKULATOR'));
if (!$error) {
$output .= $this->displayConfirmation($this->l('Parametry uaktualnione.'));
}
}
return $output . $this->renderForm();
}
public function hookDisplayProductButtons($params)
{
if (empty($params['product']->price_amount)){
return;
}
$price = $params['product']->price_amount;
if (!$this->checkAmount($price)) {
return;
}
if (!$this->isCached('productraty.tpl', $this->getCacheId($params['product']->id))) {
$promotion = Tools::getValue('RATY_PROMOTION', Configuration::get('RATY_PROMOTION'));
$this->smarty->assign(array(
'this_path' => $this->_path,
'this_path_raty' => $this->_path,
'this_path_ssl' => Tools::getShopDomainSsl(true, true) . __PS_BASE_URI__ . 'modules/' . $this->name . '/',
'this_kalkulator' => Tools::getValue('RATY_KALKULATOR', Configuration::get('RATY_KALKULATOR')) .
'?installmentNumber=21&offerCode='.$promotion.'&cartValue=',
'this_cena' => $this->changeNumberFormat(round($price, 2))
));
}
return $this->display(__FILE__, 'productraty.tpl', $this->getCacheId($params['product']->id));
}
public function hookDisplayShoppingCartFooter($params)
{
if (!$this->checkCurrency($params['cart']) || !$this->checkAmount($params['cart']->getOrderTotal())) {
return;
}
$promotion = Tools::getValue('RATY_PROMOTION', Configuration::get('RATY_PROMOTION'));
$this->smarty->assign(array(
'this_path' => $this->_path,
'this_path_raty' => $this->_path,
'this_path_ssl' => Tools::getShopDomainSsl(true, true) . __PS_BASE_URI__ . 'modules/' . $this->name . '/',
'this_kalkulator' => Tools::getValue('RATY_KALKULATOR', Configuration::get('RATY_KALKULATOR')) .
'?installmentNumber=21&offerCode='.$promotion.'&cartValue=',
'this_cena' => $this->changeNumberFormat($params['cart']->getOrderTotal()),
));
return $this->display(__FILE__, 'raty_cart.tpl', $this->getCacheId());
}
public function hookDisplayHeader($params)
{
$this->context->controller->addCSS($this->_path . 'raty.css', 'all');
}
public function hookPayment($params)
{
if (!$this->active) {
return;
}
if (!$this->changeNumberFormat($this->checkAmount($params['cart']->getOrderTotal()))) {
return;
}
$promotion = Tools::getValue('RATY_PROMOTION', Configuration::get('RATY_PROMOTION'));
$this->smarty->assign(array(
'this_path' => $this->_path,
'this_path_raty' => $this->_path,
'this_path_ssl' => Tools::getShopDomainSsl(true, true) . __PS_BASE_URI__ . 'modules/' . $this->name . '/',
'this_kalkulator' => Tools::getValue('RATY_KALKULATOR', Configuration::get('RATY_KALKULATOR')) .
'?installmentNumber=21&offerCode='.$promotion.'&cartValue=',
'this_cena' => $this->changeNumberFormat($params['cart']->getOrderTotal()),
));
return $this->display(__FILE__, 'payment.tpl');
}
public function hookPaymentReturn($params)
{
if (!$this->active) {
return;
}
$state = $params['order']->getCurrentState();
if (in_array($state, array(Configuration::get('PS_OS_RATY'), Configuration::get('PS_OS_OUTOFSTOCK'), Configuration::get('PS_OS_OUTOFSTOCK_UNPAID')))) {
$customer = new Customer($params['order']->id_customer);
$firstName = $customer->firstname;
$lastName = $customer->lastname;
$url = Tools::getValue('RATY_URL', Configuration::get('RATY_URL'));
$partnerId = Tools::getValue('RATY_PARTNERID', Configuration::get('RATY_PARTNERID'));
$subpartnerId = Tools::getValue('RATY_SUBPARTNERID', Configuration::get('RATY_SUBPARTNERID'));
$mcc = Tools::getValue('RATY_MCC', Configuration::get('RATY_MCC'));
$promotion = Tools::getValue('RATY_PROMOTION', Configuration::get('RATY_PROMOTION'));
$salt = Tools::getValue('RATY_SALT', Configuration::get('RATY_SALT'));
$calculatedIncome = '';
$limit = '';
$transactionCode = $params['order']->reference;
$total = $params['order']->total_paid;
$date = date('Y-m-d');
$time = date('H:i:s');
$dateAndTime = $date . 'T' . $time;
$verificationCode = hash('sha256', $salt . $this->changeNumberFormat($total) .
$transactionCode . $partnerId . $subpartnerId . $dateAndTime . $mcc . $firstName . $lastName . $limit . $calculatedIncome . $promotion);
$values = [
'url' => $url,
'firstName' => $firstName,
'lastName' => $lastName,
'amount' => $total,
'partnerId' => $partnerId,
'subpartnerId' => $subpartnerId,
'mcc' => $mcc,
'limit' => $limit,
'promotion' => $promotion,
'calculatedIncome' => $calculatedIncome,
'verificationCode' => $verificationCode,
'transactionCode' => $transactionCode,
'dateAndTime' => $dateAndTime,
'amount' => $this->changeNumberFormat($total),
'status' => 'ok',
'articlesList' => base64_encode(json_encode($this->getAliorsArticlesListJson(
$params['order']->getProducts(),
(float)$params['order']->total_shipping,
(float)$params['order']->total_discounts
))),
];
$this->context->smarty->assign($values);
} else {
$this->context->smarty->assign('status', 'failed');
}
return $this->context->smarty->fetch('module:raty/views/templates/hook/payment_return.tpl');
}
public function renderForm()
{
$fields_form = array(
'form' => array(
'legend' => array(
'title' => $this->l('Ustawienia'),
'icon' => 'icon-cogs'
),
'input' => array(
array(
'type' => 'text',
'label' => $this->l('Adres URL'),
'name' => 'RATY_URL',
'class' => 'fixed-width-xxl',
'desc' => $this->l('Adres URL banku.')
),
array(
'type' => 'text',
'label' => $this->l('PartnerID'),
'name' => 'RATY_PARTNERID',
'class' => 'fixed-width-xxl',
'desc' => $this->l('Kod partnera handlowego')
),
array(
'type' => 'text',
'label' => $this->l('SubpartnerID'),
'name' => 'RATY_SUBPARTNERID',
'class' => 'fixed-width-xxl',
'desc' => $this->l('Dodatkowy kod partnera handlowego.')
),
array(
'type' => 'text',
'label' => $this->l('MCC'),
'name' => 'RATY_MCC',
'class' => 'fixed-width-xxl',
'desc' => $this->l('Kod MCC.')
),
array(
'type' => 'text',
'label' => $this->l('Promocja'),
'name' => 'RATY_PROMOTION',
'class' => 'fixed-width-xxl',
'desc' => $this->l('Kod promocji.')
),
array(
'type' => 'text',
'label' => $this->l('Wartość'),
'name' => 'RATY_WARTOSC',
'class' => 'fixed-width-xxl',
'desc' => $this->l('Minimalna wartość od której dostępna jest sprzedaż ratalna.')
),
array(
'type' => 'text',
'label' => $this->l('URL kalkulatora'),
'name' => 'RATY_KALKULATOR',
'class' => 'fixed-width-xxl',
'desc' => $this->l('Link do obliczenia wysokości rat')
),
array(
'type' => 'text',
'label' => $this->l('Salt'),
'name' => 'RATY_SALT',
'class' => 'fixed-width-xxl',
'desc' => $this->l('Kod Salt odtrzymany od banku')
),
),
'submit' => array(
'title' => $this->l('Save'),
)
),
);
$helper = new HelperForm();
$helper->show_toolbar = false;
$helper->table = $this->table;
$lang = new Language((int) Configuration::get('PS_LANG_DEFAULT'));
$helper->default_form_language = $lang->id;
$helper->allow_employee_form_lang = Configuration::get('PS_BO_ALLOW_EMPLOYEE_FORM_LANG') ? Configuration::get('PS_BO_ALLOW_EMPLOYEE_FORM_LANG') : 0;
$helper->identifier = $this->identifier;
$helper->submit_action = 'submitRaty';
$helper->currentIndex = $this->context->link->getAdminLink('AdminModules', false) . '&configure=' . $this->name . '&tab_module=' . $this->tab . '&module_name=' . $this->name;
$helper->token = Tools::getAdminTokenLite('AdminModules');
$helper->tpl_vars = array(
'fields_value' => $this->getConfigFieldsValues(),
'languages' => $this->context->controller->getLanguages(),
'id_language' => $this->context->language->id
);
return $helper->generateForm(array($fields_form));
}
public function checkCurrency($cart)
{
$currency_order = new Currency($cart->id_currency);
$currencies_module = $this->getCurrency($cart->id_currency);
if (is_array($currencies_module)) {
foreach ($currencies_module as $currency_module) {
if ($currency_order->id == $currency_module['id_currency']) {
return true;
}
}
}
return false;
}
public function getConfigFieldsValues()
{
return array(
'RATY_URL' => Tools::getValue('RATY_URL', Configuration::get('RATY_URL')),
'RATY_PARTNERID' => Tools::getValue('RATY_PARTNERID', Configuration::get('RATY_PARTNERID')),
'RATY_SUBPARTNERID' => Tools::getValue('RATY_SUBPARTNERID', Configuration::get('RATY_SUBPARTNERID')),
'RATY_MCC' => Tools::getValue('RATY_MCC', Configuration::get('RATY_MCC')),
'RATY_PROMOTION' => Tools::getValue('RATY_PROMOTION', Configuration::get('RATY_PROMOTION')),
'RATY_WARTOSC' => Tools::getValue('RATY_WARTOSC', $this->changeNumberFormat(Configuration::get('RATY_WARTOSC'))),
'RATY_KALKULATOR' => Tools::getValue('RATY_KALKULATOR', Configuration::get('RATY_KALKULATOR')),
'RATY_SALT' => Tools::getValue('RATY_SALT', Configuration::get('RATY_SALT')),
);
}
public function checkAmount($total)
{
$wartosc = (float) Tools::getValue('RATY_WARTOSC', $this->changeNumberFormat(Configuration::get('RATY_WARTOSC')));
if ($wartosc > 0) {
return $wartosc <= $total;
}
return false;
}
private function changeNumberFormat($value)
{
return number_format($value, 2, '.', '');
}
private function getAliorsArticlesListJson(array $products, $totalShippingCost, $totalDiscounts)
{
$totalShippingCost = (float)$totalShippingCost;
$totalDiscounts = (float)$totalDiscounts;
// @see https://stackoverflow.com/questions/42981409/php7-1-json-encode-float-issue
// json_encode makes float values wrong. This is simple fix
if (version_compare(phpversion(), '7.1', '>=')) {
ini_set( 'serialize_precision', -1 );
}
$json = ['articlesList' => []];
foreach ($products as $prod) {
if (!empty($prod['unit_price_tax_incl'])){
$price = $prod['unit_price_tax_incl'];
} else {
$price = !empty($prod['product_price_wt']) ? $prod['product_price_wt'] : $prod['product_price'];
}
$json['articlesList'][] = [
"category" => $this->getAliorsCategory($prod['id_category_default']),
"name" => $prod['product_name'],
"number" => (int)$prod['product_quantity'],
"price" => (float)$price,
];
}
if ($totalShippingCost){
$json['articlesList'][] = [
"category" => 'TKC_USLUGI', // from Alior's docs
"name" => 'Shipping costs',
"number" => 1,
"price" => $totalShippingCost,
];
}
if ($totalDiscounts){
$json['articlesList'][] = [
"category" => 'TKC_RABAT', // from Alior's docs
"name" => 'Discount',
"number" => 1,
"price" => $totalDiscounts * -1,
];
}
return $json;
}
/**
* Returns Alior's ID of category based on mapping (see map.php)
* @return string
*/
private function getAliorsCategory($shopCategoryId)
{
$map = require(dirname(__FILE__) . '/map.php');
if (empty($map)) {
return '';
}
foreach ($map as $aliorId => $shopCats) {
if (in_array($shopCategoryId, $shopCats)) {
return $aliorId;
}
}
return !empty($map['default']) ? $map['default'] : '';
}
}