Your IP : 3.145.139.84


Current Path : /home/bitrix/ext_www/dev.ballu.in.ua/local/components/online_paid/fsk/
Upload File :
Current File : /home/bitrix/ext_www/dev.ballu.in.ua/local/components/online_paid/fsk/component.php

<?php

/**
 * Test card for AlphaBank
 *
 * name: Cardholder name
 * pan: 4111 1111 1111 1111
 * exp date: 2019/12
 * cvv2: 123
 * ACS password is 12345678
 */

namespace OnlinePaid;

include('BankController.php');
include('LogController.php');
include('MailerController.php');


use CModule,
    CSaleOrder,
    CUser,
    CSaleBasket,
    CComponentUtil,
    OnlinePaid\BankController AS BankController,
    OnlinePaid\LogController AS LogController,
    OnlinePaid\MailerController AS MailerController,
    CIBlockElement;

CModule::IncludeModule('sale');


$process = new onlinePaid();
$process->process();

/**
 * Class onlinePaid
 * @package OnlinePaid
 */
class onlinePaid
{
    /**
     * orderID сайта
     * @var null
     */
    private $SID = null;

    /**
     * orderID банка
     * @var null
     */
    private $BID = null;

    /**
     * Ответ банка
     * @var null
     */
    private $bankResponse = null;

    /**
     * Контроллер банка
     * @var null
     */
    private $CBank = null;

    /**
     * Контроллер лога
     * @var null
     */
    private $CLog = null;

    /**
     * Контроллер Мейлера
     * @var null
     */
    private $CMailer = null;

    /**
     * @var int
     */
    private $siteAmount = 0;

    /**
     * this .parameters.php
     * @var array|bool
     */
    private $config = array();

    /**
     * onlinePaid constructor.
     */
    public function __construct()
    {
        $this->config = CComponentUtil::GetComponentProps('online_paid:fsk')['PARAMETERS'];

        $this->SID = (isset($_GET['SID']) ? $_GET['SID'] : $_POST['SID']);
        $this->BID = (isset($_GET['orderId']) ? $_GET['orderId'] : "");;

        $this->CBank = new BankController();
        $this->CMailer = new MailerController();
        $this->CLog = new LogController();

    }

    public function process()
    {
		$orderPropCityID = \Bitrix\Sale\Internals\OrderPropsValueTable::getList([
			'filter' => [
				'ORDER_ID' => (int) $_REQUEST['SID'],
				'ORDER_PROPS_ID' => 11
			]
		])->fetch();

		$_REQUEST['CITY_ID'] = $orderPropCityID['VALUE'];

    	if($bankConfig = allowOnlinePaid($_REQUEST['CITY_ID']))
		{
			$switch = (isset($_GET['ID']) ? $_GET['ID'] : 'firstStep');

			switch ($switch) {
				//чекаем заказ и юзверя, кидаем в банк
				case "firstStep":
					$this->firstStep($this->SID, $bankConfig);
					break;
				// чекаем заказ из банка, шлем письма админу и пользователю
				case "secondStep":
					$this->secondStep($this->BID, $this->SID, $bankConfig);
					break;
				default:
					header('Location: error.php?not_found');
					exit();
					break;
			};
		}else {
			header("Location: error.php?not_found");
			exit();
		}
    }

    /**
     * Начало процесса
     * Проверяем тот ли пользователь хочет оплатить
     * Перекидываем в банк или на страницу ошибки
     * @param $SID
     * @param $bankConfig
     */
    private function firstStep($SID, $bankConfig)
    {
        //$this->createData($SID);
        $this->bankResponse = $this->CBank->sendData($SID, $this->createData($SID), $bankConfig);
        header('location: ' . $this->bankResponse->formUrl);

        /*echo "<pre>";
        print_r($SID);

        $info = $this->getUserOrder($SID);

        // совпадает, значит нужный юзверь
        if (!empty($this->SID) && ($_COOKIE['BX_USER_ID'] === $info['user']['BX_USER_ID'])) {
            $this->bankResponse = $this->CBank->sendData($SID, $this->createData($SID));
            //header("Location: index.php?ID=secondStep&SID={$SID}");

            //кидаем клиента на страницу банка
				header('location: ' . $this->bankResponse->formUrl);
            exit();
        } else {
            // иначе скажем что такого заказа у пользователя не существует
            header("Location: error.php?not_found");
            exit();
        }*/
    }

    /**
     * @param $BID
     * @param $SID
     * @param $bankConfig
     */
    public function secondStep($BID, $SID, $bankConfig)
    {
        $this->bankResponse = $this->CBank->checkData($BID, $bankConfig);

        $info = $this->getUserOrder($SID);

        if (
            (isset($this->bankResponse->ErrorCode))
            &&
            ($this->bankResponse->ErrorCode == $this->config['BANK']['ORDER_SUCCESS_CODE'])
            &&
            ($this->bankResponse->OrderNumber == $SID)
        ) {
            /// успешно оплатили
            $this->CLog->log("\n\nInfo: ".print_r($info,true));
            $this->CLog->log("\nOK:  check_order=> RETURN=> TRUE");
			$this->CLog->log("\n\n ---------------------- \n\n");
            $this->siteAmount = $this->bankResponse->Amount;
            $this->siteAmount = $this->bankResponse->Amount;

            //"OK. Отправить письмо админу + юзеру, что заказ оплачен, вернуть юзверя на страницу спасибо";
            //$this->CMailer->prepareMailToUser($info['order'], $info['user']);
            $this->CMailer->prepareMailToAdmin($info['order'], $info['user'], '', $GLOBALS['arGeoData']['CUR_CITY']['EMAIL']);

            //Кинуть на страницу спасибо
            $id = base64_encode($SID);
            header("Location: thank.php?r={$id}");
            exit();
        } else {

            //"ERROR, Отправить письмо админу, что заказ небыл оплачен + ErrorMessage:[orderId] не задан', вернуть юзверя на страницу спасибо";
            $this->CMailer->prepareMailToAdmin($info['order'], $info['user'], $this->bankResponse->ErrorMessage, $GLOBALS['arGeoData']['CUR_CITY']['EMAIL']);
			$this->CLog->log("\n\nInfo: ".print_r($info,true));
			$this->CLog->log("\n\nbankResponse: ".print_r($this->bankResponse,true));
			$this->CLog->log("\n\nError:  bakConfig\n" .print_r($bankConfig,true));
			$this->CLog->log("\n\nError: geo=" . $GLOBALS['arGeoData']['CUR_CITY']['ID']);

			//print_r([$BID, $SID, $bankConfig]);

            header("Location: error.php?transaction_fail");
            $this->CLog->log("\n\nOK:  check_order=> RETURN=> FALSE");
            $this->CLog->log("\n\n ---------------------- \n\n");
            exit();
        }
    }

    /**
     * Собираем json заказа
     * @param $SID
     * @return array
     */
    private function createData($SID)
    {
        $orderInfo = CSaleOrder::GetByID($SID);

        //новый заказ
        if ($orderInfo['STATUS_ID'] == 'N') {
            $orderItems = CSaleBasket::GetList(
                array(
                    "NAME" => "ASC",
                    "ID" => "ASC"
                ),
                array(
                    //"USER_ID" => $orderInfo['USER_ID'],
                    "LID" => $orderInfo['LID'],
                    "DELAY" => "N",
                    "CAN_BUY" => "Y",
                    "ORDER_ID" => $orderInfo['ID']
                ),
                false,
                false,
                array()
            );

            $data = array(); // массив заказа
            $position = 0; // номер позиции в заказе
            $basketAmount = 0; // сумма корзины

            while ($item = $orderItems->Fetch()) {
                $position++;
                $tmp = array(
                    'positionId' => "{$position}",
                    //'name' => $this->_t($item['NAME']),
                    'name' => $item['NAME'],
                );
                $tmp['quantity'] = array(
                    'value' => (int)($item['QUANTITY']),
                    'measure' => /*$this->_t('шт')*/'pc'
                );

                $itemAmount = intval($item['PRICE'] * $item['QUANTITY']);
                $tmp['itemAmount'] = (int)($itemAmount . '00');
                $tmp['itemCode'] = $item['PRODUCT_ID'];

                $tmp['tax'] = array(
                    'taxType' => 7,
                    "taxSum" => ''
                );
                $itemPrice = number_format(intval($item['PRICE']), 0, '.', '');
                $tmp['itemPrice'] = (int)($itemPrice . '00');

                $data['cartItems']['items'][] = $tmp;
                $basketAmount += $itemAmount;
            }

            //Если есть доставка
            if (!empty($orderInfo['PRICE_DELIVERY'])) {
                $position++;
                $tmp = array(
                    'positionId' => "{$position}",
                    //'name' => $this->_t($item['NAME']),
                    'name' => 'Доставка',
                );
                $tmp['quantity'] = array(
                    'value' => 1,
                    'measure' => /*$this->_t('шт')*/'pc'
                );

                $itemAmount = intval($orderInfo['PRICE_DELIVERY']);
                $tmp['itemAmount'] = (int)($itemAmount . '00');
                $tmp['itemCode'] = 9999999;

                $tmp['tax'] = array(
                    'taxType' => 7,
                    "taxSum" => ''
                );
                $itemPrice = number_format(intval($orderInfo['PRICE_DELIVERY']), 0, '.', '');
                $tmp['itemPrice'] = (int)($itemPrice . '00');

                $data['cartItems']['items'][] = $tmp;
                $basketAmount += $orderInfo['PRICE_DELIVERY'];
            }

            $orderBundle = json_encode($data, JSON_UNESCAPED_UNICODE);

            return array(
                'basketAmount' => $basketAmount . "00",
                'orderBundle' => $orderBundle

            );
        }

        return null;
    }

    /**
     * Инфо о клиенте и его заказе
     * @param $SID
     * @return array
     */
    private function getUserOrder($SID)
    {
        $orderInfo = CSaleOrder::GetByID($SID);
        $getUser = CUser::GetByID($orderInfo['USER_ID']);
        $userInfo = $getUser->Fetch();

        return array(
            'user' => $userInfo,
            'order' => $orderInfo,
        );
    }

    /**
     * @param $string
     * @return string
     */
    public function _t($string)
    {
        return iconv('cp1251', 'UTF-8', $string);
    }

    /**
     * Переводим в читаемый вид лог оплаты
     * @param $str
     * @return string
     */
    /*public function normJsonStr($str)
    {
        $str = preg_replace_callback('/\\\\u([a-f0-9]{4})/i', create_function('$m', 'return chr(hexdec($m[1])-1072+224);'), $str);
        return iconv('cp1251', 'utf-8', $str);
    }*/
}