403Webshell
Server IP : 80.87.202.40  /  Your IP : 216.73.216.169
Web Server : Apache
System : Linux rospirotorg.ru 5.14.0-539.el9.x86_64 #1 SMP PREEMPT_DYNAMIC Thu Dec 5 22:26:13 UTC 2024 x86_64
User : bitrix ( 600)
PHP Version : 8.2.27
Disable Function : NONE
MySQL : OFF |  cURL : ON |  WGET : ON |  Perl : ON |  Python : OFF |  Sudo : ON |  Pkexec : ON
Directory :  /home/bitrix/ext_www/rospirotorg.ru/bitrix/modules/sberbank.ecom2/handler/

Upload File :
current_dir [ Writeable] document_root [ Writeable]

 

Command :


[ Back ]     

Current File : /home/bitrix/ext_www/rospirotorg.ru/bitrix/modules/sberbank.ecom2/handler/handler.php
<?php

namespace Sale\Handlers\PaySystem;

use Bitrix\Main;
use Bitrix\Main\Error;
use Bitrix\Main\Localization\Loc;
use Bitrix\Main\Request;
use Bitrix\Main\Text\Encoding;
use Bitrix\Main\Type\DateTime;
use Bitrix\Main\Web;
use Bitrix\Sale\BusinessValue;
use Bitrix\Sale\PaySystem;
use Bitrix\Sale\Payment;
use Bitrix\Sale\Order;
use Bitrix\Main\Loader;
use Bitrix\Main\Config\Option;

IncludeModuleLangFile(__FILE__);
require dirname(dirname(__FILE__)) . '/config.php';
Loader::includeModule('sberbank.ecom2');

/**
 * Class SberbankEcomHandler
 * @package Sale\Handlers\PaySystem
 */
