Advertisement
Guest User

Untitled

a guest
Jan 17th, 2019
107
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 18.30 KB | None | 0 0
  1. <?
  2. if (!defined("B_PROLOG_INCLUDED") || B_PROLOG_INCLUDED !== true) {
  3.     die();
  4. }
  5. if (!CModule::IncludeModule("sale")) return;
  6.  
  7. use \Bitrix\Main\Localization\Loc;
  8. use \Bitrix\Main\Loader;
  9. use \Bitrix\Main\Service\GeoIp;
  10.  
  11. class customOrderComponent extends CBitrixComponent
  12. {
  13.     /**
  14.      * @var \Bitrix\Sale\Order
  15.      */
  16.     public $order;
  17.  
  18.     protected $errors = [];
  19.  
  20.     protected $arResponse = [
  21.         'errors' => [],
  22.         'html' => ''
  23.     ];
  24.  
  25.     function __construct($component = null)
  26.     {
  27.         parent::__construct($component);
  28.  
  29.         if (!Loader::includeModule('sale')) {
  30.             $this->errors[] = 'No sale module';
  31.         };
  32.  
  33.         if (!Loader::includeModule('catalog')) {
  34.             $this->errors[] = 'No catalog module';
  35.         };
  36.     }
  37.  
  38.     function onPrepareComponentParams($arParams)
  39.     {
  40.         if (isset($arParams['PERSON_TYPE_ID']) && intval($arParams['PERSON_TYPE_ID']) > 0) {
  41.             $arParams['PERSON_TYPE_ID'] = intval($arParams['PERSON_TYPE_ID']);
  42.         } else {
  43.             if (intval($this->request['payer']['person_type_id']) > 0) {
  44.                 $arParams['PERSON_TYPE_ID'] = intval($this->request['payer']['person_type_id']);
  45.             } else {
  46.                 $arParams['PERSON_TYPE_ID'] = 1;
  47.             }
  48.         }
  49.         if (
  50.             isset($arParams['IS_AJAX'])
  51.             && ($arParams['IS_AJAX'] == 'Y' || $arParams['IS_AJAX'] == 'N')
  52.         ) {
  53.             $arParams['IS_AJAX'] = $arParams['IS_AJAX'] == 'Y';
  54.         } else {
  55.             if (
  56.                 isset($this->request['is_ajax'])
  57.                 && ($this->request['is_ajax'] == 'Y' || $this->request['is_ajax'] == 'N')
  58.             ) {
  59.                 $arParams['IS_AJAX'] = $this->request['is_ajax'] == 'Y';
  60.             } else {
  61.                 $arParams['IS_AJAX'] = false;
  62.             }
  63.         }
  64.         if (isset($arParams['ACTION']) && strlen($arParams['ACTION']) > 0) {
  65.             $arParams['ACTION'] = strval($arParams['ACTION']);
  66.         } else {
  67.             if (isset($this->request['action']) && strlen($this->request['action']) > 0) {
  68.                 $arParams['ACTION'] = strval($this->request['action']);
  69.             } else {
  70.                 $arParams['ACTION'] = '';
  71.             }
  72.         }
  73.         if(isset($arParams['PATH_TO_BASKET']) && strlen($arParams['PATH_TO_BASKET']) > 0){
  74.  
  75.             $arParams['PATH_TO_BASKET'] = strval($arParams['PATH_TO_BASKET']);
  76.  
  77.         }
  78.         else{
  79.  
  80.             $arParams['PATH_TO_BASKET'] = '/basket/';
  81.  
  82.         }
  83.  
  84.         if(isset($arParams['MIN_SUM']) && intval($arParams['MIN_SUM']) > 0){
  85.  
  86.             $arParams['MIN_SUM'] = intval($arParams['MIN_SUM']);
  87.  
  88.         }
  89.         else{
  90.  
  91.             $arParams['MIN_SUM'] = 500;
  92.  
  93.         }
  94.         return $arParams;
  95.     }
  96.  
  97.     protected function createVirtualOrder()
  98.     {
  99.         global $USER;
  100.  
  101.         try {
  102.             $siteId = \Bitrix\Main\Context::getCurrent()->getSite();
  103.             $basketItems = \Bitrix\Sale\Basket::loadItemsForFUser(
  104.                 \CSaleBasket::GetBasketUserID(),
  105.                 $siteId
  106.             )
  107.                 ->getOrderableItems();
  108.  
  109.  
  110.             if (count($basketItems) == 0 && $basketItems->getPrice() < $this->arParams['MIN_SUM']) {
  111.                 LocalRedirect($this->arParams['PATH_TO_BASKET']);
  112.             }
  113.             if ($USER->IsAuthorized()){
  114.  
  115.                 $user_id = $USER->GetID();
  116.  
  117.             }
  118.             else{
  119.  
  120.                 $user_id = \CSaleUser::GetAnonymousUserID();
  121.  
  122.             }
  123.  
  124.             $this->order = \Bitrix\Sale\Order::create($siteId, $user_id);
  125.             $this->order->setPersonTypeId($this->arParams['PERSON_TYPE_ID']);
  126.             $this->order->setBasket($basketItems);
  127.  
  128.             $this->setOrderProps();
  129.  
  130.             //устанавливаем комментарий покупателя из свойства
  131.             if(!empty($this->request['ORDER_DESCRIPTION'])):
  132.  
  133.                 $this->order->setField('USER_DESCRIPTION', $this->request['ORDER_DESCRIPTION']);
  134.  
  135.  
  136.             endif;
  137.  
  138.             if (intval($this->request['location_code']) > 0) {
  139.  
  140.                 $location_code = $this->request['location_code'];
  141.  
  142.             }
  143.  
  144.             else{
  145.  
  146.                 $ipAddress = GeoIp\Manager::getRealIp();
  147.                 $location_code = \Bitrix\Sale\Location\GeoIp::getLocationCode($ipAddress, LANGUAGE_ID);
  148.  
  149.  
  150.             }
  151.  
  152.  
  153.             foreach ($this->order->getPropertyCollection() as $prop) {
  154.  
  155.                 switch ($prop->getField('CODE')):
  156.                     case 'LOCATION':
  157.  
  158.                         $prop->setValue($location_code);
  159.  
  160.                         break;
  161.                 endswitch;
  162.             }
  163.  
  164.             /* @var $shipmentCollection \Bitrix\Sale\ShipmentCollection */
  165.             $shipmentCollection = $this->order->getShipmentCollection();
  166.  
  167.             if (intval($this->request['delivery_id']) > 0) {
  168.                 $shipment = $shipmentCollection->createItem(
  169.                     Bitrix\Sale\Delivery\Services\Manager::getObjectById(
  170.                         intval($this->request['delivery_id'])
  171.                     )
  172.                 );
  173.             } else {
  174.                 $shipment = $shipmentCollection->createItem();
  175.             }
  176.  
  177.             /** @var $shipmentItemCollection \Bitrix\Sale\ShipmentItemCollection */
  178.             $shipmentItemCollection = $shipment->getShipmentItemCollection();
  179.             $shipment->setField('CURRENCY', $this->order->getCurrency());
  180.             foreach ($this->order->getBasket()->getOrderableItems() as $item) {
  181.                 /**
  182.                  * @var $item \Bitrix\Sale\BasketItem
  183.                  * @var $shipmentItem \Bitrix\Sale\ShipmentItem
  184.                  * @var $item \Bitrix\Sale\BasketItem
  185.                  */
  186.                 $shipmentItem = $shipmentItemCollection->createItem($item);
  187.                 $shipmentItem->setQuantity($item->getQuantity());
  188.                 $shipmentItem->setField('DELIVERY_ID', $this->request['delivery_id']);
  189.             }
  190.  
  191.         } catch (\Exception $e) {
  192.             $this->errors[] = $e->getMessage();
  193.         }
  194.     }
  195.  
  196.     protected function setOrderProps()
  197.     {
  198.         global $USER;
  199.         $arUser = $USER->GetByID(intval($USER->GetID()))
  200.             ->Fetch();
  201.  
  202.         if (is_array($arUser)) {
  203.             $fio = $arUser['LAST_NAME'] . ' ' . $arUser['NAME'] . ' ' . $arUser['SECOND_NAME'];
  204.             $fio = trim($fio);
  205.             $arUser['FIO'] = $fio;
  206.         }
  207.  
  208.         foreach ($this->order->getPropertyCollection() as $prop) {
  209.             /** @var \Bitrix\Sale\PropertyValue $prop */
  210.             $value = '';
  211.  
  212.             if (empty($value)) {
  213.                 foreach ($this->request as $key => $val) {
  214.                     if (strtolower($key) == strtolower($prop->getField('CODE'))) {
  215.                         $value = $val;
  216.                     }
  217.                 }
  218.             }
  219.  
  220.             if (empty($value)) {
  221.                 $value = $prop->getProperty()['DEFAULT_VALUE'];
  222.             }
  223.  
  224.             if (!empty($value)) {
  225.                 $prop->setValue($value);
  226.             }
  227.         }
  228.     }
  229.  
  230.     protected function calcAction()
  231.     {
  232.         $this->setTemplateName('');
  233.  
  234.         //Собираем ID доставок
  235.         $deliveryIDs = [];
  236.         if (isset($this->request['delivery_id'])) {
  237.             if (is_array($this->request['delivery_id'])) {
  238.                 foreach ($this->request['delivery_id'] as $val) {
  239.                     if (intval($val) > 0) {
  240.                         $deliveryIDs[intval($val)] = intval($val);
  241.                     }
  242.                 }
  243.             } elseif (intval($this->request['delivery_id']) > 0) {
  244.                 $deliveryIDs = [intval($this->request['delivery_id'])];
  245.             } else {
  246.                 $deliveryIDs = [];
  247.             }
  248.  
  249.         }
  250.  
  251.         if(empty($deliveryIDs)):
  252.  
  253.             $deliveries = \Bitrix\Sale\Delivery\Services\Manager::getActiveList();
  254.  
  255.             foreach ( $deliveries as $index => $value) {
  256.  
  257.                 $deliveryIDs[$index] = $index;
  258.  
  259.             }
  260.  
  261.  
  262.         endif;
  263.         //На выходе в любом случае будет массив
  264.         sort($deliveryIDs);
  265.  
  266.         if (empty($deliveryIDs)) {
  267.             throw new \Exception('Нет доставок для расчета');
  268.         }
  269.  
  270.         $shipment = false;
  271.         /** @var \Bitrix\Sale\Shipment $shipmentItem */
  272.         foreach ($this->order->getShipmentCollection() as $shipmentItem) {
  273.             if (!$shipmentItem->isSystem()) {
  274.                 $shipment = $shipmentItem;
  275.                 break;
  276.             }
  277.         }
  278.  
  279.         if (!$shipment) {
  280.             throw new \Exception('Отгрузка не найдена');
  281.         }
  282.  
  283.         //Массив с доставками,
  284.         $availableDeliveries = \Bitrix\Sale\Delivery\Services\Manager::getRestrictedObjectsList(
  285.             $shipment
  286.         );
  287.  
  288.         foreach ($deliveryIDs as $deliveryId) {
  289.             $obDelivery = false;
  290.             if (isset($availableDeliveries[$deliveryId])) {
  291.                 //Если переданный из запроса ID доставки доступен покупателю
  292.                 $obDelivery = $availableDeliveries[$deliveryId];
  293.             }
  294.  
  295.             if ($obDelivery) {
  296.                 $arDelivery = [
  297.                     'id'                => $obDelivery->getId(),
  298.                     'name'              => $obDelivery->getName(),
  299.                     'logo_path'         => $obDelivery->getLogotipPath(),
  300.                     'show'              => false,
  301.                     'calculated'        => false,
  302.                     'period'            => '',
  303.                     'price'             => 0,
  304.                     'price_formated'    => '',
  305.                 ];
  306.  
  307.                 $calcResult = $obDelivery->calculate($shipment);
  308.  
  309.                 if ($calcResult->isSuccess()) {
  310.                     $arDelivery['calculated'] = true;
  311.                     $arDelivery["price"] = $calcResult->getPrice();
  312.                     $arDelivery["price_formated"] = \SaleFormatCurrency(
  313.                         $calcResult->getPrice(),
  314.                         $this->order->getCurrency()
  315.                     );
  316.  
  317.                     if (strlen($calcResult->getPeriodDescription()) > 0) {
  318.                         $arDelivery["period_text"] = $calcResult->getPeriodDescription();
  319.                     }
  320.                 }
  321.  
  322.                 if (floatval($arDelivery['price']) > 0) {
  323.                     $arDelivery['show'] = true;
  324.                 }
  325.  
  326.                 if (empty($arDelivery["period_text"])) {
  327.                     $arDelivery["period_text"] = '...';
  328.                 }
  329.  
  330.                 $this->arResponse['deliveries'][$arDelivery['ID']] = $arDelivery;
  331.             } else {
  332.                 //В аякс ответе, даже недоступную доставку возвращаем
  333.                 $this->arResponse['deliveries'][$deliveryId] = [
  334.                     'id'   => $deliveryId,
  335.                     'show' => false
  336.                 ];
  337.             }
  338.         }
  339.  
  340.     }
  341.  
  342.     protected function getDeliveries(){
  343.  
  344.         $shipment = false;
  345.         /** @var \Bitrix\Sale\Shipment $shipmentItem */
  346.         foreach ($this->order->getShipmentCollection() as $shipmentItem) {
  347.             if (!$shipmentItem->isSystem()) {
  348.                 $shipment = $shipmentItem;
  349.                 break;
  350.             }
  351.         }
  352.  
  353.         if (!$shipment) {
  354.             throw new \Exception('Отгрузка не найдена');
  355.         }
  356.  
  357.         //Массив с доставками,
  358.         $availableDeliveries = \Bitrix\Sale\Delivery\Services\Manager::getRestrictedObjectsList(
  359.             $shipment
  360.         );
  361.  
  362.         $arDeliveries = array();
  363.  
  364.         foreach ($availableDeliveries as $delivery) {
  365.  
  366.             $obDelivery = $delivery;
  367.  
  368.             if ($obDelivery) {
  369.  
  370.                 $arDelivery = [
  371.                     'id'                => $obDelivery->getId(),
  372.                     'name'              => $obDelivery->getName(),
  373.                     'logo_path'         => $obDelivery->getLogotipPath(),
  374.                     'show'              => false,
  375.                     'calculated'        => false,
  376.                     'period'            => '',
  377.                     'price'             => 0,
  378.                     'price_formated'    => '',
  379.                 ];
  380.                 $shipment_inner = $this->order->getShipmentCollection()->createItem(
  381.                     Bitrix\Sale\Delivery\Services\Manager::getObjectById(
  382.                         intval($obDelivery->getId())
  383.                     )
  384.                 );
  385.                 $calcResult = $obDelivery->calculate($shipment_inner);
  386.  
  387.  
  388.                 if ($calcResult->isSuccess()) {
  389.                     $arDelivery['calculated'] = true;
  390.                     $arDelivery["price"] = $calcResult->getPrice();
  391.                     $arDelivery["price_formated"] = \SaleFormatCurrency(
  392.                         $calcResult->getPrice(),
  393.                         $this->order->getCurrency()
  394.                     );
  395.  
  396.                     if (strlen($calcResult->getPeriodDescription()) > 0) {
  397.                         $arDelivery["period_text"] = $calcResult->getPeriodDescription();
  398.                     }
  399.                 }
  400.  
  401.                 if (floatval($arDelivery['price']) > 0) {
  402.                     $arDelivery['show'] = true;
  403.                 }
  404.  
  405.                 if (empty($arDelivery["period_text"])) {
  406.                     $arDelivery["period_text"] = '...';
  407.                 }
  408.                 $shipment_inner->delete();
  409.                 $arDeliveries[] = $arDelivery;
  410.             }
  411.         }
  412.  
  413.         return $arDeliveries;
  414.  
  415.     }
  416.  
  417.     public function getPropByCode($code)
  418.     {
  419.         $result = false;
  420.  
  421.         $propId = 0;
  422.         if (isset($this->propMap[$code])) {
  423.             $propId = $this->propMap[$code];
  424.         }
  425.  
  426.         if ($propId > 0) {
  427.             $result = $this->order
  428.                 ->getPropertyCollection()
  429.                 ->getItemByOrderPropertyId($propId);
  430.         }
  431.  
  432.         return $result;
  433.     }
  434.  
  435.     public function getPropDataByCode($code)
  436.     {
  437.         $result = [];
  438.  
  439.         $propId = 0;
  440.         if (isset($this->propMap[$code])) {
  441.             $propId = $this->propMap[$code];
  442.         }
  443.  
  444.         if ($propId > 0) {
  445.             $result = $this->order
  446.                 ->getPropertyCollection()
  447.                 ->getItemByOrderPropertyId($propId)
  448.                 ->getFieldValues();
  449.         }
  450.  
  451.         return $result;
  452.     }
  453.  
  454.     function executeComponent()
  455.     {
  456.         global $APPLICATION;
  457.  
  458.         if ($this->arParams['IS_AJAX']) {
  459.             $APPLICATION->RestartBuffer();
  460.         }
  461.  
  462.         $this->createVirtualOrder();
  463.  
  464.         $this->arDeliveries = $this->getDeliveries();
  465.        
  466.         $this->createVirtualOrder();
  467.         if(!empty($this->arParams['ACTION'])) {
  468.             if (is_callable([$this, $this->arParams['ACTION'] . "Action"])) {
  469.                 try {
  470.                     call_user_func([$this, $this->arParams['ACTION'] . "Action"]);
  471.                 } catch (\Exception $e) {
  472.                     $this->errors[] = $e->getMessage();
  473.                 }
  474.             }
  475.         }
  476.  
  477.         if (isset($this->request['save']) && $this->request['save'] == 'Y') {
  478.  
  479.  
  480.             if (intval($this->request['payment_id']) > 0) {
  481.                 $paymentCollection = $this->order->getPaymentCollection();
  482.                 $payment = $paymentCollection->createItem(
  483.                     Bitrix\Sale\PaySystem\Manager::getObjectById(
  484.                         intval($this->request['payment_id'])
  485.                     )
  486.                 );
  487.                 $payment->setField("SUM", $this->order->getPrice());
  488.                 $payment->setField("CURRENCY", $this->order->getCurrency());
  489.  
  490.             }
  491.             else{
  492.  
  493.                 $payment_id = 19;
  494.  
  495.                 $paymentCollection = $this->order->getPaymentCollection();
  496.                 $payment = $paymentCollection->createItem(
  497.                     Bitrix\Sale\PaySystem\Manager::getObjectById($payment_id)
  498.  
  499.                 );
  500.                
  501.                 $payment->setField("SUM", $this->order->getPrice());
  502.                 $payment->setField("CURRENCY", $this->order->getCurrency());
  503.  
  504.  
  505.  
  506.             }
  507.             $this->order->save();
  508.             $url = 'https://secure.payonlinesystem.com/ru/payment/select/';
  509.             $postData = array(
  510.                 'MerchantId' => '77863',
  511.                 'OrderId' => $this->order->getId(),
  512.                 'Amount'=> number_format($this->order->getPrice(), 2, ".", ""),
  513.                 'Currency' => $this->order->getCurrency(),
  514.                 'PrivateSecurityKey'=> 'a7affa62-3e13-432d-93fd-fef97f7a27a9',
  515.                 'ReturnUrl' => SITE_SERVER_NAME.'/bitrix/tools/biznesup.payonline/result.php',
  516.                 'FailUrl' => SITE_SERVER_NAME.'/bitrix/tools/biznesup.payonline/result.php'
  517.             );
  518.  
  519.             $hash = "MerchantId=".$postData['MerchantId']."&".
  520.                 "OrderId=".$postData['OrderId']."&".
  521.                 "Amount=".$postData['Amount']."&".
  522.                 "Currency=".$postData['Currency']."&".
  523.                 "PrivateSecurityKey=".$postData['PrivateSecurityKey'];
  524.  
  525.             $hash = md5($hash);
  526.             $global_url = $url."?"."MerchantId=".$postData['MerchantId']."&".
  527.                 "OrderId=".$postData['OrderId']."&".
  528.                 "Amount=".$postData['Amount']."&".
  529.                 "Currency=".$postData['Currency']."&".
  530.                 "SecurityKey=".$hash."&".
  531.                 "ReturnUrl=".$postData['ReturnUrl']."&".
  532.                 "FailUrl=".$postData['ReturnUrl'];
  533.  
  534.             LocalRedirect($global_url);
  535.         }
  536.  
  537.         if ($this->arParams['IS_AJAX']) {
  538.             if ($this->getTemplateName() != '') {
  539.                 ob_start();
  540.                 $this->includeComponentTemplate();
  541.                 $this->arResponse['html'] = ob_get_contents();
  542.                 ob_end_clean();
  543.             }
  544.  
  545.             $this->arResponse['errors'] = $this->errors;
  546.  
  547.             header('Content-Type: application/json');
  548.             echo json_encode($this->arResponse);
  549.             $APPLICATION->FinalActions();
  550.             die();
  551.         } else {
  552.             $this->includeComponentTemplate();
  553.         }
  554.     }
  555. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement