function get_pay_button($bill_id, $bill_sum, $bill_payment_sum)
 {
     if ($bill_payment_sum == '') {
         $payment_amount = $bill_sum;
     } else {
         $payment_amount = $bill_payment_sum;
     }
     $user_id = (int) $this->getSessionUserId();
     $language = Multilanguage::get_current_language();
     require_once SITEBILL_DOCUMENT_ROOT . '/apps/begateway/lib/begateway-api-php/lib/beGateway.php';
     require_once SITEBILL_DOCUMENT_ROOT . '/apps/system/lib/system/user/user.php';
     require_once SITEBILL_DOCUMENT_ROOT . '/apps/begateway/classes/currency.php';
     $currency = new begateway_currency();
     $order_currency = $currency->getCurrencyCode(CURRENT_CURRENCY);
     if ($order_currency == 'RUR') {
         $order_currency = 'RUB';
     }
     $user = new User_Object();
     \beGateway\Settings::$shopId = $this->site_id;
     \beGateway\Settings::$shopKey = $this->site_key;
     \beGateway\Settings::$gatewayBase = 'https://' . $this->domain_gateway;
     \beGateway\Settings::$checkoutBase = 'https://' . $this->domain_checkout;
     #\beGateway\Logger::getInstance()->setLogLevel(\beGateway\Logger::DEBUG);
     $transaction = new \beGateway\GetPaymentToken();
     $transaction->money->setCurrency($order_currency);
     $transaction->money->setAmount($payment_amount);
     $transaction->setDescription(sprintf(Multilanguage::_('ORDER_DESCRIPTION', 'begateway'), $bill_id));
     $transaction->setTrackingId($user_id . '|' . $bill_id);
     $transaction->setLanguage($language);
     $sitebill_host = $this->_protocol_scheme() . '://' . $_SERVER['HTTP_HOST'] . SITEBILL_MAIN_URL;
     $notification_url = $sitebill_host . '/apps/begateway/listener.php';
     $notification_url = str_replace('carts.local', 'webhook.begateway.com:8443', $notification_url);
     $transaction->setNotificationUrl($notification_url);
     $transaction->setSuccessUrl($sitebill_host . '/account/balance');
     $transaction->setDeclineUrl($sitebill_host . '/account/balance/?do=add_bill');
     $transaction->setFailUrl($sitebill_host . '/account/balance/?do=add_bill');
     $transaction->setCancelUrl($sitebill_host . '/account/balance');
     $transaction->customer->setEmail($user->getEmail($user_id));
     $transaction->setAddressHidden();
     $response = $transaction->submit();
     if ($response->isSuccess()) {
         $payment_params = array();
         $payment_params['token'] = $response->getToken();
         $payment_params['url'] = \beGateway\Settings::$checkoutBase . '/checkout';
         $this->template->assign('payment_text', sprintf(Multilanguage::_('YOU_HAVE_ORDER', 'begateway'), (string) $payment_amount, $this->getConfigValue('ue_name')));
         $this->template->assign('payment_button', Multilanguage::_('PAYMENT_BUTTON', 'begateway'));
         $this->template->assign('payment_description', $this->description[$language]);
         $this->template->assign('payment_params', $payment_params);
     } else {
         $this->template->assign('payment_error', Multilanguage::_('PAYMENT_ERROR', 'system') . '<br>' . $response->getMessage());
     }
     return $this->template->fetch(SITEBILL_DOCUMENT_ROOT . '/apps/begateway/site/template/pay_form.tpl');
 }
if ($zip) {
    $transaction->customer->setZip($zip);
}
if ($email) {
    $transaction->customer->setEmail($email);
}
if ($phone) {
    $transaction->customer->setPhone($phone);
}
if ($state) {
    $transaction->customer->setState($state);
}
if ($country) {
    $transaction->customer->setCountry($country);
}
$transaction->setAddressHidden();
$response = $transaction->submit();
if (!$response->isSuccess()) {
    ShowMessage(Loc::getMessage("DEVTM_BEGATEWAY_GET_TOKEN_ERROR") . $response->getMessage());
    die;
}
$_SESSION["token"] = md5($USER->GetID() . ":" . $response->getToken());
$form_type = \Bitrix\Main\Config\Option::get($module_id, "form_type");
if ($form_type == "inline" || $form_type == "overlay") {
    $GLOBALS["APPLICATION"]->AddHeadScript("/bitrix/php_interface/include/sale_payment/devtm.begateway/begateway.min.js");
    $css = \Bitrix\Main\Config\Option::get($module_id, "css_form");
    $id = "begateway-order-" . $order_id;
    if ($form_type == "overlay") {
        echo "<button id=\"{$id}\" >" . Loc::getMessage("DEVTM_BEGATEWAY_BUY_BUTTON") . "</button>";
    } else {
        echo "<div id=\"{$id}\"></div>";
    public function getNotification()
    {
        $sum = $this->getSumWithCoeff();
        $oSite_Alias = $this->_shopOrder->Shop->Site->getCurrentAlias();
        $site_alias = !is_null($oSite_Alias) ? $oSite_Alias->name : '';
        $shop_path = $this->_shopOrder->Shop->Structure->getPath();
        $shopUrl = 'http://' . $site_alias . $shop_path;
        $handlerUrl = $shopUrl . "cart/?order_id={$this->_shopOrder->id}";
        $successUrl = $handlerUrl . "&payment=success";
        $failUrl = $handlerUrl . "&payment=fail";
        $cancelUrl = $handlerUrl;
        /* в режиме разработки переопределить домен для доставки нотификации о платеже */
        $handlerUrl = str_replace('hostcms.local', 'hostcms.webhook.begateway.com:8443', $handlerUrl);
        $oShop_Currency = Core_Entity::factory('Shop_Currency')->find($this->_begateway_currency_id);
        if (!is_null($oShop_Currency->id)) {
            $serviceName = 'Оплата счета N ' . $this->_shopOrder->id;
            $this->_setupLogger();
            $transaction = new \beGateway\GetPaymentToken();
            /* конвертировать RUR код в RUB */
            $currency = $oShop_Currency->code;
            $currency = $currency == 'RUR' ? 'RUB' : $currency;
            $transaction->money->setCurrency($currency);
            $transaction->money->setAmount($sum);
            $transaction->setDescription($serviceName);
            $transaction->setTrackingId($this->_shopOrder->id);
            $transaction->setLanguage('ru');
            $transaction->setNotificationUrl($handlerUrl . '&webhook=begateway');
            $transaction->setSuccessUrl($successUrl);
            $transaction->setDeclineUrl($failUrl);
            $transaction->setFailUrl($cancelUrl);
            $transaction->setCancelUrl($shopUrl);
            foreach ($this->_payment_methods as $pm) {
                $klass = $this->_camelize($pm);
                $settings = NULL;
                if (isset($this->_payment_methods_settings[$pm])) {
                    $settings = $this->_payment_methods_settings[$pm];
                }
                if ($pm == 'erip') {
                    $settings['account_number'] = (string) $this->_shopOrder->id;
                    $settings['order_id'] = (int) $this->_shopOrder->id;
                    $settings['service_info'][0] = sprintf($settings['service_info'][0], $this->_shopOrder->id);
                }
                $klass = "\\beGateway\\PaymentMethod\\" . $klass;
                $transaction->addPaymentMethod(new $klass($settings));
            }
            if ($this->_shopOrder->email) {
                $transaction->customer->setEmail($this->_shopOrder->email);
            }
            if ($this->_hideAddress) {
                $transaction->setAddressHidden();
            }
            $response = $transaction->submit();
            if ($response->isSuccess()) {
                ?>
        <h1>Оплата заказа</h1>
        <p>Сумма к оплате составляет <strong><?php 
                echo $sum;
                ?>
 <?php 
                echo $oShop_Currency->name;
                ?>
</strong></p>

        <p>Для оплаты нажмите кнопку "Оплатить".</p>

        <p style="color: rgb(112, 112, 112);">
          Внимание! Нажимая &laquo;Оплатить&raquo; Вы подтверждаете передачу контактных данных на сервер платежной системы для оплаты.
        </p>

        <form action="<?php 
                echo $response->getRedirectUrlScriptName();
                ?>
" name="pay" method="post">
          <input type="hidden" name="token" value="<?php 
                echo $response->getToken();
                ?>
">
          <input type="submit" name="button" value="Оплатить">
        </form>
        <?php 
            } else {
                ?>
        <h1>Ошибка создания идентификатора платежа</h1>
        <p>Вернитесь назад и попробуйте еще раз</p>
        <?php 
                if ($response->getMessage()) {
                    echo "<p>Причина: " . $response->getMessage();
                }
                ?>
        <?php 
            }
        } else {
            ?>
<h1>Не найдена валюта с идентификатором <?php 
            $this->_begateway_currency_id;
            ?>
!</h1><?php 
        }
    }
   function generate_begateway_form($order_id)
   {
       //creates a self-submitting form to pass the user through to the beGateway server
       global $woocommerce;
       $order = new WC_order($order_id);
       if ('yes' == $this->debug) {
           $this->log->add('begateway', 'Generating payment form for order ' . $order->get_order_number());
       }
       // Order number & Cart Contents for description field - may change
       $item_loop = 0;
       //grab the langauge
       $lang = explode('-', get_bloginfo('language'));
       $lang = $lang[0];
       if (in_array($lang, \beGateway\Language::getSupportedLanguages())) {
           $language = $lang;
       } else {
           $language = 'en';
       }
       $token = new \beGateway\GetPaymentToken();
       if ($this->transaction_type == 'authorization') {
           $token->setAuthorizationTransactionType();
       }
       $token->money->setCurrency(get_woocommerce_currency());
       $token->money->setAmount($order->order_total);
       $token->setDescription(__('Order', 'woocommerce') . ' # ' . $order->get_order_number());
       $token->setTrackingId(ltrim($order->get_order_number(), '#'));
       $token->customer->setFirstName($order->billing_first_name);
       $token->customer->setLastName($order->billing_last_name);
       $token->customer->setCountry($order->billing_country);
       $token->customer->setCity($order->billing_city);
       $token->customer->setPhone($order->billing_phone);
       $token->customer->setZip($order->billing_postcode);
       $token->customer->setAddress($order->billing_address_1 . $order->billing_address_2);
       $token->customer->setEmail($order->billing_email);
       if (in_array($order->billing_country, array('US', 'CA'))) {
           $token->customer->setState($order->billing_state);
       }
       $token->setSuccessUrl(esc_url_raw($this->get_return_url($order)));
       $token->setDeclineUrl(esc_url_raw($order->get_cancel_order_url_raw()));
       $token->setFailUrl(esc_url_raw($order->get_cancel_order_url_raw()));
       $token->setCancelUrl(esc_url_raw($order->get_cancel_order_url_raw()));
       $token->setNotificationUrl($this->notify_url);
       $token->setLanguage($language);
       $token->setAddressHidden();
       if ('yes' == $this->debug) {
           $this->log->add('begateway', 'Requesting token for order ' . $order->get_order_number());
       }
       $response = $token->submit();
       if (!$response->isSuccess()) {
           if ('yes' == $this->debug) {
               $this->log->add('begateway', 'Unable to get payment token on order: ' . $order_id . 'Reason: ' . $response->getMessage());
           }
           $woocommerce->add_error(__('Unable to contact the payment server at this time. Please try later.'));
           $woocommerce->add_error($response->getMessage());
           exit;
       }
       //now look to the result array for the token
       if ($response->getToken()) {
           $payment_url = $response->getRedirectUrlScriptName();
           update_post_meta(ltrim($order->get_order_number(), '#'), '_Token', $token);
           if ('yes' == $this->debug) {
               $this->log->add('begateway', 'Token received, forwarding customer to: ' . $payment_url);
           }
       } else {
           $woocommerce->add_error(__('Payment error: ') . $response->getMessage());
           if ('yes' == $this->debug) {
               $this->log->add('begateway', 'Payment error order ' . $order_id . '  ' . $error_to_show);
           }
           exit('Sorry - there was an error contacting the bank server, please try later');
       }
       wc_enqueue_js('
   jQuery("body").block({
     message: "' . __('Thank you for your order. We are now redirecting you to make the payment.', 'woocommerce-begateway') . '",
       overlayCSS: {
         background: "#fff",
         opacity: 0.6
       },
       css: {
         padding:        20,
         textAlign:      "center",
         color:          "#555",
         border:         "3px solid #aaa",
         backgroundColor:"#fff",
         cursor:         "wait",
         lineHeight:		"32px"
       }
   });
   jQuery("#submit_begateway_payment_form").click();
 ');
       return '<form action="' . $payment_url . '" method="post" id="begateway_payment_form">
   <input type="hidden" name="token" value="' . $response->getToken() . '">
   <input type="submit" class="button-alt" id="submit_begateway_payment_form" value="' . __('Make payment', 'woocommerce-begateway') . '" /> <a class="button cancel" href="' . $order->get_cancel_order_url() . '">' . __('Cancel order &amp; restore cart', 'woothemes') . '</a>
   </form>';
   }
 public function hookPayment($params)
 {
     global $smarty, $cookie;
     if (!$this->active) {
         return;
     }
     $err_msg = '';
     $customer = new Customer((int) $params['cart']->id_customer);
     $address = new Address(intval($params['cart']->id_address_invoice));
     $country = Country::getIsoById((int) $address->id_country);
     $lang_iso_code = strtolower(Language::getIsoById((int) $cookie->id_lang));
     $sp_lang = \beGateway\Language::getSupportedLanguages();
     if (!in_array($lang_iso_code, $sp_lang)) {
         $lang_iso_code = 'en';
     }
     $shop_ptype = trim(Configuration::get('BEGATEWAY_SHOP_PAYTYPE'));
     $currency = new Currency((int) $params['cart']->id_currency);
     $currency_code = trim($currency->iso_code);
     $amount = $params['cart']->getOrderTotal(true, 3);
     $return_base_url = (Configuration::get('PS_SSL_ENABLED') ? 'https' : 'http') . '://' . $_SERVER['HTTP_HOST'] . __PS_BASE_URI__ . 'modules/' . $this->name . '/validation.php?';
     $callbackurl = $return_base_url . 'action=callback';
     $callbackurl = str_replace('carts.local', 'webhook.begateway.com:8443', $callbackurl);
     $cancelurl = (Configuration::get('PS_SSL_ENABLED') ? 'https' : 'http') . '://' . $_SERVER['HTTP_HOST'] . __PS_BASE_URI__;
     $successurl = $return_base_url . 'action=success&id_cart=' . (int) $params['cart']->id . '&id_module=' . (int) $this->id . '&key=' . $customer->secure_key;
     $failurl = $return_base_url . 'action=fail';
     $state_val = NULL;
     if (in_array($country, array('US', 'CA'))) {
         $state = new State((int) $address->id_state);
         if (Validate::isLoadedObject($state)) {
             $state_val = $state->iso_code;
         } else {
             $state_val = 'NA';
         }
     }
     $phone = $address->phone ? $address->phone : $address->phone_mobile;
     $transaction = new \beGateway\GetPaymentToken();
     if ($shop_ptype == 'authorization') {
         $transaction->setAuthorizationTransactionType();
     } else {
         $transaction->setPaymentTransactionType();
     }
     $transaction->money->setCurrency($currency_code);
     $transaction->money->setAmount($amount);
     $transaction->setDescription($this->l('Order No. ') . $params['cart']->id);
     $transaction->setTrackingId($params['cart']->id);
     $transaction->setLanguage($lang_iso_code);
     $transaction->setNotificationUrl($callbackurl);
     $transaction->setSuccessUrl($successurl);
     $transaction->setDeclineUrl($failurl);
     $transaction->setFailUrl($failurl);
     $transaction->setCancelUrl($cancelurl);
     $transaction->customer->setFirstName($address->firstname);
     $transaction->customer->setLastName($address->lastname);
     $transaction->customer->setCountry($country);
     $transaction->customer->setAddress($address->address1 . ' ' . $address->address2);
     $transaction->customer->setCity($address->city);
     $transaction->customer->setZip($address->postcode);
     $transaction->customer->setEmail($cookie->email);
     $transaction->customer->setPhone($phone);
     $transaction->customer->setState($state_val);
     $transaction->setAddressHidden();
     $paymentUrl = '';
     try {
         $response = $transaction->submit();
         if ($response->isError()) {
             $err_msg .= $response->getMessage();
         }
         if ($response->isSuccess()) {
             $paymentUrl = $response->getRedirectUrl();
         }
     } catch (Exception $e) {
         $err_msg .= $e->getMessage();
     }
     $smarty->assign(array('paymentUrl' => $paymentUrl, 'err_msg' => $err_msg, 'this_path' => $this->_path));
     $template = 'beGateway.tpl';
     if (_PS_VERSION_ < 1.6) {
         $template = 'beGateway_1_5.tpl';
     }
     return $this->display(__FILE__, $template);
 }
    function showEndForm($pmconfigs, $order)
    {
        $jshopConfig = JSFactory::getConfig();
        $item_name = sprintf(_JSHOP_PAYMENT_NUMBER, $order->order_number);
        $uri = JURI::getInstance();
        $notify_url = JURI::root() . "index.php?option=com_jshopping&controller=checkout&task=step7&act=notify&js_paymentclass=pm_begateway&no_lang=1";
        $notify_url = str_replace('carts.local', 'webhook.begateway.com:8443', $notify_url);
        $return = JURI::root() . "index.php?option=com_jshopping&controller=checkout&task=step7&act=return&js_paymentclass=pm_begateway";
        $cancel_return = JURI::root() . "index.php?option=com_jshopping&controller=checkout&task=step7&act=cancel&js_paymentclass=pm_begateway";
        $cancel_return = JURI::root() . "index.php?option=com_jshopping&controller=checkout&task=step5&act=cancel&js_paymentclass=pm_begateway";
        $_country = JTable::getInstance('country', 'jshop');
        $_country->load($order->d_country);
        $country = $_country->country_code_2;
        $language = explode('-', JFactory::getLanguage()->getTag());
        $language = $language[0];
        $this->_init_pm($pmconfigs);
        $token = new \beGateway\GetPaymentToken();
        $token->money->setAmount($order->order_total);
        $token->money->setCurrency($order->currency_code_iso);
        $token->setTrackingId("{$order->order_id}|{$order->order_total}|{$order->currency_code_iso}");
        $token->setDescription($item_name);
        $token->setLanguage($language);
        $token->setNotificationUrl($notify_url);
        $token->setSuccessUrl($return);
        $token->setDeclineUrl($cancel_return);
        $token->setFailUrl($cancel_return);
        $token->setCancelUrl($cancel_return);
        $token->customer->setFirstName($order->d_f_name);
        $token->customer->setLastName($order->d_l_name);
        $token->customer->setCountry($country);
        $token->customer->setAddress($order->d_street);
        $token->customer->setCity($order->d_city);
        $token->customer->setZip($order->d_zip);
        if (strlen($order->email) > 0) {
            $token->customer->setEmail($order->email);
        }
        if (in_array($country, array('US', 'CA'))) {
            $token->customer->setState($order->d_state);
        }
        $token->setAddressHidden();
        $response = $token->submit();
        ?>
        <html>
        <head>
            <meta http-equiv="content-type" content="text/html; charset=utf-8" />
        </head>
        <body>
<?php 
        if ($response->isSuccess()) {
            ?>
        <form id="paymentform" action="<?php 
            echo $response->getRedirectUrlScriptName();
            ?>
" name = "paymentform" method = "post">
          <input type='hidden' name='token' value='<?php 
            print $response->getToken();
            ?>
'>
        </form>
        <?php 
            print _JSHOP_REDIRECT_TO_PAYMENT_PAGE;
            ?>
        <br>
        <script type="text/javascript">document.getElementById('paymentform').submit();</script>
<?php 
        } else {
            print _JSHOP_ERROR_PAYMENT . ': ' . $response->getMessage();
        }
        ?>
        </body>
        </html>
<?php 
        die;
    }