class sberbank_ecom2Handler extends PaySystem\ServiceHandler implements PaySystem\IPrePayable
{
	/**
	 * @param Payment $payment
	 * @param Request|null $request
	 * @return PaySystem\ServiceResult
	 */
	public function initiatePay(Payment $payment, Request $request = null)
	{
		$moduleId = 'sberbank.ecom2';

		$RBS_Gateway = new \Sberbank\Payments\Gateway;


		// module settings
		$RBS_Gateway->setOptions(array(
			'module_id' => Option::get($moduleId, 'MODULE_ID'),
			'gate_url_prod' => Option::get($moduleId, 'SBERBANK_PROD_URL'),
			'gate_url_test' => Option::get($moduleId, 'SBERBANK_TEST_URL'),
			'gate_url_alternative_prod' => Option::get($moduleId, 'SBERBANK_PROD_URL_ALTERNATIVE_DOMAIN'),
			'gate_url_alternative_test' => Option::get($moduleId, 'SBERBANK_TEST_URL_ALTERNATIVE_DOMAIN'),
			'module_version' => Option::get($moduleId, 'MODULE_VERSION'),
			'iso' => unserialize(Option::get($moduleId, 'ISO')),
			'cms_version' => 'Bitrix ' . SM_VERSION,
			'language' => 'ru',
			'default_cartItem_tax' => Option::get($moduleId, 'TAX_DEFAULT'),
			'ignore_product_tax' => Option::get($moduleId, 'IGNORE_PRODUCT_TAX'),
			'callback_mode' => Option::get($moduleId, 'RBS_ENABLE_CALLBACK'),
			'measurement_code' => Option::get($moduleId, 'MEASUREMENT_CODE'),
			'callback_actions' => unserialize(Option::get($moduleId, 'CALLBACK_ACTIONS')),
			'callback_action_order_status' => unserialize(Option::get($moduleId, 'CALLBACK_ACTION_ORDER_STATUS')),
			'callback_type' =>  Option::get($moduleId, 'RBS_CALLBACK_TYPE') === 'DYNAMIC' ? 'DYNAMIC' : 'STATIC',
			// 'additionalOfdParams' => array(
			// 'agent_info.type' => 6,
			// 'agent_info.paying.operation' => '',
			// 'agent_info.paying.phones' => '',
			// 'agent_info.paymentsOperator.phones' => '',
			// 'agent_info.MTOperator.address' => '',
			// 'agent_info.MTOperator.inn' => '',
			// 'agent_info.MTOperator.name' => '',
			// 'agent_info.MTOperator.phones' => '',
			// 'supplier_info.inn' => '',
			// 'supplier_info.name' => '',
			// 'supplier_info.phones' => '',
			// 'cashier' => '',
			// 'additional_check_props' => '',
			// 'additional_user_props.name' => '',
			// 'additional_user_props.value' => '',
			// ),
		));

		// handler settings
		$RBS_Gateway->setOptions(array(
			'ofd_tax' => $this->getBusinessValue($payment, 'SBERBANK_OFD_TAX_SYSTEM') == 0 ? 0 : $this->getBusinessValue($payment, 'SBERBANK_OFD_TAX_SYSTEM'),
			'ofd_enabled' => $this->getBusinessValue($payment, 'SBERBANK_OFD_RECIEPT')  == 'Y' ? 1 : 0,
			'ffd_version' => $this->getBusinessValue($payment, 'SBERBANK_FFD_VERSION'),
			'ffd_payment_object' => $this->getBusinessValue($payment, 'SBERBANK_FFD_PAYMENT_OBJECT'),
			'ffd_payment_object_delivery' => $this->getBusinessValue($payment, 'SBERBANK_FFD_PAYMENT_OBJECT_DELIVERY'),
			'ffd_payment_method' => $this->getBusinessValue($payment, 'SBERBANK_FFD_PAYMENT_METHOD'),
			'ffd_payment_method_delivery' => $this->getBusinessValue($payment, 'SBERBANK_FFD_PAYMENT_METHOD_DELIVERY'),
			'test_mode' => $this->getBusinessValue($payment, 'SBERBANK_GATE_TEST_MODE') == 'Y' ? 1 : 0,
			'handler_two_stage' => $this->getBusinessValue($payment, 'SBERBANK_HANDLER_TWO_STAGE') == 'Y' ? 1 : 0,
			'handler_logging' => $this->getBusinessValue($payment, 'SBERBANK_HANDLER_LOGGING') == 'Y' ? 1 : 0,
			'enable_cacert' => $this->getBusinessValue($payment, 'SBERBANK_API_ENABLE_CACERT')  == 'Y' ? true : false,
			'fes_cashboxId' => Option::get($moduleId, 'RBS_ENABLE_FES_CODES') ? $this->getBusinessValue($payment, 'RBS_FES_CASHBOX_ID') : "",
			'enable_order_payer_data' => Option::get($moduleId, 'RBS_ENABLE_ORDER_PAYER_DATA'),
		));

		$RBS_Gateway->buildData(array(
			'orderNumber' => $this->getBusinessValue($payment, 'SBERBANK_ORDER_NUMBER') . '_' . $payment->getField('ID'),
			'amount' => $this->getBusinessValue($payment, 'SBERBANK_ORDER_AMOUNT'),
			'userName' => $this->getBusinessValue($payment, 'SBERBANK_GATE_LOGIN'),
			'password' => $this->getBusinessValue($payment, 'SBERBANK_GATE_PASSWORD'),
			'description' => $this->getOrderDescription($payment, 'SBERBANK_ORDER_DESCRIPTION'),
		));


		$protocol = isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== "off" ? 'https://' : 'http://';
		$domain_name = strtok($_SERVER['HTTP_HOST'], ":");

		if (strlen($domain_name) < 3) {
			$domain_name = $_SERVER['SERVER_NAME'];
		}
		if (strlen($domain_name) < 3) {
			$domain_name = Option::get($moduleId, 'NOTIFY_URL', '');
		}

		if (strlen($domain_name) > 3) {
			$RBS_Gateway->setOptions(
				array(
					'domain_found' => true,
					'callback_url' => html_entity_decode($protocol . $domain_name . '/bitrix/tools/sale_ps_result.php?PAYMENT=SBERBANK&OPERATION_CALLBACK=SBER')
				)
			);
		}

		global $USER;
		if ($USER->IsAuthorized()) {
			$id = $USER->GetID();
			$email = $USER->GetEmail();
			$site_url = $domain_name;
			$RBS_Gateway->buildData(array(
				'clientID' => $this->createStoredCredentialClientID($id, $email, $site_url)
			));
		};

		$RBS_Gateway->buildData(array(
			'returnUrl' => $protocol . $domain_name . '/bitrix/tools/sale_ps_result.php' . '?PAYMENT=SBERBANK&ORDER_ID=' . $payment->getField('ORDER_ID') . '&PAYMENT_ID=' . $payment->getField('ID')		
		));

		if (Option::get($moduleId, 'RBS_CALLBACK_TYPE')) {
			$RBS_Gateway->buildData(array(
				'dynamicCallbackUrl' => $protocol . $domain_name . '/bitrix/tools/sale_ps_result.php' . '?PAYMENT=SBERBANK&ORDER_ID=' . $payment->getField('ORDER_ID') . '&PAYMENT_ID=' . $payment->getField('ID') . '&OPERATION_CALLBACK=SBER&OPERATION_TYPE=DYNAMIC',
			));
		}

		$Order = Order::load($payment->getOrderId());
		$propertyCollection = $Order->getPropertyCollection();

		$phone_key = strlen(Option::get($moduleId, 'OPTION_PHONE')) > 0 ? Option::get($moduleId, 'OPTION_PHONE') : 'PHONE';
		$email_key = strlen(Option::get($moduleId, 'OPTION_EMAIL')) > 0 ? Option::get($moduleId, 'OPTION_EMAIL') : 'EMAIL';
		$fio_key = strlen(Option::get($moduleId, 'OPTION_FIO')) > 0 ? Option::get($moduleId, 'OPTION_FIO') : 'FIO';

		$phone = preg_replace('/\D+/', '', $this->getPropertyValueByCode($propertyCollection, $phone_key));

		if (substr($phone, 0, 1) == '7') {
			$phone = '+' . $phone;
		}
		if (substr($phone, 0, 1) == '8') {
			$phone[0] = '7';
			$phone = '+' . $phone;
		}

		$RBS_Gateway->setOptions(array(
			'customer_name' => $this->getPropertyValueByCode($propertyCollection, $fio_key),
			'customer_email' => $this->getPropertyValueByCode($propertyCollection, $email_key),
			'customer_phone' => $phone,
		));

		if ($RBS_Gateway->ofdEnable()) {

			
			$Basket = $Order->getBasket();
			$basketItems = $Basket->getBasketItems();
			$positions = [];
			$lastIndex = 0;
			$nomenclature_code_value = Option::get($moduleId, 'NOMECLATURE_CODE_VALUE');

			foreach ($basketItems as $key => $BasketItem) {
				$fes_truCode = false;
				$nomenclature = false;
				if(Option::get($moduleId, 'RBS_ENABLE_FES_CODES') || Option::get($moduleId, 'RBS_ENABLE_NOMECLATURE')) {
					$productId = $BasketItem->getProductId(); // Получаем ID товара
				    // Запрашиваем свойство "FES" у товара из инфоблока
				    $productData = \CIBlockElement::GetList(
				        [],
				        ['ID' => $productId],
				        false,
				        false,
				        ['ID', 'IBLOCK_ID', 'PROPERTY_FES_TRUCODE','PROPERTY_' . $nomenclature_code_value]
				    );
				    if ($product = $productData->GetNext()) {
				        $fes_truCode = $product['PROPERTY_FES_TRUCODE_VALUE'] ? $product['PROPERTY_FES_TRUCODE_VALUE'] : false;
				        $nomenclature = $product['PROPERTY_'.  strtoupper($nomenclature_code_value) .'_VALUE'] ? $product['PROPERTY_'.  strtoupper($nomenclature_code_value) .'_VALUE'] : false;
				    }
			    }

				$lastIndex = $key + 1;
				$position = array(
		            'positionId' => $key,
		            'itemCode' => $BasketItem->getProductId(),
		            'name' => str_replace("\n", "", mb_substr($BasketItem->getField('NAME'), 0, 120)),
		            'itemAmount' => $BasketItem->getFinalPrice(),
		            'itemPrice' => $BasketItem->getPrice(),
		            'quantity' => array(
		                'value' => $BasketItem->getQuantity(),
		                'measure' => $BasketItem->getField('MEASURE_NAME') ? $BasketItem->getField('MEASURE_NAME') : Loc::getMessage('SBERBANK_PAYMENT_FIELD_MEASURE'),
		            ),
		            'tax' => array(
		                'taxType' =>  $RBS_Gateway->getTaxCode( $BasketItem->getField('VAT_RATE')),
		            ),
		            'fes_truCode' => $fes_truCode,
		            'nomenclature' => $nomenclature,
		        );

				// If need support suplier_info
				// $position['agent_info'] = array(
				// 	'agent_info.type' => '6',
				// 	'agent_info.MTOperator.phones' => '+79169998877',
				// );
				
				$positions[] = $position;


				// $RBS_Gateway->setPosition($position);
			}
			if($Order->getField('PRICE_DELIVERY') > 0) {
				
				Loader::includeModule('catalog');
				$deliveryInfo = \Bitrix\Sale\Delivery\Services\Manager::getById($Order->getField('DELIVERY_ID'));

				$deliveryVatItem = \CCatalogVat::GetByID($deliveryInfo['VAT_ID'])->Fetch();
				$RBS_Gateway->setOptions(array(
				    'delivery' => true,
				));
				$positions[] = array(
		            'positionId' => $lastIndex + 1,
		            'itemCode' => 'DELIVERY_' . $Order->getField('DELIVERY_ID'),
		            'name' => Loc::getMessage('SBERBANK_PAYMENT_FIRLD_DELIVERY'),
		            'itemAmount' => $Order->getField('PRICE_DELIVERY'),
		            'itemPrice' => $Order->getField('PRICE_DELIVERY'),
		            'quantity' => array(
		                'value' => 1,
		                'measure' => Loc::getMessage('SBERBANK_PAYMENT_FIELD_MEASURE'),
		            ),
		            'tax' => array(
		                'taxType' => $RBS_Gateway->getTaxCodeDelivery($deliveryVatItem['RATE']),
		            ),
		        );
			}

			if(Option::get($moduleId, 'DISCOUNT_HELPER')) {
		     // DISCOUNT CALCULATE
			    $RBS_Discount = new \Sberbank\Payments\Discount;
				$result_order_sum = $Order->getPrice() - $Order->getSumPaid();
	            $discount = $RBS_Discount->discoverDiscount($result_order_sum,$positions);
	            if($discount > 0) { 
	                $RBS_Discount->setOrderDiscount($discount);
	                $recalculatedPositions = $RBS_Discount->normalizeItems($positions);
	                $recalculatedAmount = $RBS_Discount->getResultAmount();
	                $positions = $recalculatedPositions;
	            }
            }

            
            foreach ($positions as $key => $position) {
				$RBS_Gateway->setPosition($position);
			}
		}

		$gateResponse = $RBS_Gateway->registerOrder();
		$params = array(
			'sberbank_result' => $gateResponse,
			'payment_link' => $RBS_Gateway->getPaymentLink(),
			'currency' => $payment->getField('CURRENCY'),
			'auto_redirect_exceptions' => unserialize(Option::get($moduleId, 'AUTO_REDIRECT_EXCEPTIONS')),
		);
		$this->setExtraParams($params);

		$result = $this->showTemplate($payment, "payment");
		if (method_exists($result, 'setPaymentUrl')) {
			$result->setPaymentUrl($RBS_Gateway->getPaymentLink());
		}

		return $result;
	}

	public function processRequest(Payment $payment, Request $request)
	{
		global $APPLICATION;
		$moduleId = 'sberbank.ecom2';
		$result = new PaySystem\ServiceResult();
		$order = Order::load($payment->getOrderId());

		$handler_logging =  $this->getBusinessValue($payment, 'SBERBANK_HANDLER_LOGGING') == 'Y' ? 1 : 0;

		// $request_data = $request->getQueryList()->toArray();
		$RBS_Gateway = new \Sberbank\Payments\Gateway;
		$RBS_Gateway->setOptions(array(
			// module settings
			'gate_url_prod' => Option::get($moduleId, 'SBERBANK_PROD_URL'),
			'gate_url_test' => Option::get($moduleId, 'SBERBANK_TEST_URL'),
			'gate_url_alternative_prod' => Option::get($moduleId, 'SBERBANK_PROD_URL_ALTERNATIVE_DOMAIN'),
			'gate_url_alternative_test' => Option::get($moduleId, 'SBERBANK_TEST_URL_ALTERNATIVE_DOMAIN'),
			'test_mode' => $this->getBusinessValue($payment, 'SBERBANK_GATE_TEST_MODE') == 'Y' ? 1 : 0,
			'callback_redirect' => $request->get('CALLBACK_REDIRECT') == 1 ? 1 : 0,
			'handler_logging' => $handler_logging,
			'callback_operation' => $request->get('operation')
		));

		$RBS_Gateway->buildData(array(
			'userName' => $this->getBusinessValue($payment, 'SBERBANK_GATE_LOGIN'),
			'password' => $this->getBusinessValue($payment, 'SBERBANK_GATE_PASSWORD'),
			'orderId' => $request->get('CALLBACK_REDIRECT') == 1 ? $request->get('mdOrder') : $request->get('orderId'),
		));

		$gateResponse = $RBS_Gateway->checkOrder();

		$resultId = explode("_", $gateResponse['orderNumber']);
		array_pop($resultId);
		$res_payment_id = array_pop($resultId);
		$resultId = implode('_', $resultId);

		$successPayment = true;
		$change_order_status_logic = true;


		$order_status_map_callback = [
		    0 => 'FALSE',
		    1 => 'approved',
		    2 => 'deposited',
		    3 => 'reversed',
		    4 => 'refunded',
		    5 => 'FALSE',
		    6 => 'declinedByTimeout',
		];
		
		$operation_name = $order_status_map_callback[$gateResponse['orderStatus']];

		if ($resultId != $this->getBusinessValue($payment, 'SBERBANK_ORDER_NUMBER')) {
			$successPayment = false;
		}

		if ($gateResponse['errorCode'] != 0 || ($gateResponse['orderStatus'] != 1 && $gateResponse['orderStatus'] != 2)) {
			$successPayment = false;
		}

		// Order canceled by tymeout
		if (
			$request->get('CALLBACK_REDIRECT') == 1 && $request->get('operation') === 'declinedByTimeout'
			&& Option::get($moduleId, 'CANCEL_ORDER_BY_TIMEOUT')
			&& $request->get('CALLBACK_REDIRECT') == 1
			&& !$payment->isPaid()
		) {

			$this->cancelOrder($payment->getOrderId());
			return $result;
		}

		// Payment success
		if ($successPayment && $request->get('operation') == 'deposited' && !$payment->isPaid() && ($request->get('CALLBACK_REDIRECT') == 1 || !Option::get($moduleId, 'RBS_ENABLE_CALLBACK'))) {

			$inputJson = self::encode($request->toArray());

			$fields = array(
				'PS_INVOICE_ID' => $request->get('CALLBACK_REDIRECT') == 1 ? $request->get('mdOrder') : $request->get('orderId'),
				"PS_STATUS_CODE" => $gateResponse['orderStatus'],
				"PS_STATUS_DESCRIPTION" => $gateResponse["cardAuthInfo"]["pan"] . ";" . $gateResponse['cardAuthInfo']["cardholderName"],
				"PS_SUM" => $gateResponse["amount"] / 100,
				"PS_STATUS" => 'Y',

				"PS_CURRENCY" => $gateResponse["currency"],
				"PS_RESPONSE_DATE" => new DateTime()
			);

			$result->setOperationType(PaySystem\ServiceResult::MONEY_COMING);
			$result->setPsData($fields);


			// set delivery status
			if ($this->getBusinessValue($payment, 'SBERBANK_HANDLER_SHIPMENT') == 'Y') {
				$shipmentCollection = $order->getShipmentCollection();
				foreach ($shipmentCollection as $shipment) {
					if (!$shipment->isSystem()) {
						$shipment->allowDelivery();
					}
				}
			}
		}


		$is_need_payment_cancel = Option::get($moduleId, 'CANCEL_PAYMENT_BY_REFUNDED');

		// Payment reversed
		if($payment->isPaid() && $gateResponse['orderStatus'] === 3 && $request->get('CALLBACK_REDIRECT') == 1) {

			$fields = array( "PS_RESPONSE_DATE" => new DateTime());

			$is_part_cancel = $gateResponse['paymentAmountInfo']['approvedAmount'] > 0 && $gateResponse['paymentAmountInfo']['approvedAmount'] < $gateResponse['amount'];
			$is_full_cancel = $gateResponse['paymentAmountInfo']['approvedAmount'] === 0;

			if($is_full_cancel) {
				$fields['PS_STATUS_MESSAGE'] = Loc::getMessage('SBERBANK_CANCEL_FULL_MESSAGE') . ($gateResponse['amount'] / 100) . Loc::getMessage('SBERBANK_R');
			} else if($is_part_cancel) {
				$cancel_summ = $gateResponse['amount'] - $gateResponse['paymentAmountInfo']['approvedAmount'];
				$fields['PS_STATUS_MESSAGE'] = Loc::getMessage('SBERBANK_CANCEL_MESSAGE') . ($cancel_summ / 100) . Loc::getMessage('SBERBANK_R');
			}

			if ($is_need_payment_cancel && $is_full_cancel) {
				$result->setOperationType(PaySystem\ServiceResult::MONEY_LEAVING);
			}

			$result->setPsData($fields);
		}


		// Payment refund
		if($payment->isPaid() && $gateResponse['orderStatus'] === 4 && $request->get('CALLBACK_REDIRECT') == 1) {
			
			$fields = array( "PS_RESPONSE_DATE" => new DateTime());

			$is_part_refunted = $gateResponse['paymentAmountInfo']['approvedAmount'] === $gateResponse['amount'] && $gateResponse['paymentAmountInfo']['refundedAmount'] != 0;
			$is_full_refunded = $gateResponse['paymentAmountInfo']['approvedAmount'] === $gateResponse['paymentAmountInfo']['refundedAmount'];


			if($is_full_refunded) {
				$fields['PS_STATUS_MESSAGE'] = Loc::getMessage('SBERBANK_REFUNDED_FULL_MESSAGE') . ($gateResponse['amount'] / 100) . Loc::getMessage('SBERBANK_R');
			} else if($is_part_refunted) {
				$fields['PS_STATUS_MESSAGE'] = Loc::getMessage('SBERBANK_REFUNDED_MESSAGE') . ($gateResponse['paymentAmountInfo']['refundedAmount'] / 100) . Loc::getMessage('SBERBANK_R');
			}

			if ($is_need_payment_cancel && $is_full_refunded) {
				$result->setOperationType(PaySystem\ServiceResult::MONEY_LEAVING);
			}

			$result->setPsData($fields);
		}


		// Change order status
		if ($request->get('CALLBACK_REDIRECT') == 1) {

			// set order status
			$option_order_status = unserialize(Option::get($moduleId, 'CALLBACK_ACTION_ORDER_STATUS'));
			$new_status = $option_order_status[$operation_name];

			$is_need_change_status = true;

			if ($gateResponse['orderStatus'] === 4 && $gateResponse['paymentAmountInfo']['depositedAmount'] > 0) {
				$is_need_change_status = false;
			}
			if ($new_status != 'FALSE' && $is_need_change_status) {
				$statuses = array();
				$dbStatus = \CSaleStatus::GetList(array("SORT" => "ASC"), array("LID" => LANGUAGE_ID), false, false, array("ID", "NAME", "SORT"));
				while ($arStatus = $dbStatus->GetNext()) {
					$statuses[$arStatus["ID"]] = "[" . $arStatus["ID"] . "] " . $arStatus["NAME"];
				}

				if (array_key_exists($new_status, $statuses)) {
					$order->setField('STATUS_ID', $new_status);
				} else {
					echo '<span style="display:block; font-size:16px; display:block; color:red;padding:20px 0;">ERROR! CANT CHANGE ORDER STATUS</span>';
				}
			}
			$order->save();

			require dirname(dirname(__FILE__)) . '/config.php';
			if ($SBERBANK_CONFIG['CALLBACK_BROADCAST']) {
				$broadcast_url = Option::get($moduleId, 'CALLBACK_REDIRECT_BROADCAST', '');
				$queryParams = $request->getRequestMethod() == 'GET' ? $request->getQueryList()->toArray() : $request->getPostList()->toArray();
				if (strlen($broadcast_url) > 5) {
					$RBS_Gateway->broadcast_callback($broadcast_url, $queryParams);
				}
			}

			return $result;
		}


		$order->save();
		
		$returnPage = $this->getBusinessValue($payment, 'SBERBANK_RETURN_URL');
		$failPage = $this->getBusinessValue($payment, 'SBERBANK_FAIL_URL');

		if (strlen($returnPage) > 4 && $successPayment) {
			echo "<script>window.location='" . $this->getOrderDescription($payment, 'SBERBANK_RETURN_URL') . "'</script>";
		} else if (strlen($failPage) > 4 && !$successPayment) {
			echo "<script>window.location='" . $this->getOrderDescription($payment, 'SBERBANK_FAIL_URL') . "'</script>";
		} else {
			self::printResultText($payment, $successPayment);
		}


		return $result;
	}

	public function getPaymentIdFromRequest(Request $request)
	{
		$paymentId = $request->get('PAYMENT_ID');
		return intval($paymentId);
	}

	public function getCurrencyList()
	{
		return array('RUB', 'EUR', 'USD', 'UAH', 'BYN');
	}

	public static function getIndicativeFields()
	{
		return array('PAYMENT' => 'SBERBANK');
	}

	static protected function isMyResponseExtended(Request $request, $paySystemId)
	{
		global $APPLICATION;

		$RBS_Gateway = new \Sberbank\Payments\Gateway;

		if ($request->get('OPERATION_CALLBACK') == 'SBER' && $request->get('CALLBACK_REDIRECT') != 1) {

			if (!$request->get('orderNumber')) {
				$RBS_Gateway->baseLogger('CALLBACK_RETURN', 'CALLBACK', $request->getQueryList(), [], 'ERROR PROCESSING CALLBACK');
				return false;
			}

			$arrOrderIds = explode("_", $request->get('orderNumber'));
			array_pop($arrOrderIds);
			$R_PAYMENT_ID = array_pop($arrOrderIds);
			$R_ORDER_ID = implode('_', $arrOrderIds);

			if (!$R_ORDER_ID) {
				return false;
			}

			$order = is_numeric($R_ORDER_ID) ? Order::load($R_ORDER_ID) : false;

			if ($order) {
				$paymentCollection = $order->getPaymentCollection();
				foreach ($paymentCollection as $payment) {
					if ($R_PAYMENT_ID == $payment->getId()) {
						LocalRedirect($APPLICATION->GetCurUri("ORDER_ID=" . $payment->getOrderId() . "&PAYMENT_ID=" . $R_PAYMENT_ID . "&CALLBACK_REDIRECT=1" . "&operation=" . $request->get('operation')));
					}
				}
			}

			$order = Order::loadByAccountNumber($R_ORDER_ID);
			if ($order) {
				$paymentCollection = $order->getPaymentCollection();
				foreach ($paymentCollection as $payment) {
					if ($R_PAYMENT_ID == $payment->getId()) {
						LocalRedirect($APPLICATION->GetCurUri("ORDER_ID=" . $payment->getOrderId() . "&PAYMENT_ID=" . $R_PAYMENT_ID . "&CALLBACK_REDIRECT=1" . "&operation=" . $request->get('operation')));
					}
				}
			}
			if (!$order) {
				$RBS_Gateway->baseLogger('CALLBACK_RETURN', 'CALLBACK', $request->getQueryList(), [], 'ERROR PROCESSING CALLBACK');
				return false;
			}
			return false;
		}


		if (!$request->get('ORDER_ID')) {
			return false;
		}

		$order = is_numeric($request->get('ORDER_ID')) ? Order::load($request->get('ORDER_ID')) : false;

		if (!$order) {
			$order = Order::loadByAccountNumber($request->get('ORDER_ID'));
		}
		if (!$order) {
			echo Loc::getMessage('RBS_MESSAGE_ERROR_BAD_ORDER');
			return false;
		}

		$paymentIds = $order->getPaymentSystemId();
		return in_array($paySystemId, $paymentIds);
	}

	private function getPropertyValueByCode($propertyCollection, $code)
	{
		$property = '';
		foreach ($propertyCollection as $property) {
			if ($property->getField('CODE') == $code)
				return $property->getValue();
		}
	}
	private function createStoredCredentialClientID($id, $email, $site_url)
	{
		return md5($id  .  $client_email  . $site_url);
	}
	/**
	 * @return array
	 */
	protected function getUrlList()
	{
		return array();
	}

	/**
	 * @return array
	 */
	public function getProps()
	{
		$data = array();

		return $data;
	}

	/**
	 * @param Payment $payment
	 * @param Request $request
	 * @return bool
	 */
	public function initPrePayment(Payment $payment = null, Request $request)
	{
		return true;
	}

	/**
	 * @param array $orderData
	 */
	public function payOrder($orderData = array())
	{
	}

	/**
	 * @param array $orderData
	 * @return bool|string
	 */
	public function BasketButtonAction($orderData = array())
	{
		return true;
	}

	/**
	 * @param array $orderData
	 */
	public function setOrderConfig($orderData = array())
	{
		if ($orderData)
			$this->prePaymentSetting = array_merge($this->prePaymentSetting, $orderData);
	}

	protected function getOrderDescription(Payment $payment, $PROP_CODE)
	{
		/** @var PaymentCollection $collection */
		$collection = $payment->getCollection();
		$order = $collection->getOrder();
		$userEmail = $order->getPropertyCollection()->getUserEmail();

		$description =  str_replace(
			array(
				'#PAYMENT_NUMBER#',
				'#ORDER_NUMBER#',
				'#PAYMENT_ID#',
				'#ORDER_ID#',
				'#USER_EMAIL#'
			),
			array(
				$payment->getField('ACCOUNT_NUMBER'),
				$order->getField('ACCOUNT_NUMBER'),
				$payment->getId(),
				$order->getId(),
				($userEmail) ? $userEmail->getValue() : ''
			),
			$this->getBusinessValue($payment, $PROP_CODE)
		);

		return $description;
	}

	private static function encode(array $data)
	{
		return Main\Web\Json::encode($data, JSON_UNESCAPED_UNICODE);
	}

	protected function printResultText($payment, $successPayment)
	{
		global $APPLICATION;
		echo '<div class="sberbank-center" style="width: 100%;display: flex;align-items: center;align-content: center;justify-content: center;height: 100%;position: fixed;"><div style="display: block;background:#fff;padding: 10px 10px; margin-left:-10px;border-radius: 6px;max-width: 400px; border: 1px solid #e7e7e7;">';
		echo '<div class="sberbank-result-message" style="margin:5px; text-align:center;padding:10px 20px; 0"><span style=" font-family: arial;font-size: 16px;">';

		if ($successPayment) {
			$APPLICATION->SetTitle(Loc::getMessage('SBERBANK_PAYMENT_MESSAGE_THANKS'));
			echo Loc::getMessage('SBERBANK_PAYMENT_MESSAGE_THANKS_DESCRIPTION') . $this->getBusinessValue($payment, 'SBERBANK_ORDER_NUMBER');
		} else {
			$APPLICATION->SetTitle(Loc::getMessage('SBERBANK_PAYMENT_MESSAGE_ERROR'));
			echo Loc::getMessage('SBERBANK_PAYMENT_MESSAGE_ERROR') . ' #' . $this->getBusinessValue($payment, 'SBERBANK_ORDER_NUMBER');
		}
		echo '<div style=" display: block; margin:10px 10px 0;"><a style="font-family: arial;font-size: 16px;color: #21a038;" href="/">' . Loc::getMessage('SBERBANK_RETURN_LINK') . '</a></div>';
		echo "</span></div>";
		echo "</div></div>";
	}

	private function cancelOrder($orderId)
	{
		$order = Order::load($orderId);
		$order->setField("CANCELED", "Y");
		$order->setField("REASON_CANCELED", Loc::getMessage('SBERBANK_CANCEL_ORDER_MESSAGE'));
		$order->save();
	}


	public function isRefundableExtended()
	{
	}
	public function confirm(Payment $payment)
	{
	}
	public function cancel(Payment $payment)
	{
	}
	public function refund(Payment $payment, $refundableSum)
	{
	}
	public function sendResponse(PaySystem\ServiceResult $result, Request $request)
	{
	}
}

Youez - 2016 - github.com/yon3zu
LinuXploit