first commit

This commit is contained in:
2026-03-05 13:07:40 +01:00
commit 64ba0721ee
25709 changed files with 4691006 additions and 0 deletions

View File

@@ -0,0 +1,41 @@
<?php
/**
* Created by tpay.com.
* Date: 29.01.2018
* Time: 11:57
*/
class AddFee
{
const WOOCOMMERCE = 'woocommerce';
public function addFeeTpay($gatewayId, $fee, $feeAmount)
{
if ((WC()->session->chosen_payment_method) == $gatewayId) {
global $woocommerce;
switch ($fee) {
case 1:
$woocommerce->cart->add_fee(
__('Opłata za płatność online', static::WOOCOMMERCE),
$feeAmount,
true,
'standard'
);
break;
case 2:
$kwota = $woocommerce->cart->cart_contents_total + $woocommerce->cart->shipping_total;
$fee = $kwota * $feeAmount / 100;
$woocommerce->cart->add_fee(
__('Opłata za płatność online', static::WOOCOMMERCE),
$fee,
true,
'standard'
);
break;
default:
break;
}
}
}
}

View File

@@ -0,0 +1,219 @@
<?php
class SettingsTpay
{
const VISIBILITY_VISIBLE = 'visibility: visible';
const VISIBILITY_HIDDEN = 'visibility: hidden';
const TITLE = 'title';
const TYPE = 'type';
const DEFAULT_SETTING = 'default';
const DESCRIPTION = 'description';
const WOOCOMMERCE = 'woocommerce';
const SELECT = 'select';
const OPTIONS = 'options';
const DESC_TIP = 'desc_tip';
public function getSettings($charge, $list, $shippingSettings = array())
{
$ukryjD = static::VISIBILITY_VISIBLE;
$ukryjK = static::VISIBILITY_VISIBLE;
if ($charge == '0') {
$ukryjD = static::VISIBILITY_HIDDEN;
}
if ($list == '1') {
$ukryjK = static::VISIBILITY_HIDDEN;
}
return array(
'enabled' => array(
static::TITLE => __('Włącz/Wyłącz', static::WOOCOMMERCE),
static::TYPE => 'checkbox',
'label' => __('Włącz metodę płatności przez tpay.com.', static::WOOCOMMERCE),
static::DEFAULT_SETTING => 'yes',
static::DESCRIPTION => sprintf(__(' <a href="%s" TARGET="_blank">Zarejestruj konto w systemie
tpay.com</a>.', static::WOOCOMMERCE), 'https://secure.tpay.com/panel/rejestracja.html'),
),
'documentation' => array(
static::TITLE => __('Instrukcja konfiguracji', static::WOOCOMMERCE),
static::TYPE => static::TITLE,
static::DESCRIPTION => sprintf(__(' <a href="%s" TARGET="_blank">
Link do instrukcji konfiguracji modułu</a>.', static::WOOCOMMERCE),
'https://support.tpay.com/pl/developer/addons/woocommerce/woocommerce-instrukcja'),
),
static::TITLE => array(
static::TITLE => __('Nazwa', static::WOOCOMMERCE),
static::TYPE => 'text',
static::DEFAULT_SETTING => __('Tpay', static::WOOCOMMERCE),
static::DESC_TIP => true,
),
static::DESCRIPTION => array(
static::TITLE => __('Opis', static::WOOCOMMERCE),
static::TYPE => 'textarea',
static::DESCRIPTION => __(
'Ustawia opis bramki, który widzi użytkownik przy tworzeniu zamówienia.',
static::WOOCOMMERCE
),
static::DEFAULT_SETTING => __(
'System płatności tpay.com to bezpieczny i szybki sposób płatności, który został wybrany przez Odbiorcę płatności w celu przyjęcia od Ciebie zapłaty.',
static::WOOCOMMERCE
),
),
'opis' => array(
static::TITLE => __('Tytuł transakcji', static::WOOCOMMERCE),
static::TYPE => 'text',
static::DESCRIPTION => __('Pozwala zmodyfikować opis transakcji, do którego zostanie autoamtycznie
dodane "Zamówienie nr (order_id)".'
, static::WOOCOMMERCE),
static::DEFAULT_SETTING => __(''
, static::WOOCOMMERCE),
),
'seller_id' => array(
static::TITLE => __('ID sprzedawcy', static::WOOCOMMERCE),
static::TYPE => 'text',
static::DESCRIPTION => __('Twoje ID sprzedawcy w systemie tpay.com.
Liczba co najmniej czterocyfrowa (może być pięciocyfowa), np. 12345', static::WOOCOMMERCE),
static::DEFAULT_SETTING => __('0', static::WOOCOMMERCE),
static::DESC_TIP => true,
),
'security_code' => array(
static::TITLE => __('Kod bezpieczeństwa', static::WOOCOMMERCE),
static::TYPE => 'text',
static::DESCRIPTION => __('Kod bezpieczeństwa Twojego konta na tpay.com.', static::WOOCOMMERCE),
static::DEFAULT_SETTING => __('0', static::WOOCOMMERCE),
static::DESC_TIP => true,
),
'blik_on' => array(
static::TITLE => __('Włącz płatności blikiem na stronie sklepu', static::WOOCOMMERCE),
static::TYPE => static::SELECT,
static::DEFAULT_SETTING => '0',
static::OPTIONS => array(
'0' => __('NIE', static::WOOCOMMERCE),
'1' => __('TAK', static::WOOCOMMERCE),
),
),
'api_key' => array(
static::TITLE => __('Klucz API', static::WOOCOMMERCE),
static::TYPE => 'text',
static::DESCRIPTION => __('Klucz API wygenerowany w panelu odbiorcy płatności tpay.com.'
, static::WOOCOMMERCE),
static::DEFAULT_SETTING => __('0', static::WOOCOMMERCE),
static::DESC_TIP => true,
),
'api_pass' => array(
static::TITLE => __('Hasło API', static::WOOCOMMERCE),
static::TYPE => 'text',
static::DESCRIPTION => __('Hasło do klucza API', static::WOOCOMMERCE),
static::DEFAULT_SETTING => __('0', static::WOOCOMMERCE),
static::DESC_TIP => true,
),
'doplata' => array(
static::TITLE => __('Dopłata doliczana za korzystanie z tej metody płatności', static::WOOCOMMERCE),
static::TYPE => static::SELECT,
static::DEFAULT_SETTING => '0',
static::OPTIONS => array(
'0' => __('NIE', static::WOOCOMMERCE),
'1' => __('PLN', static::WOOCOMMERCE),
'2' => __('%', static::WOOCOMMERCE),
),
),
'kwota_doplaty' => array(
static::TITLE => __('Kwota dopłaty', static::WOOCOMMERCE),
static::TYPE => "text",
'css' => $ukryjD,
static::DESCRIPTION => __('Kwota jaka zostanie doliczona do zamówienia.
Jako separator liczb należy wykorzystać kropkę', static::WOOCOMMERCE),
static::DEFAULT_SETTING => __('0', static::WOOCOMMERCE),
static::DESC_TIP => true,
),
'bank_list' => array(
static::TITLE => __('Włącz wybór banku na stronie sklepu', static::WOOCOMMERCE),
static::TYPE => static::SELECT,
static::DEFAULT_SETTING => '0',
static::OPTIONS => array(
'0' => __('TAK', static::WOOCOMMERCE),
'1' => __('NIE', static::WOOCOMMERCE),
),
),
'bank_view' => array(
static::TITLE => __('Widok listy kanałów', static::WOOCOMMERCE),
static::TYPE => static::SELECT,
static::DEFAULT_SETTING => '0',
'css' => $ukryjK,
static::OPTIONS => array(
'0' => __('Kafelki', static::WOOCOMMERCE),
'1' => __('Lista', static::WOOCOMMERCE),
),
),
'shipping_methods' => array(
'title' => __('Włącz dla wysyłki - opcja niedostępna w niektórych instalacjach Woocommerce',
'woocommerce'),
'type' => 'multiselect',
'class' => 'wc-enhanced-select',
'css' => 'width: 400px;',
'default' => '',
'description' => __('Wybierz metody wysyłki dla których chcesz włączyć płatności. Jeśli dla wszystkich, pozostaw to pole puste.',
'woocommerce'),
'options' => $shippingSettings,
'desc_tip' => true,
'custom_attributes' => array(
'data-placeholder' => __('Wybierz metody wysyłki', 'woocommerce'),
),
),
'auto_finish_order' => array(
static::TITLE => __('Automatycznie oznaczaj zamówienie jako zrealizowane', static::WOOCOMMERCE),
static::TYPE => static::SELECT,
static::DEFAULT_SETTING => 0,
static::OPTIONS => array(
0 => __('NIE', static::WOOCOMMERCE),
1 => __('TAK', static::WOOCOMMERCE),
),
),
'order_pending_status' => array(
static::TITLE => __('Status po złożeniu zamówienia', static::WOOCOMMERCE),
static::TYPE => static::SELECT,
static::DEFAULT_SETTING => 0,
static::OPTIONS => array(
0 => __('Oczekujące', static::WOOCOMMERCE),
1 => __('Wstrzymane', static::WOOCOMMERCE),
),
),
'proxy_server' => array(
static::TITLE => __('Mój serwer korzysta z komunikacji przez proxy', static::WOOCOMMERCE),
static::TYPE => static::SELECT,
static::DEFAULT_SETTING => 0,
static::OPTIONS => array(
0 => __('NIE', static::WOOCOMMERCE),
1 => __('TAK', static::WOOCOMMERCE),
),
),
'enable_IP_validation' => array(
static::TITLE => __('Weryfikuj adres serwera powiadomień (zalecane)', static::WOOCOMMERCE),
static::TYPE => static::SELECT,
static::DEFAULT_SETTING => 1,
static::OPTIONS => array(
1 => __('TAK', static::WOOCOMMERCE),
0 => __('NIE', static::WOOCOMMERCE),
),
),
'online_methods_only' => array(
static::TITLE => __('Pokaż tylko metody płatności księgujące online', static::WOOCOMMERCE),
static::TYPE => static::SELECT,
static::DEFAULT_SETTING => 0,
static::OPTIONS => array(
0 => __('NIE', static::WOOCOMMERCE),
1 => __('TAK', static::WOOCOMMERCE),
),
),
);
}
}

View File

@@ -0,0 +1,230 @@
<?php
class SettingsTpayCards
{
const TITLE = 'title';
const TYPE = 'type';
const DEFAULT_SETTING = 'default';
const DESCRIPTION = 'description';
const WOOCOMMERCE = 'woocommerce';
const GATEWAY_NAME = 'WC_Gateway_Tpay_Cards';
const SELECT = 'select';
const OPTIONS = 'options';
const DESC_TIP = 'desc_tip';
const HTTP = 'http:';
const HTTPS = 'https:';
public function getSettings($shippingSettings = array())
{
if ((isset($_SERVER['HTTP_X_FORWARDED_PROTO']) && $_SERVER['HTTP_X_FORWARDED_PROTO'] === 'https')
|| (is_ssl())
) {
$domain = str_replace(static::HTTP, static::HTTPS, home_url('/'));
$notify_link = add_query_arg('wc-api', static::GATEWAY_NAME, $domain);
} else {
$domain = str_replace(static::HTTPS, static::HTTP, home_url('/'));
$notify_link = add_query_arg('wc-api', static::GATEWAY_NAME, $domain);
}
$options = array(
'enabled' => array(
static::TITLE => __('Włącz/Wyłącz', static::WOOCOMMERCE),
static::TYPE => 'checkbox',
'label' => __('Włącz metodę płatności kartami przez Tpay.', static::WOOCOMMERCE),
static::DEFAULT_SETTING => 'no',
static::DESCRIPTION => sprintf(__(' <a href="%s" TARGET="_blank">Zarejestruj konto w systemie
tpay.com</a>.', static::WOOCOMMERCE), 'https://secure.tpay.com/panel/rejestracja.html'),
),
'doc_link' => array(
static::TITLE => __('Instrukcja', static::WOOCOMMERCE),
static::TYPE => static::TITLE,
static::DESCRIPTION => sprintf(__(' <a href="%s" TARGET="_blank">Instrukcja konfiguracji
</a>', static::WOOCOMMERCE), 'https://support.tpay.com/pl/developer/addons/woocommerce/woocommerce-instrukcja'),
),
static::TITLE => array(
static::TITLE => __('Nazwa metody płatności', static::WOOCOMMERCE),
static::TYPE => 'text',
static::DEFAULT_SETTING => __('Tpay credit cards', static::WOOCOMMERCE),
static::DESC_TIP => true,
),
'proxy_server' => array(
static::TITLE => __('Mój serwer korzysta z komunikacji przez proxy', static::WOOCOMMERCE),
static::TYPE => static::SELECT,
static::DEFAULT_SETTING => 0,
static::OPTIONS => array(
0 => __('NIE', static::WOOCOMMERCE),
1 => __('TAK', static::WOOCOMMERCE),
),
),
'shipping_methods' => array(
'title' => __('Włącz dla wysyłki - opcja niedostępna w niektórych instalacjach Woocommerce', static::WOOCOMMERCE),
'type' => 'multiselect',
'class' => 'wc-enhanced-select',
'css' => 'width: 400px;',
'default' => '',
'description' => __('Wybierz metody wysyłki dla których chcesz włączyć płatności. Jeśli dla wszystkich, pozostaw to pole puste.', static::WOOCOMMERCE),
'options' => $shippingSettings,
'desc_tip' => true,
'custom_attributes' => array(
'data-placeholder' => __('Wybierz metody wysyłki', static::WOOCOMMERCE),
),
),
'resp_link' => array(
static::TITLE => __('Link powiadomień do panelu odbiorcy płatności',
static::WOOCOMMERCE),
static::TYPE => static::TITLE,
static::DESCRIPTION => add_query_arg(array('type' => 'sale'), $notify_link) .
'<br/>Zwróć uwagę czy Twoja strona korzysta z protokołu https. Jeśli link został błędnie rozpoznany jako http, zamień protokół http na https przed wprowadzeniem ustawień w panelu odbiorcy płatności',
),
'debugMode' => array(
static::TITLE => __('Tryb debugowania', static::WOOCOMMERCE),
static::TYPE => 'checkbox',
static::DEFAULT_SETTING => 'no',
static::DESCRIPTION => __('Wyłącz w trybie produkcyjnym.'
),
),
'auto_finish_order' => array(
static::TITLE => __('Automatycznie oznaczaj zamówienie jako zrealizowane', static::WOOCOMMERCE),
static::TYPE => static::SELECT,
static::DEFAULT_SETTING => 0,
static::OPTIONS => array(
0 => __('NIE', static::WOOCOMMERCE),
1 => __('TAK', static::WOOCOMMERCE),
),
),
'midNumber' => array(
static::TITLE => __("Numer MID'u", static::WOOCOMMERCE),
static::TYPE => static::SELECT,
static::DEFAULT_SETTING => '0',
static::OPTIONS => array(),
),
);
for ($i = 1; $i < 11; $i++) {
$array = array(
'midOn' . $i => array(
static::TITLE => __('Włącz MID', static::WOOCOMMERCE),
static::TYPE => 'checkbox',
'label' => __("Używaj tego MID'u", static::WOOCOMMERCE),
static::DEFAULT_SETTING => 'no',
),
'midType' . $i => array(
static::TITLE => __('Konto wielowalutowe', static::WOOCOMMERCE),
static::TYPE => static::SELECT,
static::DEFAULT_SETTING => '0',
static::OPTIONS => array(
'0' => __('NIE - tylko PLN', static::WOOCOMMERCE),
'1' => __('TAK - wszystkie obsługiwane waluty', static::WOOCOMMERCE),
),
),
'midDomain' . $i => array(
static::TITLE => __("Domena przypisana do MID'u", static::WOOCOMMERCE),
static::TYPE => 'text',
static::DEFAULT_SETTING => $domain,
),
'midCurrency' . $i => array(
static::TITLE => __("Waluty, dla których ma być używany MID oddzielone przecinkiem
np. EUR,USD (puste jeśli wszystkie)"
, static::WOOCOMMERCE),
static::TYPE => 'text',
static::DEFAULT_SETTING => '',
),
static::DESCRIPTION . $i => array(
static::TITLE => __('Opis', static::WOOCOMMERCE),
static::TYPE => 'textarea',
static::DESCRIPTION => __('Ustawia opis bramki, który widzi użytkownik
przy tworzeniu zamówienia.'
, static::WOOCOMMERCE),
static::DEFAULT_SETTING => __('System płatności tpay.com to bezpieczny i szybki sposób płatności, który został wybrany przez Odbiorcę płatności w celu przyjęcia od Ciebie zapłaty.',
static::WOOCOMMERCE
)
),
'opis' . $i => array(
static::TITLE => __('Tytuł transakcji', static::WOOCOMMERCE),
static::TYPE => 'text',
static::DESCRIPTION => __('Ustawia opis transakcji, do którego zostanie autoamtycznie
dodane "Zamówienie nr (ID)".'
, static::WOOCOMMERCE),
static::DEFAULT_SETTING => __(''
, static::WOOCOMMERCE)
),
'cardApiKey' . $i => array(
static::TITLE => __('Klucz API', static::WOOCOMMERCE),
static::TYPE => 'text',
static::DESCRIPTION => __('Klucz API wygenerowany w panelu odbiorcy płatności tpay.com.'
, static::WOOCOMMERCE),
static::DEFAULT_SETTING => __('0', static::WOOCOMMERCE),
static::DESC_TIP => true,
),
'cardApiPassword' . $i => array(
static::TITLE => __('Hasło API', static::WOOCOMMERCE),
static::TYPE => 'text',
static::DESCRIPTION => __('Hasło do klucza API', static::WOOCOMMERCE),
static::DEFAULT_SETTING => __('0', static::WOOCOMMERCE),
static::DESC_TIP => true,
),
'verificationCode' . $i => array(
static::TITLE => __('Kod weryfikacyjny', static::WOOCOMMERCE),
static::TYPE => 'text',
static::DESCRIPTION => __('Kod weryfikacyjny', static::WOOCOMMERCE),
static::DEFAULT_SETTING => __('0', static::WOOCOMMERCE),
static::DESC_TIP => true,
),
'hashAlg' . $i => array(
static::TITLE => __('Typ hash', static::WOOCOMMERCE),
static::TYPE => static::SELECT,
static::DEFAULT_SETTING => 'sha1',
static::OPTIONS => array(
'sha1' => __('sha1', static::WOOCOMMERCE),
'sha256' => __('sha256', static::WOOCOMMERCE),
'sha512' => __('sha512', static::WOOCOMMERCE),
'ripemd160' => __('ripemd160', static::WOOCOMMERCE),
'ripemd320' => __('ripemd320', static::WOOCOMMERCE),
'md5' => __('md5', static::WOOCOMMERCE),
),
),
'keyRSA' . $i => array(
static::TITLE => __('Klucz RSA', static::WOOCOMMERCE),
static::TYPE => 'textarea',
static::DESCRIPTION => __('Klucz publiczny RSA', static::WOOCOMMERCE),
static::DEFAULT_SETTING => __('0', static::WOOCOMMERCE),
static::DESC_TIP => true,
),
'doplata' . $i => array(
static::TITLE => __('Dopłata doliczana za korzystanie z metody płatności'
, static::WOOCOMMERCE),
static::TYPE => static::SELECT,
static::DEFAULT_SETTING => '0',
static::OPTIONS => array(
'0' => __('NIE', static::WOOCOMMERCE),
'1' => __('PLN', static::WOOCOMMERCE),
'2' => __('%', static::WOOCOMMERCE),
),
),
'kwota_doplaty' . $i => array(
static::TITLE => __('Kwota dopłaty', static::WOOCOMMERCE),
static::TYPE => "text",
static::DESCRIPTION => __('Kwota jaka zostanie doliczona do zamówienia.
Jako separator liczb należy wykorzystać kropkę', static::WOOCOMMERCE),
static::DEFAULT_SETTING => __('0', static::WOOCOMMERCE),
static::DESC_TIP => true,
),
);
$options['midNumber'][static::OPTIONS][$i] = __((string)$i, static::WOOCOMMERCE);
$options = array_merge($options, $array);
}
return $options;
}
}

View File

@@ -0,0 +1,429 @@
<?php
use tpay\Lang;
use tpay\PaymentBasic;
use tpay\TException;
use tpay\TransactionAPI;
use tpay\Util;
use tpay\Validate;
require_once 'TpayGatewayBase.php';
class WC_Gateway_Tpay_Basic extends TpayGatewayBase
{
const GATEWAY_NAME = 'WC_Gateway_Tpay_Basic';
//MUST BE OLD NAME!
const GATEWAY_ID = 'transferuj';
const BANK_VIEW = 'bank_view';
const BLIK_METHOD = 'blik';
private $seller_id;
private $security_code;
private $blik_on;
private $api_key;
private $api_pass;
private $enable_IP_validation;
private $online_methods_only;
public function __construct()
{
$this->setEnvironment();
$this->setConfig();
$this->init_form_fields();
if ($this->api_pass !== '' && strlen($this->api_key) === 40) {
$this->supports = array('refunds');
}
add_action('woocommerce_update_options_payment_gateways_' . $this->id, array($this, 'process_admin_options'));
parent::__construct();
}
public function init_form_fields()
{
include_once 'SettingsTpay.php';
$charge = $this->get_option(static::DOPLATA);
$list = $this->get_option('bank_list');
$shippingSettings = $this->getShippingMethods();
if (!is_array($shippingSettings)) {
$shippingSettings = array();
}
$settingsTpay = new SettingsTpay();
$this->form_fields = $settingsTpay->getSettings($charge, $list, $shippingSettings);
}
/**
* Check if this gateway is enabled and available in the user's country.
* @return bool
*/
public function is_available()
{
if (get_woocommerce_currency() !== "PLN" || $this->enabled !== 'yes') {
return false;
}
if ($this->isAvailableForShippingMethod($this->shippingMethods) === false) {
return false;
}
return parent::is_available();
}
public function basketReload()
{
//przeladowanie koszyka zamowienia po wybraniu platnosci tpay.com
include_once '_tpl/basketReload.html';
}
/**
* Generates box with gateway name and description, terms acceptance checkbox and channel list
*/
public function payment_fields()
{
parent::payment_fields();
$lang = new Lang;
strcmp($this->language, 'pl_PL') === 0 ? $lang::setLang('pl') : $lang::setLang('en');
$orderAmount = $this->getCartTotal();
$data['merchant_id'] = $this->seller_id;
$data['online_only'] = $this->online_methods_only;
$data['show_regulations_checkbox'] = true;
$data['regulation_url'] = $this->setLanguageRegulations();
$data['policy_privacy_url'] = $this->setLanguagePP();
$data['form'] = '';
$data['showInstallments'] = $orderAmount >= 300 && $orderAmount <= 9259;
echo '<p>' . $this->description . '</p>';
if ($this->blik_on === 1) {
include_once '_tpl/blikForm.phtml';
$this->enqueueScript('blikForm', $this->pluginUrl . '/_js/blikForm.js', array('jquery'), 4, true);
}
$paymentType = $this->paymentType();
if ($paymentType === 1 || $paymentType === 2) {
$link = sprintf('"https://secure.tpay.com/groups-%s%s.js"', $data['merchant_id'], $data['online_only']);
$data['small_list'] = $paymentType === 2;
include_once '_tpl/bankSelection.phtml';
$this->enqueueScript('bankSelection', $this->pluginUrl . '/_js/bankSelection.js', array('jquery'), 4, true);
wp_add_inline_script(
'bankSelection',
sprintf(
'var show_installments = %d, link = %s, isSmallList = %d;',
$data['showInstallments'],
$link,
$data['small_list']
)
);
}
}
public function paymentType()
{
$bankListOption = $this->get_option(static::BANK_LIST);
$bankViewOption = $this->get_option(static::BANK_VIEW);
if ($bankListOption === '0' && $bankViewOption === '0') {
$type = 1;
} elseif ($bankListOption === '0' && $bankViewOption === '1') {
$type = 2;
} elseif ($bankListOption === '1') {
$type = 3;
} else {
$type = 0;
}
return $type;
}
/**
* Generates admin options
*/
public function admin_options()
{
include_once '_tpl/settingsAdmin.phtml';
}
/**
* Sends and receives data to/from tpay.com server
*/
public function gateway_communication()
{
$orderId = filter_input(INPUT_GET, static::ORDER_ID);
if ($orderId) {
$decryptedOrderId = $this->crypt($orderId, $this->security_code, false);
if ($this->shouldSetStatusOnHold($decryptedOrderId)) {
$this->setOrderStatusOnHold($decryptedOrderId);
}
$transactionConfig = $this->getTransactionConfig($orderId);
$this->createTransaction($transactionConfig);
} else {
$this->verifyPaymentResponse();
}
//exit must be present in this function!
exit;
}
private function shouldSetStatusOnHold($orderId)
{
$order = new WC_Order($orderId);
return 1 === $this->orderPendingStatus && $order->get_status() === 'pending';
}
private function setOrderStatusOnHold($orderId)
{
$order = new WC_Order($orderId);
$order->update_status('on-hold');
}
public function getTransactionConfig($orderId)
{
$transactionConfig = $this->getBaseTransactionConfigByOrderId($orderId, $this->security_code);
if ($this->online_methods_only === 1) {
$transactionConfig['online'] = 1;
}
if ((int)filter_input(INPUT_GET, static::REGULATIONS) === 1) {
$transactionConfig['accept_tos'] = 1;
}
if (filter_input(INPUT_GET, static::GROUP)) {
$transactionConfig['group'] = (int)filter_input(INPUT_GET, 'group');
}
return $transactionConfig;
}
public function createTransaction($transactionConfig)
{
$optionalParameters = array('address', 'city', 'country', 'language', 'zip', 'phone');
foreach ($optionalParameters as $parameter) {
if (array_key_exists($parameter, $transactionConfig) && strlen($transactionConfig[$parameter]) < 1) {
unset($transactionConfig[$parameter]);
}
}
if (filter_input(INPUT_GET, static::BLIKCODE) && strlen($_GET[static::BLIKCODE]) === 6) {
$blikCode = filter_input(INPUT_GET, static::BLIKCODE);
$transactionConfig['group'] = 150;
$transactionConfig['accept_tos'] = 1;
try {
$transactionAPI = new TransactionAPI(
$this->api_key,
$this->api_pass,
$this->seller_id,
$this->security_code
);
$resp = $transactionAPI->create($transactionConfig);
$resp = $transactionAPI->blik($blikCode, $resp['title']);
} catch (TException $exception) {
$redirectUrl = $transactionConfig['return_error_url'];
header("Location: " . $redirectUrl);
return false;
}
if ($resp['result'] === 1) {
$redirectUrl = sprintf('%s&method=%s', $transactionConfig['return_url'], self::BLIK_METHOD);
header("Location: " . $redirectUrl);
return true;
}
Util::log('Invalid BLIK code', 'User redirected to transaction panel');
header("Location: " . $resp['url']);
return false;
}
try {
$paymentBasic = new PaymentBasic($this->seller_id, $this->security_code);
$form = $paymentBasic->getTransactionForm($transactionConfig);
} catch (TException $exception) {
return false;
}
echo $form;
return true;
}
/**
* Verifies that no errors have occured during transaction
*/
public function verifyPaymentResponse()
{
try {
$paymentBasic = new PaymentBasic($this->seller_id, $this->security_code);
if ($this->enable_IP_validation === 0) {
$paymentBasic->disableValidationServerIP();
}
$res = $paymentBasic->checkPayment(Validate::PAYMENT_TYPE_BASIC, $this->validateProxyServer);
} catch (TException $exception) {
return;
}
$this->trId = $res['tr_id'];
$this->completePayment($res['tr_crc'], $res);
}
public function process_payment($orderId)
{
global $woocommerce;
if (
isset($_POST[static::BLIKCODE])
&& $_POST[static::BLIKCODE] !== ''
&& $this->isValidBlikCode($_POST[static::BLIKCODE]) === false
) {
wc_add_notice(
__(
'Wprowadzony kod BLIK jest niepoprawny. Kod powinien składać się z sześciu cyfr.',
static::WOOCOMMERCE
),
'error'
);
return array(static::RESULT => 'fail');
}
if (isset($_POST['tpay-regulations-input']) && (int)$_POST['tpay-regulations-input'] !== 1) {
wc_add_notice(
__(
'Aby skorzystać z tej metody płatności musisz zaakceptować regulamin systemu Tpay.',
static::WOOCOMMERCE
),
'error'
);
return array(static::RESULT => 'fail');
}
$woocommerce->cart->empty_cart();
return array(
static::RESULT => static::SUCCESS,
static::REDIRECT => add_query_arg(
array(
static::REGULATIONS => filter_input(INPUT_POST, 'tpay-regulations-input'),
static::ORDER_ID => $this->crypt($orderId, $this->security_code),
static::BLIKCODE => filter_input(INPUT_POST, static::BLIKCODE),
static::GROUP => filter_input(INPUT_POST, 'tpay-channel-input'),
),
$this->notifyLink
),
);
}
public function process_refund($order_id, $amount = null, $reason = '')
{
$order = new WC_Order($order_id);
try {
$transactionAPI = new TransactionAPI(
(string)$this->api_key,
(string)$this->api_pass,
(int)$this->seller_id,
(string)$this->security_code
);
$transactionAPI->refundAny($order->get_transaction_id(), $amount);
return true;
} catch (TException $exception) {
return false;
}
}
/**
* Sets proper transaction status for order based on $status
* @param int $orderId ; id of an order
* @param array $notification
* @return bool
*/
private function completePayment($orderId, $notification)
{
try {
$order = wc_get_order($orderId);
$orderCurrentStatus = $order->get_status('');
if ($notification['tr_status'] === 'CHARGEBACK') {
if ($orderCurrentStatus !== 'refunded') {
$order->update_status('refunded', __('Wykonano zwort transakcji.', static::WOOCOMMERCE), true);
}
return true;
}
$orderAmount = (double)$order->get_total();
if ($orderAmount !== $notification['tr_amount']) {
throw new Exception(
sprintf(
__('Amounts mismatch: expected %s, received: %s', static::WOOCOMMERCE),
$orderAmount,
$notification['tr_amount']
)
);
}
if (in_array($orderCurrentStatus, array('pending', 'on-hold', 'failed'))) {
$order->payment_complete($this->trId);
$this->addPaidOrderNote($notification['tr_error'], $order);
if ($this->autoFinishOrder === 1) {
$order->update_status('completed');
}
}
return true;
} catch (Exception $exception) {
Util::log('Exception in completing payment', $exception->getMessage() . print_r($notification, true));
return false;
}
}
private function isValidBlikCode($code)
{
return (is_numeric($code) && strlen($code) === 6);
}
private function getCartTotal()
{
if ($this->wpbo_get_woo_version_number() >= '3.2') {
$totalTax = WC()->cart->get_cart_contents_tax();
$totalFee = WC()->cart->get_fee_total();
$totalProducts = WC()->cart->get_cart_contents_total();
$orderAmount = $totalProducts + $totalFee + $totalTax;
} else {
$orderAmount = WC()->cart->get_cart_total();
}
return $orderAmount;
}
private function setConfig()
{
$this->id = __(static::GATEWAY_ID, static::WOOCOMMERCE);
$this->title = $this->get_option('title', 'Tpay');
$this->method_title = __('Tpay', static::WOOCOMMERCE);
$this->notifyLink = add_query_arg('wc-api', static::GATEWAY_NAME, $this->siteDomain);
$this->seller_id = (int)$this->get_option('seller_id', 0);
$this->security_code = $this->get_option('security_code', '');
$this->blik_on = (int)$this->get_option('blik_on', 0);
$this->api_key = $this->get_option('api_key', '');
$this->api_pass = $this->get_option('api_pass', '');
$this->validateProxyServer = (int)$this->get_option('proxy_server', 0);
$this->enable_IP_validation = (int)$this->get_option('enable_IP_validation', 1);
$this->autoFinishOrder = (int)$this->get_option('auto_finish_order', 0);
$this->orderPendingStatus = (int)$this->get_option('order_pending_status', 0);
$this->shippingMethods = $this->get_option('shipping_methods', array());
$this->online_methods_only = (int)$this->get_option('online_methods_only');
$this->transactionDescription = $this->get_option('opis', '');
$this->surchargeAmount = (float)$this->get_option(static::KWOTA_DOPLATY, 0.00);
$this->surchargeSetting = (int)$this->get_option(static::DOPLATA, 0);
$this->description = $this->get_option('description');
}
private function addPaidOrderNote($tr_error, $order)
{
if ($tr_error === 'overpay') {
$order->add_order_note(__('Zapłacono z nadpłatą.', static::WOOCOMMERCE));
} elseif ($tr_error === 'surcharge') {
$order->add_order_note(__('Zapłacono z niedopłatą.', static::WOOCOMMERCE));
} elseif ($tr_error === 'none') {
$order->add_order_note(__('Zapłacono.', static::WOOCOMMERCE));
}
}
}

View File

@@ -0,0 +1,869 @@
<?php
use tpay\Lang;
use tpay\PaymentCard;
use tpay\TException;
use tpay\Util;
use tpay\Validate;
use tpay\CardAPI;
require_once 'TpayGatewayBase.php';
class WC_Gateway_Tpay_Cards extends TpayGatewayBase
{
const CARDDATA = 'card_data';
const CURRENCY = 'currency';
const TPAY_ID = 'tpayID';
const ORDER_ID = 'order_id';
const GATEWAY_ID = 'tpaycards';
const GATEWAY_NAME = 'WC_Gateway_Tpay_Cards';
private $midId = 11;
private $debugMode;
private $cardApiKey;
private $cardApiPassword;
private $verificationCode;
private $hashAlg;
private $keyRSA;
public function __construct()
{
$this->id = __(static::GATEWAY_ID, static::WOOCOMMERCE);
add_action('woocommerce_update_options_payment_gateways_' . $this->id, array($this, 'process_admin_options'));
$this->setEnvironment();
$this->init_form_fields();
$this->shippingMethods = $this->get_option('shipping_methods', array());
$this->is_available();
$this->setConfig();
$this->supports = array('refunds');
$this->setSubscriptionsSupport();
add_action('woocommerce_api_wc_gateway_tpay_cards', array($this, 'gateway_communication'));
parent::__construct();
}
public function init_form_fields()
{
include_once 'SettingsTpayCards.php';
$settingsTpay = new SettingsTpayCards();
$shippingSettings = $this->getShippingMethods();
if (!is_array($shippingSettings)) {
$shippingSettings = array();
}
$this->form_fields = $settingsTpay->getSettings($shippingSettings);
}
public function is_available()
{
if ((int)filter_input(INPUT_GET, static::TPAY_ID)) {
$this->midId = (int)filter_input(INPUT_GET, static::TPAY_ID);
return parent::is_available();
}
if (filter_input(INPUT_POST, static::ORDER_ID)) {
$id = explode('|', filter_input(INPUT_POST, static::ORDER_ID));
if (isset($id[1])) {
$this->midId = $id[1];
return parent::is_available();
}
return false;
}
if (isset(WC()->session) && !is_null(WC()->session)) {
if ($this->isAvailableForShippingMethod($this->shippingMethods) === false) {
return false;
}
$saleCurrency = get_woocommerce_currency();
$this->setMidForCurrency($saleCurrency);
if ($this->midId === 11) {
return false;
}
try {
Validate::validateCardCurrency($saleCurrency);
return parent::is_available();
} catch (TException $exception) {
return false;
}
} else {
return parent::is_available();
}
}
public function admin_options()
{
include_once '_tpl/settingsAdminCards.phtml';
}
public function basketReload()
{
//przeladowanie koszyka zamowienia po wybraniu platnosci tpay.com
include_once '_tpl/basketReload.html';
}
public function gateway_communication()
{
if (isset($_POST['type']) && $_POST['type'] === 'deregister') {
$this->verifyDeregisterNotification();
exit;
}
$paymentCard = new PaymentCard(
$this->cardApiKey,
$this->cardApiPassword,
$this->verificationCode,
$this->hashAlg,
$this->keyRSA
);
if (isset($_POST['type'], $_POST[static::ORDER_ID]) && in_array($_POST['type'], array('sale', 'refund'))) {
$this->verifyNotification($paymentCard);
exit;
}
if (filter_input(INPUT_GET, static::ORDER_ID)) {
$paymentResult = false;
$orderId = filter_input(INPUT_GET, static::ORDER_ID, FILTER_VALIDATE_INT);
$order = new WC_Order($orderId);
$transactionData = $this->getTransactionConfig($orderId);
$savedCardId = filter_input(INPUT_GET, 'savedId', FILTER_VALIDATE_INT);
$this->setTpayOrder($orderId, $this->midId, $transactionData['language']);
$user = wp_get_current_user();
if ($savedCardId > 0 && !is_null($user)) {
$userId = $user->ID;
$clientCards = $this->getClientCards($userId);
foreach ($clientCards as $row => $card) {
if (isset($card['id']) && $savedCardId === (int)$card['id']) {
$paymentResult = $this->payBySavedCard($paymentCard, $transactionData, $order, $card);
}
}
} elseif (filter_input(INPUT_GET, static::CARDDATA)) {
$paymentResult = $this->payByNewCard($paymentCard, $transactionData, $order);
}
if ($paymentResult === false) {
$this->tryToPayByRedirect($paymentCard, $transactionData, $order);
} else {
$successUrl = $transactionData['return_url'];
header("Location: " . $successUrl);
}
exit;
}
//exit must be present here!
exit;
}
/**
* @param PaymentCard $paymentCard
* @param array $transactionData
* @return bool|mixed
* @throws TException
*/
public function processCardSale($paymentCard, $transactionData)
{
if ($transactionData['language'] === 'pl') {
Lang::setLang('pl');
} else {
Lang::setLang('en');
}
if ($this->debugMode === 'yes') {
var_dump($transactionData);
}
$_POST[static::CARDDATA] = $transactionData[static::CARDDATA];
$_POST['client_name'] = $transactionData['name'];
$_POST['client_email'] = $transactionData['email'];
$_POST['card_save'] = $transactionData['card_save'];
return $paymentCard->secureSale(
$transactionData['amount'],
$transactionData[static::ORDER_ID],
$transactionData['description'],
$transactionData[static::CURRENCY],
true,
$transactionData['language'],
$transactionData['return_url'],
$transactionData['return_error_url'],
$transactionData['module']
);
}
/**
* @param PaymentCard $paymentCard
* @throws TException
*/
public function verifyNotification($paymentCard)
{
$resp = $paymentCard->handleNotification($this->validateProxyServer);
$orderId = explode('|', $resp[static::ORDER_ID]);
$order = new WC_Order($orderId[0]);
$orderCurrency = method_exists($order, 'get_currency') ?
$order->get_currency() : $order->get_order_currency();
$orderCurrency = Validate::validateCardCurrency($orderCurrency);
$orderTotal = number_format($order->get_total(), 2, '', '');
$amountPaid = number_format($resp['amount'], 2, '', '');
if (isset($resp['type']) && $resp['type'] === 'sale' && $orderTotal !== $amountPaid) {
throw new TException(
sprintf(
'Order amount mismatch. Order: %s paid: %s',
$orderTotal,
$amountPaid
)
);
}
$paymentCard->validateSign(
$resp['sign'],
$resp['sale_auth'],
$resp['card'],
str_replace(',', '.', $resp['amount']),
$resp['date'],
$resp['status'],
$orderCurrency,
isset($resp['test_mode']) ? '1' : '',
$resp['order_id'],
$resp['type'],
isset($resp['sale_ref']) ? $resp['sale_ref'] : '',
isset($resp['cli_auth']) ? $resp['cli_auth'] : '',
isset($resp['reason']) ? $resp['reason'] : ''
);
$this->trId = $resp['sale_auth'];
$this->completePayment($order, $resp);
}
public function removeCard($token)
{
try {
global $wpdb;
require_once(ABSPATH . 'wp-admin/includes/upgrade.php');
$wpdb->delete($this->authTableName, array('cliAuth' => $token));
} catch (Exception $e) {
Util::logLine($e->getMessage());
}
}
public function payment_fields()
{
parent::payment_fields();
$user = wp_get_current_user();
$clientCards = array();
if (!is_null($user) && $user->ID) {
$clientCards = $this->getClientCards($user->ID);
}
$data['userCards'] = array();
foreach ($clientCards as $card) {
$data['userCards'][] = array(
'cardId' => $card['id'],
'shortCode' => $card['cardNoShort'],
);
}
$data['rsa_key'] = $this->keyRSA;
$lang = new Lang;
strcmp($this->language, 'pl_PL') === 0 ? $lang::setLang('pl') : $lang::setLang('en');
$data['regulation_url'] = $this->setLanguageRegulations();
$data['policy_privacy_url'] = $this->setLanguagePP();
include_once "_tpl/cardForm.phtml";
$this->enqueueDependentScripts();
}
public function process_payment($orderId)
{
if (isset($_POST['tpay-cards-regulations-input']) && (int)$_POST['tpay-cards-regulations-input'] !== 1) {
wc_add_notice(
__(
'Aby skorzystać z tej metody płatności musisz zaakceptować regulamin systemu Tpay.',
static::WOOCOMMERCE
),
'error'
);
return array(static::RESULT => 'fail');
}
if (isset($_POST['savedId']) && $_POST['savedId'] === 'new' && empty($_POST[static::CARDDATA])) {
wc_add_notice(
__(
'Wybierz zapisaną kartę lub wprowadź poprawne dane nowej karty.',
static::WOOCOMMERCE
),
'error'
);
return array(static::RESULT => 'fail');
}
if (!isset($_POST['savedId']) && empty($_POST[static::CARDDATA])) {
wc_add_notice(__('Wprowadź poprawne dane karty i zaakceptuj regulamin.', static::WOOCOMMERCE), 'error');
return array(static::RESULT => 'fail');
}
$cardSave = filter_input(INPUT_POST, 'card_save');
if (class_exists('WC_Subscriptions_Order', false)
&& WC_Subscriptions_Order::order_contains_subscription($orderId)
) {
$subscriptionInitialAmount = WC_Subscriptions_Order::get_total_initial_payment($orderId);
if ($subscriptionInitialAmount <= 0) {
wc_add_notice(
__(
'Wybrana metoda płatności nie obsługuje zamówień z darmowym okresem próbnym. Prosimy wybrać inną
metodę płatności.',
static::WOOCOMMERCE
),
'error'
);
return array(static::RESULT => 'fail');
}
if ($cardSave !== 'on' && !empty($_POST[static::CARDDATA])
&& (!isset($_POST['savedId']) || $_POST['savedId'] === 'new')
) {
wc_add_notice(
__(
'W celu zakupu usługi subskrypcyjnej należy wyrazić zgodę na zapisanie karty.',
static::WOOCOMMERCE
),
'error'
);
return array(static::RESULT => 'fail');
}
}
WC()->cart->empty_cart();
return array(
static::RESULT => static::SUCCESS,
static::REDIRECT => add_query_arg(
array(
static::CARDDATA => filter_input(INPUT_POST, static::CARDDATA),
static::TPAY_ID => filter_input(INPUT_POST, static::TPAY_ID),
static::ORDER_ID => $orderId,
'card_save' => $cardSave,
'savedId' => filter_input(INPUT_POST, 'savedId'),
),
$this->notifyLink
),
);
}
public function process_refund($order_id, $amount = null, $reason = '')
{
$order = new WC_Order($order_id);
$midId = $this->getOrderMidId($order->get_id());
$paymentCard = new CardApi(
$this->get_option('cardApiKey' . $midId),
$this->get_option('cardApiPassword' . $midId),
$this->get_option('verificationCode' . $midId),
$this->get_option('hashAlg' . $midId)
);
$currency = Validate::validateCardCurrency(
method_exists($order, 'get_currency') ?
$order->get_currency() : $order->get_order_currency()
);
$lang = $this->getClientLanguageByOrderId($order_id);
if (empty($reason)) {
switch ($lang) {
default:
case 'pl':
$reason = __('Zwrot', static::WOOCOMMERCE);
break;
case 'en':
$reason = __('Refund', static::WOOCOMMERCE);
break;
case 'de':
$reason = __('die Ruckzahlung', static::WOOCOMMERCE);
break;
}
}
try {
$refundResult = $paymentCard->refund('', $order->get_transaction_id(), $reason, $amount, $currency, $lang);
return ($refundResult['status'] === 'correct');
} catch (Exception $exception) {
Util::log('Exception in refunding card payment', $exception->getMessage());
return false;
}
}
/**
* @param float $chargeAmount
* @param WC_Order $order
* @return bool
* @throws TException
*/
public function scheduled_subscription_payment($chargeAmount, $order)
{
if ($order->get_status() !== 'pending') {
return false;
}
$currency = method_exists($order, 'get_currency') ? $order->get_currency() :
$order->get_order_currency();
$userId = $order->get_user_id();
$this->setMidForCurrency($currency);
$transactionData = $this->getTransactionConfig($order->get_id());
$transactionData['amount'] = $chargeAmount;
$transactionData['description'] = $this->getSubRenewalDescription(get_user_locale($userId)) .
$order->get_order_number();
$paymentCard = new PaymentCard(
$this->get_option('cardApiKey' . $this->midId),
$this->get_option('cardApiPassword' . $this->midId),
$this->get_option('verificationCode' . $this->midId),
$this->get_option('hashAlg' . $this->midId),
$this->get_option('keyRSA' . $this->midId)
);
$userCards = $this->getClientCards($userId);
if (empty($userCards)) {
$order->add_order_note(__('Użytkownik wyrejestrował wszystkie karty', static::WOOCOMMERCE));
}
foreach ($userCards as $row => $card) {
$result = $this->payBySavedCard($paymentCard, $transactionData, $order, $card);
if ($result === true) {
$this->setTpayOrder($order->get_id(), $this->midId, $transactionData['language']);
WC_Subscriptions_Manager::process_subscription_payments_on_order($order);
return true;
}
$order->add_order_note(__('Nieudana płatność kartą nr ', static::WOOCOMMERCE) . $card['cardNoShort']);
}
WC_Subscriptions_Manager::process_subscription_payment_failure_on_order($order);
return false;
}
/**
* @param PaymentCard $paymentCard
* @param array $transactionData
* @param WC_Order $order
* @param array $card
* @return bool
* @throws TException
*/
protected function payBySavedCard($paymentCard, $transactionData, $order, $card)
{
$order->add_order_note(__('Płatność zapisaną kartą ', static::WOOCOMMERCE) . $card['cardNoShort']);
$transaction = $paymentCard->getPresaleTransaction(
$card['cliAuth'],
$transactionData['description'],
$transactionData['amount'],
$transactionData[static::ORDER_ID],
$transactionData['language'],
Validate::validateCardCurrency($transactionData[static::CURRENCY])
);
$response = $paymentCard->cardSavedSale($card['cliAuth'], $transaction['sale_auth']);
if ((int)$response['result'] === 1 && $response['status'] === 'correct') {
$this->trId = $response['sale_auth'];
$this->completePayment($order, $response);
return true;
}
if (isset($response['err_code']) && (int)$response['err_code'] === 8) {
$this->removeCard($card['cliAuth']);
}
return false;
}
private function getSubRenewalDescription($language)
{
switch ($language) {
case (stripos($language, 'en') !== false):
$description = __('Subscription renewal, order no ', static::WOOCOMMERCE);
break;
case (stripos($language, 'de') !== false):
$description = __('Abonnementverlängerung, Best.-Nr ', static::WOOCOMMERCE);
break;
default:
$description = __('Odnowienie subskrypcji, zamówienie nr ', static::WOOCOMMERCE);
break;
}
return $description;
}
private function setMidForCurrency($saleCurrency)
{
$counter = 10;
$validMidId = array();
$midForCurrency = '';
$midPLN = '';
for ($i = 1; $i <= $counter; $i++) {
if ($this->get_option('midDomain' . $i) === $this->siteDomain) {
$validMidId[] = $i;
}
}
foreach ($validMidId as $iValue) {
$midCurrency = explode(',', $this->get_option('midCurrency' . $iValue));
$midType = $this->get_option('midType' . $iValue);
$midOn = $this->get_option('midOn' . $iValue);
if ((int)$midType === 0 && $saleCurrency === 'PLN' && $midOn !== 'no') {
$this->midId = $iValue;
$midPLN = $iValue;
break;
}
foreach ($midCurrency as $key => $value) {
if ((strcasecmp($midCurrency[$key], $saleCurrency) === 0
|| strcasecmp($midCurrency[$key], filter_input(INPUT_POST, static::CURRENCY)) === 0)
&& $midOn !== 'no' && (int)$midType === 1
) {
$this->midId = $iValue;
$midForCurrency = $iValue;
} elseif ($midCurrency[$key] === '' && $midOn !== 'no') {
$this->midId = $iValue;
}
}
}
if (!empty($midForCurrency) && empty($midPLN)) {
$this->midId = $midForCurrency;
}
}
/**
* @param int $orderId
* @return array
* @throws TException
*/
private function getTransactionConfig($orderId)
{
$transactionConfig = $this->getBaseTransactionConfigByOrderId($orderId);
if ((int)wp_get_current_user()->ID > 0 && filter_input(INPUT_GET, 'card_save')) {
$transactionConfig['card_save'] = filter_input(INPUT_GET, 'card_save');
} else {
$transactionConfig['card_save'] = false;
}
$transactionConfig[static::ORDER_ID] = $orderId . '|' . $this->midId;
$transactionConfig[static::CARDDATA] = str_replace(' ', '+', filter_input(INPUT_GET, static::CARDDATA));
$order = new WC_Order($orderId);
$transactionConfig[static::CURRENCY] = method_exists($order, 'get_currency') ? $order->get_currency() :
$order->get_order_currency();
return $transactionConfig;
}
/**
* @param PaymentCard $paymentCard
* @param array $transactionData
* @param WC_Order $order
* @return bool
* @throws TException
*/
private function payByNewCard($paymentCard, $transactionData, $order)
{
$response = $this->processCardSale($paymentCard, $transactionData);
if (isset($response[static::RESULT])
&& (int)$response[static::RESULT] === 1
&& $response['status'] === 'correct') {
$paymentCard->validateSign(
$response['sign'],
$response['sale_auth'],
$response['card'],
number_format((float)$transactionData['amount'], 2, '.', ''),
$response['date'],
$response['status'],
Validate::validateCardCurrency($transactionData[static::CURRENCY]),
isset($response['test_mode']) ? '1' : '',
'',
'',
'',
isset($response['cli_auth']) ? $response['cli_auth'] : ''
);
$order->add_order_note(__('Płatność kartą bez 3DS', static::WOOCOMMERCE));
$this->trId = $response['sale_auth'];
$this->completePayment($order, $response);
return true;
}
if (isset($response['3ds_url'])) {
$order->add_order_note(__('Płatność kartą - przekierowano klienta do bramki 3DS', static::WOOCOMMERCE));
wp_redirect($response['3ds_url']);
exit;
}
return false;
}
/**
* @param PaymentCard $paymentCard
* @param array $transactionData
* @param WC_Order $order
* @throws TException
*/
private function tryToPayByRedirect($paymentCard, $transactionData, $order)
{
$response = $paymentCard->getTransactionUrl(
$transactionData['name'],
$transactionData['email'],
$transactionData['description'],
$transactionData['amount'],
Validate::validateCardCurrency($transactionData[static::CURRENCY]),
$transactionData[static::ORDER_ID],
!$transactionData['card_save'],
$transactionData['language'],
$transactionData['return_url'],
$transactionData['return_error_url']
);
if (isset($response['sale_auth'])) {
$transactionUrl = 'https://secure.tpay.com/cards/?sale_auth=' . $response['sale_auth'];
$order->add_order_note(
__(
'Nieudana płatność kartą - przekierowano klienta do panelu transakcyjnego. Link transakcji: ',
static::WOOCOMMERCE
) . $transactionUrl
);
wp_redirect($transactionUrl);
} else {
$this->completePayment($order, $response);
$errorUrl = $transactionData['return_error_url'];
if ($this->debugMode === 'yes') {
var_dump($response);
} else {
header("Location: " . $errorUrl);
}
}
}
private function setTpayOrder($orderId, $midId, $language)
{
$language = strtolower($language);
$orderId = (int)$orderId;
$midId = (int)$midId;
$sql = "INSERT INTO $this->tableName SET wooId = $orderId, midId = $midId, client_language = '$language'";
require_once(ABSPATH . 'wp-admin/includes/upgrade.php');
dbDelta($sql);
}
private function verifyDeregisterNotification()
{
$paymentCard = new PaymentCard('1', '1', '1', 'sha1', '1');
$notification = $paymentCard->handleNotification($this->validateProxyServer);
if (isset($notification['type'], $notification['cli_auth']) && $notification['type'] === 'deregister') {
$this->removeCard($notification['cli_auth']);
}
}
/**
* @param WC_Order $order
* @param array $notification
* @return bool
*/
private function completePayment($order, $notification)
{
try {
if (
isset($notification['type'], $notification['amount'], $notification['sale_auth'])
&& $notification['type'] === 'refund'
&& $notification['status'] === 'correct'
) {
$this->addOrderRefund($notification, $order);
return true;
}
if (isset($notification['status']) && $notification['status'] === 'correct') {
$order->add_order_note(__('Zapłacono.', static::WOOCOMMERCE));
$order->payment_complete($this->trId);
if ($this->autoFinishOrder === 1) {
$order->update_status('completed');
}
if (isset($notification['cli_auth'], $notification['card']) && $order->get_user_id() > 0) {
$this->saveClientToken($order->get_user_id(), $notification);
}
return true;
}
$reason = '';
if (isset($notification['card'])) {
$reason .= isset($notification['reason']) ? $notification['reason'] . ' ' : '';
$reason .= isset($notification['err_desc']) ? $notification['err_desc'] : '';
}
if ($reason !== '') {
$order->update_status('failed', __('Zapłata nie powiodła się.', static::WOOCOMMERCE) . ' ' . $reason);
return true;
}
} catch (Exception $exception) {
Util::log('Exception in completing payment', $exception->getMessage() . print_r($notification, true));
return false;
}
return true;
}
/**
* @param int $userId
* @param array $notification
*/
private function saveClientToken($userId, $notification)
{
$userId = (int)$userId;
$token = $notification['cli_auth'];
$cardNoShort = $notification['card'];
$sql = "INSERT INTO $this->authTableName SET clientId = $userId, cliAuth = '$token', cardNoShort = '$cardNoShort', midId = $this->midId";
require_once(ABSPATH . 'wp-admin/includes/upgrade.php');
dbDelta($sql);
}
private function getClientCards($clientId)
{
global $wpdb;
$clientId = (int)$clientId;
$sql = "SELECT id, cliAuth, cardNoShort FROM $this->authTableName WHERE clientId = $clientId AND midId = $this->midId";
require_once(ABSPATH . 'wp-admin/includes/upgrade.php');
return $wpdb->get_results($sql, ARRAY_A);
}
private function getOrderMidId($orderId)
{
global $wpdb;
$orderId = (int)$orderId;
$sql = "SELECT midId FROM $this->tableName WHERE wooId = $orderId";
require_once(ABSPATH . 'wp-admin/includes/upgrade.php');
$result = $wpdb->get_results($sql);
return $result[0]->midId;
}
private function getClientLanguageByOrderId($orderId)
{
global $wpdb;
$orderId = (int)$orderId;
$sql = "SELECT client_language FROM $this->tableName WHERE wooId = $orderId";
require_once(ABSPATH . 'wp-admin/includes/upgrade.php');
$result = $wpdb->get_results($sql);
return $result[0]->client_language;
}
/**
* @param array $notification
* @param WC_Order $order
* @throws Exception
*/
private function addOrderRefund($notification, $order)
{
$order->add_order_note(
sprintf(
__(
'Wykonano zwrot transakcji. Kwota zwrotu: %s',
static::WOOCOMMERCE
),
number_format($notification['amount'], 2)
)
);
if ($order->get_total() === $notification['amount']) {
$order->update_status('refunded', 'Status zamówienia zmieniony na zwrócone.');
} else {
wc_create_refund(
array(
'amount' => $notification['amount'],
'reason' => sprintf(
__('Identyfikator zwrotu: %s', static::WOOCOMMERCE),
$notification['sale_auth']
),
'order_id' => $order->get_id(),
)
);
}
}
private function setConfig()
{
$this->method_title = __('Tpay credit cards', static::WOOCOMMERCE);
$this->notifyLink = add_query_arg('wc-api', static::GATEWAY_NAME, $this->siteDomain);
$this->title = $this->get_option('title', 'Tpay credit cards');
$this->debugMode = $this->get_option('debugMode', 'no');
$this->transactionDescription = $this->get_option('opis' . $this->midId);
$this->surchargeSetting = (int)$this->get_option(static::DOPLATA . $this->midId, 0);
$this->surchargeAmount = (float)$this->get_option(static::KWOTA_DOPLATY . $this->midId, 0.00);
$this->description = $this->get_option('description' . $this->midId, '');
$this->cardApiKey = $this->get_option('cardApiKey' . $this->midId, '');
$this->cardApiPassword = $this->get_option('cardApiPassword' . $this->midId, '');
$this->verificationCode = $this->get_option('verificationCode' . $this->midId, '');
$this->hashAlg = $this->get_option('hashAlg' . $this->midId, 'sha1');
$this->keyRSA = $this->get_option('keyRSA' . $this->midId, '');
$this->autoFinishOrder = (int)$this->get_option('auto_finish_order', 0);
$this->validateProxyServer = (int)$this->get_option('proxy_server', 0);
}
private function setSubscriptionsSupport()
{
$subscriptionsSupport = array(
'subscriptions',
'subscription_cancellation',
'subscription_suspension',
'subscription_reactivation',
'subscription_amount_changes',
'subscription_date_changes',
'subscription_payment_method_change',
'subscription_payment_method_change_customer',
'subscription_payment_method_change_admin',
'multiple_subscriptions',
);
if (class_exists('WC_Subscriptions', false)) {
$this->supports = array_merge($this->supports, $subscriptionsSupport);
add_action(
'woocommerce_scheduled_subscription_payment_' . $this->id,
array($this, 'scheduled_subscription_payment'),
10,
2
);
}
}
private function enqueueDependentScripts()
{
$this->enqueueScript('jsencrypt', $this->pluginUrl . '/lib/src/common/_js/jsencrypt.min.js', array('jquery'));
$this->enqueueScript(
'string_routines',
$this->pluginUrl . '/lib/src/common/_js/string_routines.js',
array('jquery'),
false,
true
);
$this->enqueueScript(
'visibilityChangesHandler',
$this->pluginUrl . '/_js/visibilityChangesHandler.js',
array('jquery'),
4,
true
);
$this->enqueueScript(
'jquery.payment',
$this->pluginUrl . '/lib/src/common/_js/jquery.payment.js',
array('jquery'),
false,
true
);
$this->enqueueScript(
'tpayCards',
$this->pluginUrl . '/_js/tpayCards.js',
array(
'jquery',
'jquery.payment',
'visibilityChangesHandler',
'string_routines',
'jsencrypt'
),
61,
true
);
$this->enqueueScript(
'tpayCardPayment',
$this->pluginUrl . '/_js/cardPayment.js',
array('tpayCards', 'visibilityChangesHandler'),
4,
true
);
}
}

View File

@@ -0,0 +1,313 @@
<?php
use tpay\TException;
use tpay\Util;
require_once 'lib/src/_class_tpay/Validate.php';
require_once 'lib/src/_class_tpay/Util.php';
require_once 'lib/src/_class_tpay/Exception.php';
require_once 'lib/src/_class_tpay/PaymentBasic.php';
require_once 'lib/src/_class_tpay/PaymentCard.php';
require_once 'lib/src/_class_tpay/CardApi.php';
require_once 'lib/src/_class_tpay/Curl.php';
require_once 'lib/src/_class_tpay/TransactionApi.php';
require_once 'lib/src/_class_tpay/Lang.php';
abstract class TpayGatewayBase extends WC_Payment_Gateway
{
const REGULATIONS = 'regulations';
const BLIKCODE = 'blik_code';
const ORDER_ID = 'orderId';
const GROUP = 'group';
const RESULT = 'result';
const REDIRECT = 'redirect';
const SUCCESS = 'success';
const TR_CRC = 'tr_crc';
const TR_ERROR = 'tr_error';
const KWOTA_DOPLATY = 'kwota_doplaty';
const BANK_LIST = 'bank_list';
const DOPLATA = 'doplata';
const WOOCOMMERCE = 'woocommerce';
const HTTP = 'http://';
const HTTPS = 'https://';
const HTTP_X_FORWARDED_PROTO = 'HTTP_X_FORWARDED_PROTO';
const TPAY_LOGO_URL = 'https://tpay.com/img/banners/logo-tpay-50x25.svg';
const TPAY_REGULATIONS_URL = 'https://secure.tpay.com/regulamin.pdf';
const TPAY_REGULATIONS_URL_EN = 'https://tpay.com/user/assets/files_for_download/terms-and-conditions-of-payments.pdf';
const TPAY_PRIVACY_POLICY_URL = 'https://secure.tpay.com/partner/pliki/klauzula-informacyjna-platnik-umowa.pdf';
const TPAY_PRIVACY_POLICY_URL_EN = 'https://secure.tpay.com/partner/pliki/terms-and-conditions-of-payments.pdf';
const GATEWAY_ID = '';
protected $language = 'pl_PL';
protected $pluginUrl;
protected $trId;
protected $siteDomain;
protected $tableName;
protected $authTableName;
protected $surchargeSetting = 0;
protected $notifyLink;
protected $autoFinishOrder;
protected $orderPendingStatus;
protected $transactionDescription;
protected $surchargeAmount;
protected $validateProxyServer;
protected $shippingMethods = array();
public function __construct()
{
global $wpdb;
$this->has_fields = true;
$this->language = get_locale();
$this->tableName = $wpdb->prefix . "woocommerce_tpay";
$this->authTableName = $wpdb->prefix . "woocommerce_tpay_clients";
$this->icon = apply_filters('woocommerce_transferuj_icon', static::TPAY_LOGO_URL);
if ($this->surchargeSetting !== 0) {
add_action('woocommerce_cart_calculate_fees', array($this, 'addFeeTpay'), 99);
add_action('woocommerce_review_order_after_submit', array($this, 'basketReload'));
}
}
/**
* Generates box with gateway name and description, terms acceptance checkbox and channel list
*/
public function payment_fields()
{
wp_enqueue_style('tpay_woocommerce_sytle', $this->pluginUrl . '/lib/src/common/_css/style.css', array(), 21);
}
public function addFeeTpay()
{
if (WC()->session->get('chosen_payment_method') === static::GATEWAY_ID) {
$cart = WC()->cart;
switch ($this->surchargeSetting) {
case 1:
$cart->add_fee(
__('Opłata za płatność online', static::WOOCOMMERCE),
$this->surchargeAmount,
true,
'standard'
);
break;
case 2:
if (method_exists($cart, 'get_cart_contents_total') && method_exists($cart, 'get_shipping_total')) {
$amount = $cart->get_cart_contents_total() + $cart->get_shipping_total();
} else {
$amount = $cart->cart_contents_total + $cart->shipping_total;
}
$fee = $amount * $this->surchargeAmount / 100;
$cart->add_fee(
__('Opłata za płatność online', static::WOOCOMMERCE),
$fee,
true,
'standard'
);
break;
default:
break;
}
}
}
protected function setEnvironment()
{
if ((isset($_SERVER[static::HTTP_X_FORWARDED_PROTO]) && $_SERVER[static::HTTP_X_FORWARDED_PROTO] === 'https')
|| (is_ssl())
) {
$this->pluginUrl = str_replace(static::HTTP, static::HTTPS, plugins_url('', __FILE__));
$this->siteDomain = preg_replace('/\?.*/', '', str_replace(static::HTTP, static::HTTPS, home_url('/')));
} else {
$this->pluginUrl = plugins_url('', __FILE__);
$this->siteDomain = preg_replace('/\?.*/', '', str_replace(static::HTTPS, static::HTTP, home_url('/')));
}
}
protected function setLanguageRegulations()
{
if ($this->language === 'pl_PL') {
return static::TPAY_REGULATIONS_URL;
}
return static::TPAY_REGULATIONS_URL_EN;
}
protected function setLanguagePP()
{
if ($this->language === 'pl_PL') {
return static::TPAY_PRIVACY_POLICY_URL;
}
return static::TPAY_PRIVACY_POLICY_URL_EN;
}
protected function getShippingMethods()
{
$canUse = true;
$outdatedSettingsList = array(
'legacy_flat_rate',
'woocommerce_local_pickup_settings',
'woocommerce_flat_rate_settings',
'woocommerce_free_shipping_settings',
'woocommerce_international_delivery_settings',
'woocommerce_local_delivery_settings',
);
foreach ($outdatedSettingsList as $setting) {
$settings = get_option($setting);
if (isset($settings['enabled']) && $settings['enabled'] !== 'no') {
$canUse = false;
}
}
$options = array();
if ($canUse && class_exists('WC_Shipping', false)) {
$Shipping = WC()->shipping();
if (method_exists($Shipping, 'get_shipping_methods')) {
try {
$shippingMethods = $Shipping->get_shipping_methods();
foreach ($shippingMethods as $method) {
if (isset($method->id, $method->method_title)) {
$options[$method->id] = $method->method_title;
}
}
} catch (Exception $e) {
Util::log('Exception in getShippingMethods ', print_r($e, true));
}
return $options;
}
}
return $options;
}
protected function isAvailableForShippingMethod($shippingMethods)
{
if (empty($shippingMethods) || !isset(WC()->session)) {
return true;
}
$chosenShippingMethod = WC()->session->get('chosen_shipping_methods');
$valid = false;
if (is_array($chosenShippingMethod)) {
foreach ($chosenShippingMethod as $methodKey => $methodName) {
$chosenShippingMethod = $methodName;
}
}
foreach ($shippingMethods as $shippingMethod) {
if (is_string($chosenShippingMethod) && strpos($chosenShippingMethod, $shippingMethod) !== false) {
$valid = true;
}
}
return $valid;
}
protected function getBaseTransactionConfigByOrderId($orderId, $secret = '')
{
if (!is_numeric($orderId)) {
$orderId = $this->crypt($orderId, $secret, false);
}
if ($orderId === false) {
throw new TException(sprintf('Invalid order ID %s', $orderId));
}
$order = wc_get_order($orderId);
$orderAddress = $order->get_address();
if (strcmp($this->language, 'pl_PL') === 0) {
$language = 'pl';
} elseif (strcmp($this->language, 'de_DE') === 0) {
$language = 'de';
} else {
$language = 'en';
}
$description = array(
'pl' => __('Zamówienie nr', static::WOOCOMMERCE),
'en' => __('Order no', static::WOOCOMMERCE),
'de' => __('Bestellnr', static::WOOCOMMERCE),
);
return array(
'amount' => $order->get_total(),
'description' => sprintf(
"%s %s %s",
preg_replace('/[^A-ZĄĆĘŁŃÓŚŹŻa-ząćęłńóśźż0-9\-\ ]/ui', '', $this->transactionDescription),
$description[$language],
$order->get_order_number()
),
'language' => $language,
'crc' => $orderId,
'email' => $orderAddress['email'],
'name' => $orderAddress['first_name'] . ' ' . $orderAddress['last_name'],
'address' => $orderAddress['address_1'] . ' ' . $orderAddress['address_2'],
'city' => $orderAddress['city'],
'country' => $orderAddress['country'],
'zip' => $orderAddress['postcode'],
'phone' => str_replace(' ', '', $orderAddress['phone']),
'return_url' => $this->get_return_url($order) . '&utm_nooverride=1',
'return_error_url' => $order->get_checkout_payment_url(),
'result_url' => $this->notifyLink,
'module' => 'WooCommerce ' . $this->wpbo_get_woo_version_number(),
);
}
protected function crypt($string, $secret, $encrypt = true)
{
$iv = substr(md5($secret), 16);
$encrypt_method = "AES-256-CBC";
$key = hash('sha256', $secret);
return $encrypt ? base64_encode(openssl_encrypt($string, $encrypt_method, $key, 0, $iv)) :
openssl_decrypt(base64_decode($string), $encrypt_method, $key, 0, $iv);
}
protected function wpbo_get_woo_version_number()
{
// If get_plugins() isn't available, require it
if (!function_exists('get_plugins')) {
require_once(ABSPATH . 'wp-admin/includes/plugin.php');
}
// Create the plugins folder and file variables
$plugin_folder = get_plugins('/' . 'woocommerce');
$plugin_file = 'woocommerce.php';
if (isset($plugin_folder[$plugin_file]['Version'])) {
return $plugin_folder[$plugin_file]['Version'];
} else {
return null;
}
}
protected function enqueueScript($handle, $src, $deps, $ver = false, $inFooter = false)
{
wp_register_script($handle, $src, $deps, $ver, $inFooter);
wp_enqueue_script($handle, $src, $deps, $inFooter);
}
}

Binary file not shown.

After

Width:  |  Height:  |  Size: 55 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 8.4 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 877 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.4 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 19 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.9 KiB

View File

@@ -0,0 +1,104 @@
(function ($) {
$.loadScript = function (url, callback) {
$.ajax({
url: url,
dataType: 'script',
success: callback,
async: false
});
}
function setupBanksForm() {
var str = '',
i,
str2 = '',
tile,
others = [157, 106, 109, 148, 104],
group,
id,
groupName,
logoSrc;
if (isSmallList === 0) {
for (i in tr_groups) {
group = tr_groups[i];
id = group[0];
groupName = group[1];
logoSrc = group[3];
if (show_installments == 0 && id == 109) {
continue;
}
tile = getBankTile(id, groupName, logoSrc);
if (inArray(id, others) === false) {
str += tile;
} else {
str2 += tile;
}
}
var $wrapper = $('#bank-selection-form');
$wrapper.html(str + str2);
$wrapper.find('.tpay-group-holder.tpay-with-logo').click(function () {
var bankId = $(this).attr('data-groupId'),
input = document.getElementById('tpay-channel-input'),
bank_block = document.getElementById('bank-' + bankId),
active_bank_blocks = document.getElementsByClassName('tpay-active');
input.value = bankId;
if (active_bank_blocks.length > 0) {
active_bank_blocks[0].className = active_bank_blocks[0].className.replace('tpay-active', '');
}
if (bank_block !== null) {
bank_block.className = bank_block.className + ' tpay-active';
}
})
} else {
for (i in tr_groups) {
group = tr_groups[i];
id = group[0];
groupName = group[1];
if (show_installments == 0 && id == 109) {
continue;
}
str += getBankOption(id, groupName);
}
document.getElementById('tpay-bank-list').innerHTML = str;
var $wrapper = $('#tpay-bank-list');
$wrapper.change(function () {
document.getElementById('tpay-channel-input').value = document.getElementById('tpay-bank-list').value;
});
}
var regulation_checkbox = document.getElementById('tpay-accept-regulations-checkbox'),
regulations_input = document.getElementById('tpay-regulations-input');
regulation_checkbox.onchange = function () {
regulations_input.value = (this.checked) ? 1 : 0;
};
}
function getBankTile(groupId, groupName, logoSrc) {
return '<div class="tpay-group-holder tpay-with-logo" id="bank-' + groupId + '" data-groupId="' + groupId + '">' +
'<div class="tpay-group-name">' + groupName + '</div>' +
'<div class="tpay-group-logo-holder">' +
'<img src="' + logoSrc + '" class="tpay-group-logo" alt="' + groupName + '"/>' +
'</div></div>';
}
function getBankOption(groupId, groupName) {
return '<option value="' + groupId + '" >' + groupName + '</option>';
}
function inArray(needle, haystack) {
var length = haystack.length;
for (var i = 0; i < length; i++) {
if (haystack[i] == needle) return true;
}
return false;
}
$(document).ready(function () {
var tpayBanksLink = link;
$.loadScript(tpayBanksLink, setupBanksForm);
$(document.body).on('updated_checkout', function () {
$.loadScript(tpayBanksLink, setupBanksForm);
});
});
})(jQuery);

View File

@@ -0,0 +1,18 @@
(function ($) {
$(document).ready(function () {
setupBlikForm();
$(document.body).on('updated_checkout', function () {
setupBlikForm();
});
});
setupBlikForm = function () {
$('#blik_code').on('input change blur', function () {
var that = $(this);
if (that.val().length > 0) {
$('#tpay-transfers-form').css('display', 'none');
} else {
$('#tpay-transfers-form').css('display', 'block');
}
});
}
})(jQuery);

View File

@@ -0,0 +1,162 @@
(function ($) {
function CardPayment(url, pubkey) {
this.url = url;
this.pubkey = pubkey;
$("#card_payment_form").attr("action", url);
var numberInput = $('#card_number'),
expiryInput = $('#expiry_date'),
cvcInput = $('#cvc');
const TRIGGER_EVENTS = 'input change blur';
function SubmitPayment() {
var cardNumber = numberInput.val().replace(/\s/g, ''),
cd = cardNumber + '|' + expiryInput.val().replace(/\s/g, '') + '|' + cvcInput.val().replace(/\s/g, '') + '|' + document.location.origin,
encrypt = new JSEncrypt(),
decoded = Base64.decode(pubkey),
encrypted;
encrypt.setPublicKey(decoded);
encrypted = encrypt.encrypt(cd);
$("#card_data").val(encrypted);
$("#card_vendor").val($.payment.cardType(cardNumber));
}
function setWrong($elem) {
$elem.addClass('wrong').removeClass('valid');
}
function setValid($elem) {
$elem.addClass('valid').removeClass('wrong');
}
function validateCcNumber($elem) {
var isValid = false,
ccNumber = $.payment.formatCardNumber($elem.val()),
supported = ['mastercard', 'maestro', 'visa'],
type = $.payment.cardType(ccNumber),
notValidNote = $('#info_msg_not_valid'),
cardTypeHolder = $('.tpay-card-icon'),
notSupportedNote = $('#info_msg_not_supported');
$elem.val($.payment.formatCardNumber($elem.val()));
cardTypeHolder.attr('class', 'tpay-card-icon');
if (supported.indexOf(type) < 0 && type !== null && ccNumber.length > 1) {
showElem(notSupportedNote);
hideElem(notValidNote);
setWrong($elem);
} else if (supported.indexOf(type) > -1 && $.payment.validateCardNumber(ccNumber)) {
setValid($elem);
hideElem(notSupportedNote);
hideElem(notValidNote);
isValid = true;
SubmitPayment();
} else if (ccNumber.length < 4) {
hideElem(notSupportedNote);
hideElem(notValidNote);
setWrong($elem);
} else {
setWrong($elem);
showElem(notValidNote);
hideElem(notSupportedNote);
}
if (type !== '') {
cardTypeHolder.addClass('tpay-' + type + '-icon');
}
return isValid;
}
function hideElem($elem) {
$elem.css('display', 'none');
}
function showElem($elem) {
$elem.css('display', 'block');
}
function validateExpiryDate($elem) {
var isValid = false, expiration;
$elem.val($.payment.formatExpiry($elem.val()));
expiration = $elem.payment('cardExpiryVal');
if (!$.payment.validateCardExpiry(expiration.month, expiration.year)) {
setWrong($elem);
} else {
setValid($elem);
isValid = true;
SubmitPayment();
}
return isValid;
}
function validateCvc($elem) {
var isValid = false;
if (!$.payment.validateCardCVC($elem.val(), $.payment.cardType(numberInput.val().replace(/\s/g, '')))) {
setWrong($elem);
} else {
setValid($elem);
isValid = true;
SubmitPayment();
}
return isValid;
}
numberInput.on(TRIGGER_EVENTS, function () {
validateCcNumber($(this));
});
expiryInput.on(TRIGGER_EVENTS, function () {
validateExpiryDate($(this));
});
cvcInput.on(TRIGGER_EVENTS, function () {
validateCvc($(this));
});
$(".payment_box.payment_method_tpaycards").visibilityChanged({
callback: function (element, visible) {
SubmitPayment();
},
runOnLoad: false,
frequency: 1000
});
}
function handleTpayForm() {
$('input[name=savedId]').each(function () {
$(this).click(function () {
if ($(this).is(":checked")) {
if ($(this).val() !== 'new') {
$('#card_form').css({opacity: 1.0}).animate({opacity: 0.0}, 500);
setTimeout(
function () {
$('#card_form').css({display: "none"})
}, 500
);
}
}
});
});
$('#newCard').click(function () {
if ($(this).is(":checked")) {
$('#card_form').css({opacity: 0.0, display: "block"}).animate({opacity: 1.0}, 500);
}
});
}
$(document).ready(function ($) {
setupCardForm();
$(document.body).on('updated_checkout', function () {
setupCardForm();
});
function setupCardForm() {
var RSA = document.getElementById("tpayRSA").textContent;
$('input[name=savedId]').first().prop('checked', "checked");
handleTpayForm();
var cards_regulation_checkbox = document.getElementById('tpay-cards-accept-regulations-checkbox'),
cards_regulations_input = document.getElementById('tpay-cards-regulations-input');
cards_regulation_checkbox.onchange = function () {
cards_regulations_input.value = (this.checked) ? 1 : 0;
};
new CardPayment("", RSA);
}
});
})(jQuery);

View File

@@ -0,0 +1,35 @@
(function ($) {
var defaults = {
callback: function () { },
runOnLoad: true,
frequency: 100,
previousVisibility : null
};
var methods = {};
methods.checkVisibility = function (element, options) {
if ($.contains(document, element[0])) {
var previousVisibility = options.previousVisibility;
var isVisible = element.css('display') != 'none';
options.previousVisibility = isVisible;
if (previousVisibility == null) {
if (options.runOnLoad) {
options.callback(element, isVisible);
}
} else if (previousVisibility !== isVisible) {
options.callback(element, isVisible);
}
setTimeout(function() {
methods.checkVisibility(element, options);
}, options.frequency);
}
};
$.fn.visibilityChanged = function (options) {
var settings = $.extend({}, defaults, options);
return this.each(function () {
methods.checkVisibility($(this), settings);
});
};
})(jQuery);

View File

@@ -0,0 +1,44 @@
<div class="tpay-insidebg" id="tpay-transfers-form">
<input name="tpay-channel-input" id="tpay-channel-input" type="hidden">
<input name="tpay-regulations-input" id="tpay-regulations-input" type="hidden">
<div class="tpay-header-wrapper">
<div class="tpay-header-logo">
<img class="tpay-logo" src="https://tpay.com/img/banners/tpay_logo_white.svg"
style="float: left; padding: 35px 0 0 15px; max-height: 100%"/>
</div>
<div class="tpay-header-belt"></div>
</div>
<div id="groups_v" class="tpay-panel-inside-content">
<div id="bank-selection-form" class="tpay-groups-wrapper">
<?php
if ($data['small_list'] === true) { ?>
<select name="bank_list" id="tpay-bank-list" class="tpay-select"></select>
<?php
} ?>
</div>
<?php
if (isset($data['form'])) {
echo $data['form'];
} ?>
</div>
</div>
<div class="tpay-row">
<div class="tpay-amPmCheckbox">
<input id="tpay-accept-regulations-checkbox" type="checkbox" value="0">
<label for="tpay-accept-regulations-checkbox" class="tpay-info-label">
<?php
$lang->l('accept') ?> <a href="<?php
echo $data['regulation_url'] ?>"
target="_blank"><?php
$lang->l('regulations_url') ?></a>
<?php
$lang->l('regulations'); ?>
<?php
$lang->l('privacy_policy'); ?>
<a href="<?php
echo $data['policy_privacy_url'] ?>" target="_blank"><?php
$lang->l('privacy_policy_href') ?></a>
</label>
</div>
</div>

View File

@@ -0,0 +1,7 @@
<script type="text/javascript">
jQuery(document).ready(function ($) {
$(document.body).on('change', 'input[name="payment_method"]', function () {
$('body').trigger('update_checkout');
});
});
</script>

View File

@@ -0,0 +1,39 @@
<div class="tpay-insidebg" id="main-payment">
<div class="tpay-header-wrapper">
<div class="tpay-header-logo">
<img class="tpay-logo" src="https://tpay.com/img/banners/tpay_logo_white.svg"
style="float: left; padding: 35px 0 0 15px; max-height: 100%"/>
</div>
<div class="tpay-header-belt"></div>
</div>
<div class="tpay-panel-inside-content">
<div class="tpay-channel-form-wrapper tpay-content-wrapper-class">
<p><?php $lang->l('blik_info') ?></p>
<p><?php $lang->l('blik_info2') ?></p>
<center>
<img src="https://secure.tpay.com/_/banks/b64.png" style="max-height: 100%; float: none"/>
</center>
<div class="tpay-row">
<center>
<div class="tpay-input-blik-code">
<div class="tpay-input-wrapper" style="max-width: 220px">
<div class="tpay-input-label"><?php $lang->l('codeInputText') ?></div>
<input id="blik_code"
name="blik_code"
pattern="\d*"
type="tel"
autocomplete="off"
maxlength="6"
minlength="6"
placeholder="000000"
tabindex="1"
value=""
class="tpay-input-value tpay-blik-input"
/>
</div>
</div>
</center>
</div>
</div>
</div>
</div>

View File

@@ -0,0 +1,135 @@
<?php
$path = $this->pluginUrl;
?>
<link href="https://fonts.googleapis.com/css?family=Lato&display=swap" rel="stylesheet">
<p><?php echo $this->description; ?></p>
<div class="tpay-insidebg">
<div class="tpay-header-wrapper">
<div class="tpay-header-logo">
<img class="tpay-logo" src="https://tpay.com/img/banners/tpay_logo_white.svg" style="float: left; padding: 35px 0 0 15px; max-height: 100%"/>
</div>
<div class="tpay-header-belt"></div>
</div>
<p id="tpayRSA" style="display: none"><?php echo $this->keyRSA; ?></p>
<div class="tpay-panel-inside-content">
<input name="tpay-cards-regulations-input" id="tpay-cards-regulations-input" type="hidden">
<div id="card_payment_form" class="tpay-cards-choice">
<?php if (!empty($data['userCards'])) { ?>
<div id="saved_card_payment" style="visibility: visible">
<?php
foreach ($data['userCards'] as $card) { ?>
<div>
<input type="radio" name="savedId"
id="cardN<?php echo $card['cardId'] ?>"
value="<?php echo $card['cardId'] ?>"/>
<label for="cardN<?php echo $card['cardId'] ?>"><?php $lang->l('saved_card_label');
echo $card['shortCode'];
if (isset($card['vendor'])) { ?>
<div id="saved_icon" class="tpay-<?php echo $card['vendor'] ?>-icon"></div>
<?php } ?>
</label>
</div>
<?php } ?>
</div>
<div class="tpay-new-card-section">
<input type="radio" name="savedId" id="newCard" value="new"/>
<label for="newCard"> <?php $lang->l('new_card_label'); ?></label>
</div>
<div id="card_form" style="display: none">
<?php } ?>
<input type="hidden" name="card_data" id="card_data" value=""/>
<input type="hidden" name="card_vendor" id="card_vendor" value=""/>
<div class="tpay-channel-form-wrapper tpay-content-wrapper-class">
<div id="card_payment" class="tpay-input-wrapper">
<div class="tpay-col">
<div class="tpay-row">
<div class="tpay-input-wrapper">
<div class="tpay-input-credit-card-number">
<div class="tpay-input-label"><?php $lang->l('card_number') ?></div>
<input id="card_number"
pattern="\d*"
autocompletetype="cc-number"
size="30"
type="tel"
autocomplete="off"
maxlength="23"
placeholder="XXXX XXXX XXXX XXXX"
tabindex="1"
value=""
class="tpay-input-value"
/>
<div class="tpay-card-icon "></div>
</div>
</div>
</div>
</div>
<div class="tpay-col">
<div class="tpay-row">
<div class="tpay-expiration-date-input tpay-input-wrapper">
<div class="tpay-input-label"><?php $lang->l('expiration_date') ?></div>
<input id="expiry_date"
maxlength="9"
type="tel"
placeholder="01 / 2020"
autocomplete="off"
autocompletetype="cc-exp"
tabindex="2"
value=""
class="tpay-input-value"
/>
</div>
<div class="tpay-cvv-input tpay-input-wrapper">
<div class="tpay-input-label tpay-input-cvc" title="<?php $lang->l('signature') ?>">
CVC
</div>
<input id="cvc"
maxlength="4"
type="tel"
autocomplete="off"
autocompletetype="cc-cvc"
placeholder="XXX"
tabindex="3"
value=""
class="tpay-input-value"
/>
</div>
</div>
</div>
</div>
</div>
<div class="tpay-row" style="width: 10px; height: 10px;"></div>
<div class="tpay-row">
<div class="tpay-amPmCheckbox">
<input type="checkbox" id="card_save" name="card_save"/>
<label for="card_save"
class="tpay-info-label"
title="<?php $lang->l('save_card_info') ?>"><?php $lang->l('save_card') ?>
</label>
</div>
</div>
<p id="info_msg_not_supported" style="display: none"><?php $lang->l('not_supported_card') ?></p>
<p id="info_msg_not_valid" style="display: none"><?php $lang->l('not_valid_card') ?></p>
<div id="loading_scr" style="display:none">
<img src="<?php echo $path ?>/lib/src/common/_img/loading.gif"
style="vertical-align: middle;"/><?php $lang->l('processing') ?>
</div>
<input type="hidden" name="tpayID" value="<?php echo $this->midId; ?>">
<?php if (!empty($data['userCards'])) { ?>
</div>
<?php } ?>
</div>
</div>
</div>
<div class="tpay-row">
<div class="tpay-amPmCheckbox">
<input id="tpay-cards-accept-regulations-checkbox" type="checkbox" value="0">
<label for="tpay-cards-accept-regulations-checkbox" class="tpay-info-label">
<?php $lang->l('accept') ?> <a href="<?php echo $data['regulation_url'] ?>"
target="_blank"><?php $lang->l('regulations_url') ?></a>
<?php $lang->l('regulations'); ?>
<?php $lang->l('privacy_policy');?>
<a href="<?php echo $data['policy_privacy_url']?>" target="_blank"><?php $lang->l('privacy_policy_href')?></a>
</label>
</div>
</div>

View File

@@ -0,0 +1,66 @@
<h2><?php _e('Tpay', 'woocommerce'); ?></h2>
<table class="form-table">
<?php $this->generate_settings_html(); ?>
</table>
<script type="text/javascript">
function bank_list() {
var a = jQuery("#woocommerce_transferuj_bank_list option:selected").val();
if (a == "1") {
jQuery('label[for="woocommerce_transferuj_bank_view"]').attr("style", "visibility: hidden ")
jQuery("#woocommerce_transferuj_bank_view").attr("style", "visibility: hidden")
jQuery('label[for="woocommerce_transferuj_scroll"]').attr("style", "visibility: hidden ")
jQuery("#woocommerce_transferuj_scroll").attr("style", "visibility: hidden")
}
else {
jQuery('label[for="woocommerce_transferuj_bank_view"]').attr("style", "visibility: ")
jQuery("#woocommerce_transferuj_bank_view").attr("style", "visibility: ")
a = jQuery("#woocommerce_transferuj_bank_view option:selected").val();
if (a == "1") {
jQuery('label[for="woocommerce_transferuj_scroll"]').attr("style", "visibility: hidden ")
jQuery("#woocommerce_transferuj_scroll").attr("style", "visibility: hidden")
}
else {
jQuery('label[for="woocommerce_transferuj_scroll"]').attr("style", "visibility: ")
jQuery("#woocommerce_transferuj_scroll").attr("style", "visibility: ")
}
}
}
bank_list();
jQuery("#woocommerce_transferuj_bank_list").change(function () {
bank_list();
});
jQuery("#woocommerce_transferuj_bank_view").change(function () {
var a = jQuery("#woocommerce_transferuj_bank_view option:selected").val();
if (a == "1") {
jQuery('label[for="woocommerce_transferuj_scroll"]').attr("style", "visibility: hidden ")
jQuery("#woocommerce_transferuj_scroll").attr("style", "visibility: hidden")
}
else {
jQuery('label[for="woocommerce_transferuj_scroll"]').attr("style", "visibility: ")
jQuery("#woocommerce_transferuj_scroll").attr("style", "visibility: ")
}
});
jQuery("#woocommerce_transferuj_doplata").change(function () {
if (jQuery("#woocommerce_transferuj_doplata").val() == "0") {
jQuery("#woocommerce_transferuj_kwota_doplaty").attr("style", "visibility: hidden")
}
else {
if (jQuery("#woocommerce_transferuj_doplata").val() == "2") {
alert("Podaj jaki % kwoty zamówienia ma zostać doliczony do zapłaty")
}
jQuery("#woocommerce_transferuj_kwota_doplaty").attr("style", "visibility: visible ")
}
});
</script>
<?php

View File

@@ -0,0 +1,56 @@
<h2><?php _e('Tpay credit cards', 'woocommerce'); ?></h2>
<table class="form-table">
<?php $this->generate_settings_html(); ?>
</table>
<script type="text/javascript">
jQuery(document).ready(function () {
getValuesTpay();
for (var i = 1; i < 11; i++) {
jQuery("#woocommerce_tpaycards_midType" + i).change(function () {
showCurrency();
});
}
jQuery('#woocommerce_tpaycards_midNumber').change(function () {
getValuesTpay();
});
});
function showCurrency() {
var a = jQuery("#woocommerce_tpaycards_midNumber option:selected").val();
var b = jQuery("#woocommerce_tpaycards_midType" + a).val();
var c = jQuery("#woocommerce_tpaycards_midCurrnecy" + a);
if (b == 0) {
c.attr("style", "visibility: hidden ");
} else {
c.attr("style", "visibility: ");
}
}
var tr = document.getElementsByTagName('tr');
function getValuesTpay() {
var id = jQuery("#woocommerce_tpaycards_midNumber option:selected").val();
var mid = 0;
if (id == 1) {
mid = 7;
} else {
mid = (id - 1) * 13 + 7;
}
var maxMid = mid + 13;
for (var n = 7; n < tr.length; n++) {
tr[n].style.display = "none";
}
for (var o = mid; o < maxMid; o++) {
tr[o].style.display = "";
}
}
</script>
<?php

View File

@@ -0,0 +1,738 @@
<?php
/*
* Created by tpay.com
*/
namespace tpay;
/**
* CardAPI class
*
* See cards_instructions.pdf for more details
*
* @package tpay
*/
class CardAPI
{
const PRESALE = 'presale';
const EMPTYCODE = 'Client auth code is empty.';
const INVALIDCODE = 'Client auth code is invalid.';
/**
* PaymentCardAPI class constructor
*
* @param string $cardApiKey api key
* @param string $cardApiPassword api password
* @param string $verificationCode verification code
* @param string $hashAlg hash algorithm
*
* @throws TException
*/
const METHOD = 'method';
const NAME = 'name';
const EMAIL = 'email';
const DESC = 'desc';
const AMOUNT = 'amount';
const CURRENCY = 'currency';
const SIGN = 'sign';
const APIPASS = 'api_password';
const LANGUAGE = 'language';
const SALE = 'sale';
const SALEAUTH = 'sale_auth';
const CLIAUTH = 'cli_auth';
/**
* tpay payment url
* @var string
*/
private $apiURL = 'https://secure.tpay.com/api/cards/';
/**
* Card api key
* @var string
*/
private $apiKey;
/**
* Card api pass
* @var string
*/
private $apiPass;
/**
* Api verification code
* @var string
*/
private $verificationCode;
/**
* The same as chosen in merchant panel (https://secure.tpay.com/panel)
* In card api tab preferences
* @var string
*/
private $hashAlg;
public function __construct($cardApiKey, $cardApiPassword, $verificationCode = '', $hashAlg = 'sha1')
{
Validate::validateCardApiKey($cardApiKey);
Validate::validateCardApiPassword($cardApiPassword);
Validate::validateCardHashAlg($hashAlg);
if ($verificationCode !== '') {
Validate::validateCardCode($verificationCode);
}
$this->apiKey = $cardApiKey;
$this->apiPass = $cardApiPassword;
$this->hashAlg = $hashAlg;
$this->verificationCode = $verificationCode;
Util::loadClass('Curl');
}
/**
* Method used to sale initialization in tpay system.
* Successful request returns sale_auth used to redirect client to transaction panel
*
* @param string $clientName client name
* @param string $clientEmail client email
* @param string $saleDescription sale description
* @param float $amount amount
* @param string $currency currency
* @param string|null $orderID order id
* @param bool $onetimer
* @param string $lang
*
* @param bool $powUrlEnable
* @param bool|string $powUrl
* @param string $powUrlBlad
* @return bool|mixed
*/
public function registerSale(
$clientName,
$clientEmail,
$saleDescription,
$amount,
$currency = '985',
$orderID = null,
$onetimer = true,
$lang = 'pl',
$powUrlEnable = true,
$powUrl = '',
$powUrlBlad = ''
) {
return $this->registerSaleBase(
$clientName,
$clientEmail,
$saleDescription,
$amount,
$currency,
$orderID,
$onetimer,
false,
null,
$lang,
$powUrlEnable,
$powUrl,
$powUrlBlad
);
}
/**
* Prepare for register sale @see $this->registerSale
*
* @param string $clientName client name
* @param string $clientEmail client email
* @param string $saleDescription sale description
* @param float $amount amount
* @param string $currency currency
* @param string|null $orderID order id
* @param bool $onetimer
* @param bool $direct
* @param string|null $saledata encrypted credit card data
* @param string $lang
*
* @param bool $enablePowUrl
* @param string $powUrl
* @param string $powUrlBlad
* @param string $module
* @return bool|mixed
*/
private function registerSaleBase(
$clientName,
$clientEmail,
$saleDescription,
$amount,
$currency = '985',
$orderID = null,
$onetimer = true,
$direct = false,
$saledata = null,
$lang = 'pl',
$enablePowUrl = false,
$powUrl = '',
$powUrlBlad = '',
$module = null
) {
$amount = number_format(str_replace(array(',', ' '), array('.', ''), $amount), 2, '.', '');
$params = $this->recogniseMethod($direct, $saledata);
$params = array_merge($params, array(
static::NAME => $clientName,
static::EMAIL => $clientEmail,
static::DESC => $saleDescription,
static::AMOUNT => $amount,
));
$params = array_merge($params, $this->prepareSecondaryParams($currency, $orderID, $onetimer, $lang));
if ($params['method'] !== 'register_sale') {
$params['enable_pow_url'] = $enablePowUrl ? '1' : '0';
}
$params[static::SIGN] = hash($this->hashAlg, implode('&', $params) .'&'. $this->verificationCode);
if(empty($params['onetimer']))
{
unset($params['onetimer']);
}
$params[static::APIPASS] = $this->apiPass;
$params = array_merge($params, $this->checkReturnUrls($powUrl, $powUrlBlad));
if (!is_null($module) && strlen($module) <= 32) {
$params['module'] = $module;
}
Util::log('Card request', print_r($params, true));
return Curl::doCurlRequest($this->apiURL . $this->apiKey, $params);
}
/**
* Prepare for register sale @see $this->registerSale
*
* @param string $saledata
* @param bool $direct
* @return array
*
*/
private function recogniseMethod($direct = false, $saledata = null)
{
if ($direct && !empty($saledata)) {
$params = array(
static::METHOD => 'directsale',
'card' => $saledata,
);
} elseif (!$direct && !empty($saledata)) {
$params = array(
static::METHOD => 'securesale',
'card' => $saledata,
);
} else {
$params = array(
static::METHOD => 'register_sale',
);
}
return $params;
}
/**
* Prepare for register sale @see $this->registerSale
*
* @param string $currency currency
* @param string|null $orderID order id
* @param bool $onetimer
* @param string $lang
* @return array
*
*/
private function prepareSecondaryParams(
$currency = '985',
$orderID = '',
$onetimer = true,
$lang = 'pl'
) {
$params = array();
if ($currency) {
$params[static::CURRENCY] = $currency;
}
if ($orderID) {
$params['order_id'] = $orderID;
}
if ($onetimer) {
$params['onetimer'] = '1';
}
else
{
$params['onetimer'] = '';
}
if ($lang) {
$params[static::LANGUAGE] = Validate::validateCardLanguage($lang);
}
return $params;
}
private function checkReturnUrls($powUrl = '', $powUrlBlad = '')
{
$params = array();
if (filter_var($powUrl, FILTER_VALIDATE_URL)) {
$params['pow_url'] = $powUrl;
}
if (filter_var($powUrlBlad, FILTER_VALIDATE_URL)) {
$params['pow_url_blad'] = $powUrlBlad;
}
return $params;
}
/**
* This method allows Merchant to host payment form on his website and perform sale without any client redirection
* to tpay.com system. This approach requires special security considerations.
* The client will be redirected if his card has 3d secure.
* We support secure communication by encrypting card data (card number, validity date and cvv/cvs number)
* on client side (javascript) with Merchant's public RSA key and send it as one parameter (card) to our API gate.
* A valid SSL certificate on domain is required
*
* @param string $clientName client name
* @param string $clientEmail client email
* @param string $saleDescription sale description
* @param float $amount amount
* @param string $carddata encrypted credit card data
* @param string $curr currency
* @param string|null $orderID order id
* @param bool $onetimer
* @param string $lang
*
* @param bool $enablePowUrl
* @param string $powUrl
* @param string $powUrlBlad
* @param string $module
* @return bool|mixed
* @throws TException
*/
public function secureSale(
$clientName,
$clientEmail,
$saleDescription,
$amount,
$carddata,
$curr = '985',
$orderID = null,
$onetimer = true,
$lang = 'pl',
$enablePowUrl = true,
$powUrl = '',
$powUrlBlad = '',
$module = null
) {
if (!is_string($carddata) || strlen($carddata) === 0) {
throw new TException('Card data are not set');
}
return $this->registerSaleBase(
$clientName,
$clientEmail,
$saleDescription,
$amount,
$curr,
$orderID,
$onetimer,
false,
$carddata,
$lang,
$enablePowUrl,
$powUrl,
$powUrlBlad,
$module
);
}
/**
* This method allows Merchant to host payment form on his website and perform sale without any client redirection
* to tpay.com system. This approach requires special security considerations.
* We support secure communication by encrypting card data (card number, validity date and cvv/cvs number)
* on client side (javascript) with Merchant's public RSA key and send it as one parameter (card) to our API gate.
* A valid SSL certificate on domain is required
*
* @param string $clientName client name
* @param string $clientEmail client email
* @param string $saleDescription sale description
* @param float $amount amount
* @param string $carddata encrypted credit card data
* @param string $curr currency
* @param string|null $orderID order id
* @param bool $onetimer
*
* @return bool|mixed
*
* @throws TException
*/
public function directSale(
$clientName,
$clientEmail,
$saleDescription,
$amount,
$carddata,
$curr = '985',
$orderID = null,
$onetimer = true
) {
if (!is_string($carddata) || strlen($carddata) === 0) {
throw new TException('Card data are not set');
}
return $this->registerSaleBase(
$clientName,
$clientEmail,
$saleDescription,
$amount,
$curr,
$orderID,
$onetimer,
true,
$carddata
);
}
/**
* Method used to create new sale for payment on demand.
* It can be called after receiving notification with cli_auth (see communication schema in register_sale method).
* It cannot be used if onetimer option was sent in register_sale or client has unregistered
* (by link in email or by API).
*
* @param string $clientAuthCode client auth code
* @param string $saleDescription sale description
* @param float $amount amount
* @param string $currency currency
* @param null $orderID order id
* @param string $lang language
*
* @return bool|mixed
*
* @throws TException
*/
public function presale(
$clientAuthCode,
$saleDescription,
$amount,
$currency = '985',
$orderID = null,
$lang = 'pl'
) {
$params = $this->saleValidateAndPrepareParams($clientAuthCode, $saleDescription, $amount,
$currency, $orderID, $lang, static::PRESALE);
$amount = number_format($amount, 2, '.', '');
$hashParams = array(
static::PRESALE,
$clientAuthCode,
$saleDescription,
$amount,
$currency,
$orderID,
$lang,
$this->verificationCode,
);
$params[static::SIGN] = hash($this->hashAlg, implode('&', $hashParams));
$params[static::APIPASS] = $this->apiPass;
Util::log('Presale params', print_r($params, true));
return Curl::doCurlRequest($this->apiURL . $this->apiKey, $params);
}
/**
* Validate all transaction parameters and throw TException if any error occurs
* Add required fields sign and api password to config
*
* @param string $clientAuthCode client auth code
* @param string $saleDescription sale description
* @param float $amount amount
* @param string $currency currency
* @param string|null $orderID order id
* @param string $lang language
* @param string $method sale method
* @param array $errors validation errors
*
* @return array parameters for sale request
*
* @throws TException
*/
private function saleValidateAndPrepareParams(
$clientAuthCode,
$saleDescription,
$amount,
$currency,
$orderID,
$lang,
$method,
$errors = array()
) {
if (!is_string($clientAuthCode) || strlen($clientAuthCode) === 0) {
$errors[] = static::EMPTYCODE;
} else {
if (strlen($clientAuthCode) !== 40) {
$errors[] = static::INVALIDCODE;
}
}
if (!is_string($saleDescription) || strlen($saleDescription) === 0) {
$errors[] = 'Sale description is empty.';
} else {
if (strlen($saleDescription) > 128) {
$errors[] = 'Sale description is too long. Max 128 characters.';
}
}
if (!is_double($amount) && !is_float($amount) && !is_int($amount) && $amount <= 0) {
$errors[] = 'Amount is invalid.';
}
if (!is_int($currency) && strlen($currency) != 3) {
$errors[] = 'XCurrency is invalid.';
}
if (count($errors) > 0) {
throw new TException(sprintf('%s', implode(' ', $errors)));
}
$amount = number_format(str_replace(array(',', ' '), array('.', ''), $amount), 2, '.', '');
$params = array(
static::METHOD => $method,
static::CLIAUTH => $clientAuthCode,
static::DESC => $saleDescription,
static::AMOUNT => $amount,
);
if ($currency) {
$params[static::CURRENCY] = $currency;
}
if ($orderID) {
$params['order_id'] = $orderID;
}
if ($lang) {
$params[static::LANGUAGE] = $lang;
}
$params[static::SIGN] = hash($this->hashAlg, implode('&', $params) .'&'. $this->verificationCode);
$params[static::APIPASS] = $this->apiPass;
return $params;
}
/**
* Make sale by client auth code
*
* @param string $clientAuthCode client auth code
* @param string $saleDescription sale description
* @param float $amount amount
* @param string $currency currency
* @param string|null $orderID order id
* @param string $lang language
*
* @return bool|mixed
*
* @throws TException
*/
public function completeSale(
$clientAuthCode,
$saleDescription,
$amount,
$currency = '985',
$orderID = null,
$lang = 'pl'
) {
$params = $this->saleValidateAndPrepareParams($clientAuthCode, $saleDescription,
$amount, $currency, $orderID, $lang, static::PRESALE);
$response = Curl::doCurlRequest($this->apiURL . $this->apiKey, $params);
if ($response['result']) {
$saleAuthCode = $response[static::SALEAUTH];
return $this->sale($clientAuthCode, $saleAuthCode);
}
return $response;
}
/**
* Method used to execute created sale with presale method. Sale defined with sale_auth can be executed only once.
* If the method is called second time with the same parameters, system returns sale actual status - in parameter
* status - done for correct payment and declined for rejected payment.
* In that case, client card is not charged the second time.
*
* @param string $clientAuthCode client auth code
* @param string $saleAuthCode sale auth code
*
* @return bool|mixed
*/
public function sale($clientAuthCode, $saleAuthCode)
{
if (strlen($clientAuthCode) != 40) {
return false;
}
if (strlen($saleAuthCode) != 40) {
return false;
}
$params = array(
static::METHOD => static::SALE,
static::CLIAUTH => $clientAuthCode,
static::SALEAUTH => $saleAuthCode,
);
$params[static::SIGN] = hash($this->hashAlg, static::SALE .'&'.
$clientAuthCode .'&'. $saleAuthCode .'&'. $this->verificationCode);
$params[static::APIPASS] = $this->apiPass;
return Curl::doCurlRequest($this->apiURL . $this->apiKey, $params);
}
/**
* Method used to transfer money back to the client.
* The refund can reference to chosen sale (sale_auth) or directly to client (cli_auth).
* In both cases amount is adjustable in parameter amount.
* If only cli_auth is sent amount parameter is required,
* if sale_auth is passed amount and currency is not necessary -
* system will take default values from the specified sale. With sale_auth refund can be made only once
*
* @param string $clientAuthCode client auth code
* @param string|bool $saleAuthCode sale auth code
* @param string $refundDesc refund description
* @param float|null $amount amount
* @param string $currency currency
* @param string $lang
*
* @return bool|mixed
*
* @throws TException
*/
public function refund($clientAuthCode, $saleAuthCode, $refundDesc, $amount = null, $currency = '985', $lang = 'pl')
{
$errors = array();
if (!is_string($saleAuthCode) || strlen($saleAuthCode) === 0) {
$errors[] = 'Sale auth code is empty.';
} else {
if (strlen($saleAuthCode) !== 40) {
$errors[] = 'Sale auth code is invalid.';
}
}
if (!is_string($refundDesc) || strlen($refundDesc) === 0) {
$errors[] = 'Refund desc is empty.';
} else {
if (strlen($refundDesc) > 128) {
$errors[] = 'Refund desc is too long. Max 128 characters.';
}
}
if ($amount != null) {
$amount = number_format(str_replace(array(',', ' '), array('.', ''), $amount), 2, '.', '');
} else {
if ($clientAuthCode && !$saleAuthCode) {
$errors[] = 'Sale auth is false.';
}
}
if (!isset($clientAuthCode) && !isset($saleAuthCode)) {
$errors[] = 'Cli auth is not set and sale auth is not set.';
}
if (!is_int($currency) && strlen($currency) != 3) {
$errors[] = 'Currency is invalid.';
}
if (count($errors) > 0) {
throw new TException(sprintf('%s', implode(' ', $errors)));
}
$params[static::METHOD] = 'refund';
if ($clientAuthCode) {
$params[static::CLIAUTH] = $clientAuthCode;
}
else{
$params[static::CLIAUTH] = '';
}
if ($saleAuthCode) {
$params[static::SALEAUTH] = $saleAuthCode;
}
else
{
$params[static::SALEAUTH] = '';
}
$params[static::DESC] = $refundDesc;
if ($amount) {
$params[static::AMOUNT] = $amount;
}
if ($currency) {
$params[static::CURRENCY] = $currency;
}
if ($lang) {
$params[static::LANGUAGE] = $lang;
}
$params[static::SIGN] = hash($this->hashAlg, implode('&', $params) .'&' . $this->verificationCode);
foreach ($params as $paramsKey => $paramsValue) {
if ($paramsValue === '') {
unset($params[$paramsKey]);
}
}
$params[static::APIPASS] = $this->apiPass;
Util::log('Refund request params', print_r($params, true));
$result = Curl::doCurlRequest($this->apiURL . $this->apiKey, $params);
Util::log('Refund results', print_r($result, true));
if ((int)$result['result'] !== 1) {
throw new TException('Refunding error', $result['err_code']);
}
return $result;
}
/**
* Method used to deregister client card data from system.
* Client can also do it himself from link in email after payment - if onetimer was not set - in that case system
* will sent notification. After successful deregistration Merchant can no more charge client's card
*
* @param string $clientAuthCode client auth code
*
* @return bool|mixed
*
* @throws TException
*/
public function deregisterClient($clientAuthCode)
{
$errors = array();
if (!is_string($clientAuthCode) || strlen($clientAuthCode) === 0) {
$errors[] = static::EMPTYCODE;
} else {
if (strlen($clientAuthCode) !== 40) {
$errors[] = static::INVALIDCODE;
}
}
if (count($errors) > 0) {
throw new TException(sprintf('%s', implode(' ', $errors)));
}
$params[static::METHOD] = 'deregister';
$params[static::CLIAUTH] = $clientAuthCode;
$params[static::SIGN] = hash($this->hashAlg, implode('&', $params) .'&'. $this->verificationCode);
$params[static::APIPASS] = $this->apiPass;
return Curl::doCurlRequest($this->apiURL . $this->apiKey, $params);
}
}

View File

@@ -0,0 +1,113 @@
<?php
/*
* Created by tpay.com
*/
namespace tpay;
/**
* Curl class which helps with CURL handling
*
* @package tpay
*/
class Curl
{
/**
* Last executed cURL info
* @var array|null
*/
private static $curlInfo;
/**
* Last executed cURL error
* @var string
*/
private static $curlError = '';
/**
* Last executed cURL errno
* @var string
*/
private static $curlErrno = '';
/**
* Get last info
*
* @return mixed
*/
public static function getCurlLastInfo()
{
return static::$curlInfo;
}
/**
* Execute cURL request
*
* @param string $url action url
* @param array $postData array with post variables
*
* @return mixed
* @throws TException
*/
public static function doCurlRequest($url, $postData = array())
{
if (!function_exists('curl_init') || !function_exists('curl_exec')) {
throw new TException('cURL function not available');
}
$postData['json'] = true;
$ch = curl_init();
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, false);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 15);
curl_setopt($ch, CURLOPT_TIMEOUT, 50);
curl_setopt($ch, CURLOPT_VERBOSE, 1);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($postData));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_FAILONERROR, true);
curl_setopt($ch, CURLOPT_URL, $url);
$curlRes = curl_exec($ch);
static::$curlInfo = curl_getinfo($ch);
static::$curlError = curl_error($ch);
static::$curlErrno = curl_errno($ch);
static::checkResponse();
curl_close($ch);
return (array)(json_decode($curlRes));
}
/**
* List of http response codes the occurrence of which results in throw exception
*
* @var array
*/
private static $httpCodes = array(
500 => '500: Internal Server Error',
501 => '501: Not Implemented',
502 => '502: Bad Gateway',
503 => '503: Service Unavailable',
504 => '504: Gateway Timeout',
505 => '505: HTTP Version Not Supported',
);
/**
* Check cURL response and throw exception if code is not allowed
*
* @throws TException
*/
private static function checkResponse()
{
$responseCode = static::$curlInfo['http_code'];
if ($responseCode !== 200) {
if (isset(static::$httpCodes[$responseCode])) {
throw new TException(sprintf('tpay.com server return %s', static::$httpCodes[$responseCode]));
} else {
throw new TException('Unexpected response from tpay server');
}
}
}
}

View File

@@ -0,0 +1,30 @@
<?php
/*
* Created by tpay.com
*/
namespace tpay;
/**
* Class TException
*
* @package tpay
*/
class TException extends \Exception
{
/**
* @param string $message error message
* @param int $code error code
*/
public function __construct($message, $code = 0)
{
require_once(dirname(__FILE__) . '/Util.php');
$message .= ' in file ' . $this->getFile() . ' line: ' . $this->getLine();
Util::log('TException', $message . "\n\n" . $this->getTraceAsString());
$this->message = $code . ' : ' . $message;
return $code . ' : ' . $message;
}
}

View File

@@ -0,0 +1,198 @@
<?php
/*
* Created by tpay.com
*/
namespace tpay;
/**
* Class Lang
*
* @package tpay
*/
class Lang
{
const REGULATIONS = 'regulations';
/**
* Current language
*
* @var string
*/
private static $lang = 'en';
/**
* Translation data
*
* @var array
*/
private static $data = array(
'en' => array(
// GLOBALS
'fee_info' => 'Fee for using this payment method: ',
'pay' => 'Pay with Tpay',
'merchant_info' => 'Merchant info',
'amount' => 'Amount',
'order' => 'Order',
// BLIK
'codeInputText' => 'BLIK code',
'blik_info' => 'Type in 6 digit code and confirm the order to commit BLIK payment.',
'blik_info2' => 'If you want to pay with standard method, leave this field blank.',
'blik_accept' => 'By using this method you confirm acceptance',
// BANK SELECTION
'cards_and_transfers' => 'Credit cards and bank transfers',
'other_methods' => 'Others',
'accept' => 'I accept the',
'regulations_url' => self::REGULATIONS,
self::REGULATIONS => 'of Tpay service',
'privacy_policy' => 'The administrator of personal data is Krajowy Integrator Płatności S.A based in Poznań.',
'privacy_policy_href' => ' Take a look at the full content.',
'acceptance_is_required' => 'Acceptance of regulations is required before payment',
// CARD
'saved_card' => 'Saved card ',
'new_card' => 'New card',
'card_number' => 'Card number',
'expiration_date' => 'Expiration date',
'signature' => 'For MasterCard, Visa or Discover, it\'s the last three digits
in the signature area on the back of your card.',
'name_on_card' => 'Name on card',
'name_surname' => 'Name and surname',
'save_card' => 'Save my card',
'save_card_info' => 'Let faster payments in future. Card data is stored on external, save server.',
'saved_card_label' => 'Pay by saved card ',
'processing' => 'Processing data, please wait...',
'card_payment' => 'Payment',
'debit' => 'Please debit my account',
'not_supported_card' => 'Sorry, your credit card is currently not supported. Please try another payment card or payment method.',
'not_valid_card' => 'Sorry, your credit card number is invalid. Please enter the valid card number',
// DAC
'transfer_details' => 'Bank transfer details',
'payment_amount' => 'The amount of the payment',
'disposable_account' => 'Disposable account number for the payment',
// SZKWAL
'account_number' => 'Account number',
'payment_title' => 'Payment title',
'payment_method' => 'Payment method',
'szkwal_info' => 'Your title transfer is dedicated to you and very important for the identification of
payment. You can create a transfer as defined in its bank to
quickly and easily fund your account in the future',
'new_card_label' => 'Pay by a new card',
// WHITE LABEL
'go_to_bank' => 'Go to bank',
),
'pl' => array(
// GLOBALS
'fee_info' => 'Za korzystanie z płatności online sprzedawca dolicza: ',
'pay' => 'Zapłać z Tpay',
'merchant_info' => 'Dane sprzedawcy',
'amount' => 'Kwota',
'order' => 'Zamówienie',
// BLIK
'codeInputText' => 'Kod BLIK',
'blik_info' => 'Jeśli chcesz zapłacić kodem BLIK, wpisz go i dokończ zamówienie.',
'blik_info2' => 'W przeciwnym wypadku pozostaw to pole puste.',
'blik_accept' => 'Korzystając z tej metody płatności oświadczasz, że akceptujesz',
// BANK SELECTION
'cards_and_transfers' => 'Karty płatnicze i przelewy',
'other_methods' => 'Pozostałe',
'accept' => 'Akceptuję',
'regulations_url' => 'regulamin',
self::REGULATIONS => 'serwisu Tpay',
'privacy_policy' => 'Administratorem danych osobowych jest Krajowy Integrator Płatności spółka akcyjna z siedzibą w Poznaniu.',
'privacy_policy_href' => 'Zapoznaj się z pełną treścią',
'acceptance_is_required' => 'Akceptacja regulaminu jest obowiązkowa, przed rozpoczęciem płatności',
// CARD
'saved_card' => 'Zapisana karta ',
'new_card' => 'Nowa karta',
'card_number' => 'Numer karty',
'expiration_date' => 'Termin ważności',
'signature' => 'Dla MasterCard, Visa lub Discover, są to trzy ostatnie
cyfry umieszczone przy podpisie karty.',
'name_on_card' => 'Właściciel karty',
'name_surname' => 'Imię i nazwisko',
'save_card' => 'Zapisz moją kartę',
'save_card_info' => 'Zezwolenie na szybszą płatność w przyszłości.
Dane karty zostaną zapisane na serwerze Tpay',
'saved_card_label' => 'Zapłać zapisaną kartą ',
'processing' => 'Przetwarzanie danych, proszę czekać...',
'card_payment' => 'Zapłać',
'debit' => 'Proszę obciążyć moje konto',
'not_supported_card' => 'Przepraszamy, ten typ karty nie jest obecnie obsługiwany. Prosimy skorzystać z innej karty lub wybrać inną metodę płatności.',
'not_valid_card' => 'Przepraszamy, wprowadzony numer karty jest niepoprawny. Prosimy wprowadzić prawidłowy numer.',
'new_card_label' => 'Zapłać nową kartą',
// DAC
'transfer_details' => 'Szczegóły przelewu',
'payment_amount' => 'Kwota przelewu',
'disposable_account' => 'Jednorazowy numer konta dla tej transakcji',
// SZKWAL
'account_number' => 'Numer konta',
'payment_title' => 'Tytuł przelewu',
'payment_method' => 'Sposób płatności',
'szkwal_info' => 'Twój tytuł przelewu jest dedykowany dla Ciebie i bardzo ważny dla identyfikacji wpłaty.
Możesz stworzyć przelew zdefiniowany w swoim banku, aby wygodnie i szybko zasilić swoje
konto w przyszłości.',
// WHITE LABEL
'go_to_bank' => 'Przejdź do banku',
)
);
/**
* Change current language
*
* @param string $lang language code
*
* @throws TException
*/
public static function setLang($lang)
{
if (isset(static::$data[$lang])) {
static::$lang = $lang;
} else {
throw new TException('No translation for this language');
}
}
/**
* Get and print translated string
* @param $key
*/
public static function l($key)
{
echo static::get($key);
}
/**
* Get translated string
*
* @param string $key
*
* @throws TException
* @return string
*/
public static function get($key)
{
if (isset(static::$data[static::$lang][$key])) {
return static::$data[static::$lang][$key];
} else {
throw new TException('No translation for this key');
}
}
}

View File

@@ -0,0 +1,382 @@
<?php
/*
* Created by tpay.com
*/
namespace tpay;
/**
* Class PaymentBasic
*
* Class handles bank transfer payment through tpay panel
*
* @package tpay
*/
class PaymentBasic
{
const REMOTE_ADDR = 'REMOTE_ADDR';
/**
* @var string
*/
const ACTIONURL = 'action_url';
/**
* @var string
*/
const FIELDS = 'fields';
/**
* @var string
*/
const PAYMENTFORM = 'paymentForm';
/**
* Merchant id
* @var int
*/
protected $merchantId = '[MERCHANT_ID]';
/**
* tpay payment url
* @var string
*/
protected $apiURL = 'https://secure.tpay.com';
/**
* Merchant secret
* @var string
*/
private $merchantSecret = '[MERCHANT_SECRET]';
/**
* tpay response IP
* @var string
*/
private $secureIP = array(
'195.149.229.109',
'148.251.96.163',
'178.32.201.77',
'46.248.167.59',
'46.29.19.106'
);
/**
* If false library not validate tpay server IP
* @var bool
*/
private $validateServerIP = true;
/**
* Path to template directory
* @var string
*/
private $templateDir = 'common/_tpl/';
/**
* URL to tpay regulations file
* @var string
*/
private $regulationURL = 'https://secure.tpay.com/regulamin.pdf';
/**
* PaymentBasic class constructor for payment:
* - basic from tpay panel
* - with bank selection in merchant shop
* - eHat
*
* @param string|bool $merchantId merchant id
* @param string|bool $merchantSecret merchant secret
*/
public function __construct($merchantId = false, $merchantSecret = false)
{
if ($merchantId !== false) {
$this->merchantId = $merchantId;
}
if ($merchantSecret !== false) {
$this->merchantSecret = $merchantSecret;
}
require_once(dirname(__FILE__) . '/Util.php');
Util::loadClass('Curl');
Util::loadClass('Validate');
Util::loadClass('Exception');
Util::loadClass('Lang');
Util::checkVersionPHP();
Validate::validateMerchantId($this->merchantId);
Validate::validateMerchantSecret($this->merchantSecret);
}
/**
* Disabling validation of payment notification server IP
* Validation of tpay server ip is very important.
* Use this method only in test mode and be sure to enable validation in production.
*/
public function disableValidationServerIP()
{
$this->validateServerIP = false;
}
/**
* Enabling validation of payment notification server IP
*/
public function enableValidationServerIP()
{
$this->validateServerIP = true;
}
/**
* Check cURL request from tpay server after payment.
* This method check server ip, required fields and md5 checksum sent by payment server.
* Display information to prevent sending repeated notifications.
*
* @param string $paymentType optional payment type default is 'basic'
*
* @param bool $proxy
* @return array
* @throws TException
*/
public function checkPayment($paymentType = Validate::PAYMENT_TYPE_BASIC, $proxy)
{
Util::log('check basic payment', '$_POST: ' . "\n" . print_r($_POST, true));
$res = Validate::getResponse($paymentType);
$checkMD5 = $this->checkMD5(
$res['md5sum'],
$res['tr_id'],
number_format($res['tr_amount'], 2, '.', ''),
$res['tr_crc']
);
Util::logLine('Check MD5: ' . (int)$checkMD5);
if ($this->validateServerIP === true && $this->checkServer($proxy) === false) {
throw new TException('Request is not from secure server');
}
if ($checkMD5 === false) {
throw new TException('MD5 checksum is invalid');
}
echo 'TRUE';
return $res;
}
/**
* Check md5 sum to validate tpay response.
* The values of variables that md5 sum includes are available only for
* merchant and tpay system.
*
* @param string $md5sum md5 sum received from tpay
* @param string $transactionId transaction id
* @param float $transactionAmount transaction amount
* @param string $crc transaction crc
*
* @return bool
*/
private function checkMD5($md5sum, $transactionId, $transactionAmount, $crc)
{
if (!is_string($md5sum) || strlen($md5sum) !== 32) {
return false;
}
return ($md5sum === md5($this->merchantId . $transactionId .
$transactionAmount . $crc . htmlspecialchars_decode($this->merchantSecret)));
}
/**
* Check if request is called from secure tpay server
*
* @param bool $allowProxy
* @return bool
*/
private function checkServer($allowProxy)
{
if (isset($_SERVER[static::REMOTE_ADDR]) && in_array($_SERVER[static::REMOTE_ADDR], $this->secureIP)) {
return true;
}
if ($allowProxy && isset($_SERVER['HTTP_X_FORWARDED_FOR'])) {
$proxyIps = explode(',', $_SERVER['HTTP_X_FORWARDED_FOR']);
if (in_array($proxyIps[0], $this->secureIP)) {
return true;
}
}
if ($allowProxy && isset($_SERVER['HTTP_CF_CONNECTING_IP']) && in_array($_SERVER['HTTP_CF_CONNECTING_IP'],
$this->secureIP)
) {
return true;
}
return false;
}
/**
* Check cURL request from tpay server after payment.
* This method check server ip sent by payment server.
* Display information to prevent sending repeated notifications.
*
* @param string $paymentType optional payment type default is 'basic'
*
* @throws TException
*
* @return array
*/
public function checkAliasNotification($paymentType = Validate::ALIAS_BLIK)
{
Util::log('check blik notification', '$_POST: ' . "\n" . print_r($_POST, true));
$res = Validate::getResponse($paymentType);
if ($this->validateServerIP === true && $this->checkServer(false) === false) {
throw new TException('Request is not from secure server');
}
echo 'TRUE';
return $res;
}
/**
* Create HTML form for EHat payment based on transaction config
* More information about config fields @see Validate::$panelPaymentRequestFields
*
* @param array $config transaction config
*
* @return string
*/
public function getEHatForm($config)
{
$config = $this->prepareConfig($config);
$config['kanal'] = 58;
$config['akceptuje_regulamin'] = 1;
$data = array(
static::ACTIONURL => $this->apiURL,
static::FIELDS => $config,
);
return Util::parseTemplate($this->templateDir . static::PAYMENTFORM, $data);
}
/**
* Validate passed payment config and add required elements with merchant id and md5 sum
* More information about config fields @see Validate::$panelPaymentRequestField
*
* @param array $config transaction config
*
* @return array
*
* @throws TException
*/
public function prepareConfig($config)
{
$ready = Validate::validateConfig(Validate::PAYMENT_TYPE_BASIC, $config);
$md5Params = array(
$this->merchantId,
$ready['amount'],
$ready['crc'],
htmlspecialchars_decode($this->merchantSecret),
);
$ready['md5sum'] = md5(implode('&', $md5Params));
$ready['id'] = $this->merchantId;
return $ready;
}
/**
* Create HTML form for basic panel payment based on transaction config
* More information about config fields @see Validate::$panelPaymentRequestFields
*
* @param array $config transaction config
*
* @return string
*/
public function getTransactionForm($config)
{
$config = $this->prepareConfig($config);
$data = array(
static::ACTIONURL => $this->apiURL,
static::FIELDS => $config,
);
return Util::parseTemplate($this->templateDir . static::PAYMENTFORM, $data);
}
public function getTransactionFormConfig($config)
{
return $this->prepareConfig($config);
}
/**
* Create HTML form for payment with bank selection based on transaction config
* More information about config fields @see Validate::$panelPaymentRequestFields
*
* @param array $config transaction config
* @param bool $smallList type of bank selection list big icons or small form with select
* @param bool $showRegulations show accept regulations input
*
* @return string
*
* @throws TException
*/
public function getBankSelectionForm($config, $smallList = false, $showRegulations = true)
{
$config = $this->prepareConfig($config);
$config['kanal'] = 0;
$config['akceptuje_regulamin'] = ($showRegulations) ? 0 : 1;
$data = array(
static::ACTIONURL => $this->apiURL,
static::FIELDS => $config,
);
$form = Util::parseTemplate($this->templateDir . static::PAYMENTFORM, $data);
$data = array(
'merchant_id' => $this->merchantId,
'regulation_url' => $this->regulationURL,
'show_regulations_checkbox' => $showRegulations,
'form' => $form
);
if ($smallList) {
$templateFile = 'bankSelectionList';
} else {
$templateFile = 'bankSelection';
}
return Util::parseTemplate($this->templateDir . $templateFile, $data);
}
/**
* Create HTML form for payment with blik selection based on transaction config
* More information about config fields @see Validate::$blikPaymentRequestFields
*
* @param string $alias alias of registered user for One Click transactions
*
* @return string
*
* @throws TException
*/
public function getBlikSelectionForm()
{
$data = array(
'regulation_url' => $this->regulationURL,
);
return Util::parseTemplate($this->templateDir . 'blikForm', $data);
}
/**
* Check md5 sum to confirm value of payment amount
*
* @param string $md5sum md5 sum received from tpay
* @param string $transactionId transaction id
* @param string $transactionAmount transaction amount
* @param string $crc transaction crc
*
* @throws TException
*/
public function validateSign($md5sum, $transactionId, $transactionAmount, $crc)
{
if ($md5sum !== md5($this->merchantId . $transactionId . $transactionAmount . $crc . htmlspecialchars_decode($this->merchantSecret))) {
throw new TException('Invalid checksum');
}
}
}

View File

@@ -0,0 +1,572 @@
<?php
/*
* Created by tpay.com
*/
namespace tpay;
/**
* Class PaymentCard
*
* Class handles credit card payments through "Card API".
* Depending on the chosen method:
* - client is redirected to card payment panel
* - card gate form is rendered
* - when user has saved card data only button is shown
*
* @package tpay
*/
class PaymentCard
{
const RESULT = 'result';
const ORDERID = 'order_id';
const STRING = 'string';
const SALE_AUTH = 'sale_auth';
const REMOTE_ADDR = 'REMOTE_ADDR';
/**
* Card API key
* @var string
*/
private $apiKey = '[CARD_API_KEY]';
/**
* Card API password
* @var string
*/
private $apiPass = '[CARD_API_PASSWORD]';
/**
* Card API code
* @var string
*/
private $code = '[CARD_API_CODE]';
/**
* Card RSA key
* @var string
*/
private $keyRSA = '[CARD_RSA_KEY]';
/**
* Card hash algorithm
* @var string
*/
private $hashAlg = '[CARD_HASH_ALG]';
/**
* Currency code
* @var string
*/
private $currency = '985';
/**
* tpay payment url
* @var string
*/
private $apiURL = 'https://secure.tpay.com/cards/';
/**
* tpay response IP
* @var string
*/
private $secureIP = array(
'176.119.38.175',
'195.149.229.109',
'148.251.96.163',
'178.32.201.77',
'46.248.167.59',
'46.29.19.106',
);
/**
* If false library not validate tpay server IP
* @var bool
*/
private $validateServerIP = true;
/**
* PaymentCard class constructor for payment:
* - card by panel
* - card direct sale
* - for saved cards
*
* @param string|bool $apiKey card api key
* @param string|bool $apiPass card API password
* @param string|bool $code card API code
* @param string|bool $hashAlg card hash algorithm
* @param string|bool $keyRSA card RSA key
*/
public function __construct(
$apiKey = false,
$apiPass = false,
$code = false,
$hashAlg = false,
$keyRSA = false
) {
if ($apiKey !== false) {
$this->apiKey = $apiKey;
}
if ($apiPass !== false) {
$this->apiPass = $apiPass;
}
if ($code !== false) {
$this->code = $code;
}
if ($hashAlg !== false) {
$this->hashAlg = $hashAlg;
}
if ($keyRSA !== false) {
$this->keyRSA = $keyRSA;
}
require_once(dirname(__FILE__) . '/Util.php');
Util::loadClass('Validate');
Util::loadClass('Exception');
Util::loadClass('Lang');
Util::checkVersionPHP();
Validate::validateCardApiKey($this->apiKey);
Validate::validateCardApiPassword($this->apiPass);
Validate::validateCardCode($this->code);
Validate::validateCardHashAlg($this->hashAlg);
Validate::validateCardRSAKey($this->keyRSA);
Util::loadClass('CardApi');
}
/**
* Disabling validation of payment notification server IP
* Validation of tpay server ip is very important.
* Use this method only in test mode and be sure to enable validation in production.
*/
public function disableValidationServerIP()
{
$this->validateServerIP = false;
}
/**
* Enabling validation of payment notification server IP
*/
public function enableValidationServerIP()
{
$this->validateServerIP = true;
}
/**
* Create HTML form for panel payment based on transaction config
* More information about config fields @see Validate::$cardPaymentRequestFields
*
* @param array $config transaction config
*
* @return string
*
* @throws TException
*/
public function getTransactionForm($config)
{
$config = Validate::validateConfig(Validate::PAYMENT_TYPE_CARD, $config);
$curr = isset($config['currency']) ? $config['currency'] : $this->currency;
$api = new CardAPI($this->apiKey, $this->apiPass, $this->code, $this->hashAlg);
$apiResponse = $api->registerSale(
$config['name'],
$config['email'],
$config['desc'],
$config['amount'],
$curr,
$config[static::ORDERID]
);
Util::log('card register sale', print_r($apiResponse, true));
if (!is_array($apiResponse)
||
!isset($apiResponse[static::RESULT])
||
!isset($apiResponse[static::SALE_AUTH])
) {
throw new TException('Invalid api response code');
}
$data = array(
'action_url' => $this->apiURL,
static::SALE_AUTH => $apiResponse[static::SALE_AUTH],
);
return Util::parseTemplate('card/_tpl/paymentForm', $data);
}
public function getTransactionUrl(
$name,
$email,
$description,
$amount,
$currency,
$orderId = '',
$oneTimer = false,
$language = 'pl',
$powUrl = '',
$powUrlBlad = ''
)
{
$api = new CardAPI($this->apiKey, $this->apiPass, $this->code, $this->hashAlg);
return $api->registerSale(
$name,
$email,
$description,
$amount,
$currency,
$orderId,
$oneTimer,
$language,
true,
$powUrl,
$powUrlBlad
);
}
/**
* Check cURL request from tpay server after payment.
* This method check server ip, required fields and md5 checksum sent by payment server.
* Display information to prevent sending repeated notifications.
*
* @param bool $proxy
* @return mixed
* @throws TException
*/
public function handleNotification($proxy)
{
Util::log('card handle notification', print_r($_POST, true));
$notificationType = Util::post('type', static::STRING);
if ($notificationType === 'sale' || $notificationType === 'refund') {
$response = Validate::getResponse(Validate::PAYMENT_TYPE_CARD);
} elseif ($notificationType === 'deregister') {
$response = Validate::getResponse(Validate::CARD_DEREGISTER);
} else {
throw new TException('Unknown notification type');
}
if ($this->validateServerIP === true && $this->checkServer($proxy) === false) {
throw new TException('Request is not from secure server');
}
echo json_encode(array(static::RESULT => '1'));
if (in_array($notificationType, array('sale', 'refund', 'deregister'))) {
return $response;
} else {
throw new TException('Incorrect payment');
}
}
/**
* Check if request is called from secure tpay server
*
* @param bool $allowProxy
* @return bool
*/
private function checkServer($allowProxy)
{
if (isset($_SERVER[static::REMOTE_ADDR]) && in_array($_SERVER[static::REMOTE_ADDR], $this->secureIP)) {
return true;
}
if ($allowProxy && isset($_SERVER['HTTP_X_FORWARDED_FOR'])) {
$proxyIps = explode(',', $_SERVER['HTTP_X_FORWARDED_FOR']);
if (in_array($proxyIps[0], $this->secureIP)) {
return true;
}
}
if ($allowProxy && isset($_SERVER['HTTP_CF_CONNECTING_IP']) && in_array($_SERVER['HTTP_CF_CONNECTING_IP'],
$this->secureIP)
) {
return true;
}
return false;
}
/**
* Get HTML form for direct sale gate. Using for payment in merchant shop
*
* @param string $staticFilesURL path to library static files
* @param string $paymentRedirectPath payment redirect path
*
* @param bool $cardSaveAllowed
* @return string
* @throws TException
*/
public function getDirectCardForm(
$staticFilesURL = '',
$paymentRedirectPath = 'index.html',
$cardSaveAllowed = true
) {
if (!is_string($this->keyRSA) || $this->keyRSA === '') {
throw new TException('Invalid api response code');
}
$data = array(
'rsa_key' => $this->keyRSA,
'static_files_url' => $staticFilesURL,
'payment_redirect_path' => $paymentRedirectPath,
'card_save_allowed' => $cardSaveAllowed
);
return Util::parseTemplate('card/_tpl/gate', $data);
}
/**
* Get HTML form for saved card transaction. Using for payment in merchant shop
*
* @param string $cliAuth client auth sign form prev payment
* @param string $desc transaction description
* @param float $amount amount
* @param string $confirmationUrl url to send confirmation
* @param string $orderId order id
* @param string $language language
* @param string $currency currency
*
* @return string
*
* @throws TException
*/
public function getCardSavedForm(
$cliAuth,
$desc,
$amount,
$confirmationUrl,
$orderId = '',
$language = 'pl',
$currency = '985'
) {
$api = new CardAPI($this->apiKey, $this->apiPass, $this->code, $this->hashAlg);
$resp = $api->presale($cliAuth, $desc, $amount, $currency, $orderId, $language);
Util::log('Card saved presale response', print_r($resp, true));
if ((int)$resp[static::RESULT] === 1) {
$data = array(
static::SALE_AUTH => $resp[static::SALE_AUTH],
'confirmation_url' => $confirmationUrl,
static::ORDERID => $orderId
);
return Util::parseTemplate('card/_tpl/savedCard', $data);
} else {
throw new TException('Order data is invalid');
}
}
/**
* Card direct sale. Handle request from card gate form in merchant site
* from method getDirectCardForm
* Validate transaction config and all input fields
*
* @param float $orderAmount amount of payment
* @param int $orderID order id
* @param string $orderDesc order description
* @param string $currency transaction currency
*
* @return bool|mixed
*
* @throws TException
*/
public function directSale($orderAmount, $orderID, $orderDesc, $currency = '985')
{
$cardData = Util::post('card_data', static::STRING);
$clientName = Util::post('client_name', static::STRING);
$clientEmail = Util::post('client_email', static::STRING);
$saveCard = Util::post('card_save', static::STRING);
Util::log('Card direct post params', print_r(INPUT_POST, true));
$oneTimeTransaction = ($saveCard !== 'on');
$amount = number_format(str_replace(array(',', ' '), array('.', ''), $orderAmount), 2, '.', '');
$amount = (float)$amount;
$api = new CardAPI($this->apiKey, $this->apiPass, $this->code, $this->hashAlg);
$tmpConfig = array(
'amount' => $amount,
'name' => $clientName,
'email' => $clientEmail,
'desc' => $orderDesc,
static::ORDERID => $orderID,
);
Validate::validateConfig(Validate::PAYMENT_TYPE_CARD_DIRECT, $tmpConfig);
$currency = Validate::validateCardCurrency($currency);
$response = $api->directSale(
$clientName,
$clientEmail,
$orderDesc,
$amount,
$cardData,
$currency,
$orderID,
$oneTimeTransaction
);
Util::log('card direct sale response', print_r($response, true));
return $response;
}
public function secureSale(
$orderAmount,
$orderID,
$orderDesc,
$currency = '985',
$enablePowUrl = false,
$language = 'pl',
$powUrl = '',
$powUrlBlad = '',
$module = null
) {
$cardData = Util::post('card_data', static::STRING);
$clientName = Util::post('client_name', static::STRING);
$clientEmail = Util::post('client_email', static::STRING);
$saveCard = Util::post('card_save', static::STRING);
Util::log('Card secureSale post params', print_r($_POST, true));
$oneTimeTransaction = ($saveCard !== 'on');
$amount = number_format(str_replace(array(',', ' '), array('.', ''), $orderAmount), 2, '.', '');
$amount = (float)$amount;
$api = new CardAPI($this->apiKey, $this->apiPass, $this->code, $this->hashAlg);
$tmpConfig = array(
'amount' => $amount,
'name' => $clientName,
'email' => $clientEmail,
'desc' => $orderDesc,
static::ORDERID => $orderID,
'enable_pow_url' => $enablePowUrl,
'pow_url' => $powUrl,
'pow_url_blad' => $powUrlBlad
);
Validate::validateConfig(Validate::PAYMENT_TYPE_CARD_DIRECT, $tmpConfig);
$currency = Validate::validateCardCurrency($currency);
$response = $api->secureSale(
$clientName,
$clientEmail,
$orderDesc,
$amount,
$cardData,
$currency,
$orderID,
$oneTimeTransaction,
$language,
$enablePowUrl,
$powUrl,
$powUrlBlad,
$module
);
Util::log('card secure sale response', print_r($response, true));
return $response;
}
/**
* Register sale for client saved card
*
* @param string $cliAuth client auth sign
* @param string $saleAuth client sale sign
*
* @return bool|mixed
*/
public function cardSavedSale($cliAuth, $saleAuth)
{
$api = new CardAPI($this->apiKey, $this->apiPass, $this->code, $this->hashAlg);
$response = $api->sale($cliAuth, $saleAuth);
Util::log('Sale response', print_r($response, true));
return $response;
}
/**
* Get HTML form for saved card transaction. Using for payment in merchant shop
*
* @param string $cliAuth client auth sign form prev payment
* @param string $desc transaction description
* @param float $amount amount
* @param string $orderId order id
* @param string $language language
* @param string $currency currency
*
* @return string
*
* @throws TException
*/
public function getPresaleTransaction(
$cliAuth,
$desc,
$amount,
$orderId = '',
$language = 'pl',
$currency = '985')
{
$api = new CardAPI($this->apiKey, $this->apiPass, $this->code, $this->hashAlg);
$response = $api->presale($cliAuth, $desc, $amount, $currency, $orderId, $language);
Util::log('Presale response', print_r($response, true));
return $response;
}
/**
* Check md5 sum to validate tpay response.
* The values of variables that md5 sum includes are available only for
* merchant and tpay system.
*
* @param string $sign
* @param string $saleAuth
* @param string $card
* @param float $amount
* @param string $saleDate
* @param $status
* @param string $currency
* @param string $testMode
* @param string $orderId
* @param string $type
* @param string $saleRef
* @param string $cliAuth
* @param string $reason
* @throws TException
*/
public function validateSign(
$sign,
$saleAuth,
$card,
$amount,
$saleDate,
$status,
$currency = '985',
$testMode = '',
$orderId = '',
$type = 'sale',
$saleRef = '',
$cliAuth = '',
$reason = ''
) {
$hash = hash($this->hashAlg, $type . $testMode . $saleAuth . $saleRef . $orderId . $cliAuth . $card .
$currency . $amount . $saleDate . $status . $reason . $this->code);
if ($sign !== $hash) {
Util::log('sum', $type . $testMode . $saleAuth . $saleRef . $orderId . $cliAuth . $card .
$currency . $amount . $saleDate . $status . $reason . $this->code);
throw new TException('Card payment - invalid checksum');
}
}
}

View File

@@ -0,0 +1,126 @@
<?php
/*
* Created by tpay.com
*/
namespace tpay;
/**
* Class PaymentDAC
*
* Class handles DAC payment. System generate account number where client should send funds.
*
* @package tpay
*/
class PaymentDAC
{
/**
* Merchant id
* @var int
*/
private $merchantId = '[MERCHANT_ID]';
/**
* Merchant secret
* @var string
*/
private $merchantSecret = '[MERCHANT_SECRET]';
/**
* Transaction API key
* @var string
*/
private $apiKey = '[TRANSACTION_API_KEY]';
/**
* Transaction API password
* @var string
*/
private $apiPass = '[TRANSACTION_API_PASS]';
/**
* DAC payment chanel
* @var int
*/
private $channelDAC = 29;
/**
* PaymentBasic class constructor
*
* @param string|bool $merchantId merchant id
* @param string|bool $merchantSecret merchant secret
* @param string|bool $apiKey transaction API key
* @param string|bool $apiPass transaction API password
*/
public function __construct($merchantId = false, $merchantSecret = false, $apiKey = false, $apiPass = false)
{
if($merchantId !== false) {
$this->merchantId = $merchantId;
}
if($merchantSecret !== false) {
$this->merchantSecret = $merchantSecret;
}
if($apiKey !== false) {
$this->apiKey = $apiKey;
}
if($apiPass !== false) {
$this->apiPass = $apiPass;
}
require_once(dirname(__FILE__) . '/Util.php');
Util::loadClass('Validate');
Util::loadClass('Exception');
Util::loadClass('Lang');
Util::loadClass('TransactionApi');
Util::checkVersionPHP();
Validate::validateMerchantId($this->merchantId);
Validate::validateMerchantSecret($this->merchantSecret);
}
/**
* Register new DAC transaction and create HTML block with information
* about transaction and merchant data
*
* @param array $config transaction config
* @param string $staticFilesURL static files url
* @param string $merchantData merchant data
*
* @return array
*/
public function registerTransaction($config, $staticFilesURL = '', $merchantData = '')
{
$api = new TransactionAPI($this->apiKey, $this->apiPass, $this->merchantId, $this->merchantSecret);
$config['kanal'] = $this->channelDAC;
$transactionData = $api->create($config);
$transactionData['crc'] = $config['crc'];
return array(
'html' => $this->getConfirmationBlock($transactionData, $staticFilesURL, $merchantData),
'data' => $transactionData
);
}
/**
* Get HTML string with confirmation block
*
* @param array $transactionData registered transaction data from tpay server
* @param string $staticFilesURL browser url to library
* @param string $merchantData merchant data to
*
* @return string
*/
private function getConfirmationBlock($transactionData, $staticFilesURL, $merchantData)
{
$data = array(
'static_files_url' => $staticFilesURL,
'merchant_data' => $merchantData,
'transaction' => $transactionData
);
return Util::parseTemplate('dac/_tpl/confirmation', $data);
}
}

View File

@@ -0,0 +1,61 @@
<?php
/*
* Created by tpay.com
*/
namespace tpay;
/**
* Class PaymentSMS
*
* @package tpay
*/
class PaymentSMS
{
/**
* Url to verify SMS code
* @var string
*/
private $secureURL = 'http://sms.tpay.com/widget/verifyCode.php';
/**
* PaymentSMS class constructor
*/
public function __construct()
{
require_once(dirname(__FILE__) . '/Util.php');
Util::checkVersionPHP();
Util::loadClass('Curl');
}
/**
* Get code sent by from tpay SMS widget.
* Validate code by sending cURL to tpay server.
*
* @return bool
*
* @throws TException
*/
public function verifyCode()
{
$codeToCheck = Util::post('tfCodeToCheck', 'string');
$hash = Util::post('tfHash', 'string');
if ($codeToCheck === false || $hash === false) {
throw new TException('Invalid input data');
}
$postData = array(
'tfCodeToCheck' => $codeToCheck,
'tfHash' => $hash,
);
$response = Curl::doCurlRequest($this->secureURL, $postData);
$data = explode("\n", $response);
$status = (int)$data[0];
return (bool)$status;
}
}

View File

@@ -0,0 +1,490 @@
<?php
/*
* Created by tpay.com
*/
namespace tpay;
/**
* Class PaymentSzkwal
*
* SZKWał (Virtual Accounts Recharge System) was designed to simplify the payment process for the client.
* Instead of traditional payment gateway, client makes a payment with fixed
* title directly from his online
* banking without the necessity of multiple redirections through various pages. SZKWał recognizes such
* payments and notifies the partner system.
*
* @package tpay
*/
class PaymentSzkwal
{
const APILOGIN = 'api_login';
const APIPASS = 'api_password';
const DATE = 'Y-m-d';
const TITLE = 'title';
const INVALIDRESPONSE = 'Invalid server response';
const AMOUNT = 'amount';
/**
* API login
* @var string
*/
protected $apiLogin = '[SZKWAL_LOGIN]';
/**
* API password
* @var string
*/
protected $apiPass = '[SZKWAL_API_PASSWORD]';
/**
* API hash
* @var string
*/
protected $apiHash = '[SZKWAL_API_HASH]';
/**
* API partner unique address
* @var string
*/
protected $partnerUniqueAddress = '[SZKWAL_PARTNER_ADDRESS]';
/**
* API title format
* @var string
*/
protected $titleFormat = '[SZKWAL_TITLE_FORMAT]';
/**
* tpay payment url
* @var string
*/
protected $apiUrl = 'https://szkwal.tpay.com/';
/**
* The list of possible errors returning from tpay servive
* @var array
*/
protected $errorCodes = array(
'ERR01' => 'authorization failed',
'ERR02' => 'required input empty',
'ERR03' => 'incorrect title format',
'ERR04' => 'title busy',
'ERR05' => 'incorrect hash',
'ERR06' => 'no such client',
'ERR07' => 'malformed CSV',
'ERR08' => 'no such package',
'ERR09' => 'incorrect host',
'ERR10' => 'incorrect email',
'ERR11' => 'incorrect dates',
'ERR12' => 'incorrect amount',
'ERR13' => 'no such method',
'ERR14' => 'Insufficient funds',
'ERR15' => 'Incorrect client account number',
'ERR99' => 'other error',
);
/**
* PaymentSzkwal class constructor
*
* @param string|bool $apiLogin API login
* @param string|bool $apiPass API password
* @param string|bool $apiHash API hash
* @param string|bool $partnerUniqueAddress API partner unique address
* @param string|bool $titleFormat API title format
*/
public function __construct($apiLogin = false, $apiPass = false, $apiHash = false,
$partnerUniqueAddress = false, $titleFormat = false)
{
if ($apiLogin !== false) {
$this->apiLogin = $apiLogin;
}
if ($apiPass !== false) {
$this->apiPass = $apiPass;
}
if ($apiHash !== false) {
$this->apiHash = $apiHash;
}
if ($partnerUniqueAddress !== false) {
$this->partnerUniqueAddress = $partnerUniqueAddress;
}
if ($titleFormat !== false) {
$this->titleFormat = $titleFormat;
}
require_once(dirname(__FILE__) . '/Util.php');
Util::loadClass('Curl');
Util::loadClass('Exception');
Util::loadClass('Validate');
Util::loadClass('Lang');
Util::checkVersionPHP();
}
/**
* Register a new client (method RegisterClient) - or update his data with UpdateClient . This method has to
* be used before Client makes his first payment. Bellow we will register a new customer Jan Nowak and his
* dedicated constant payment title, together with his bank account number. If Client will make a payment with
* incorrect title, SZKWAL can automatically connect the payment from that bank account to this Client.
*
* @param string $clientName customer name; up to 96 alphanumeric characters;
* @param string $clientEmail customer e-mail; up to 128 alphanumeric characters, must be a valid e-mail address;
* @param int $clientPhone customer phone; up to 32 numeric characters;
* @param string $crc optional field sent in notifications; up to 64 characters;
* @param int $clientAccount client account number; 26 digits
*
* @throws TException
*
* @return array
*/
public function registerClient($clientName, $clientEmail, $clientPhone, $crc, $clientAccount)
{
$title = $this->generateTitle();
Util::log('SZKWal register client sha1 params', print_r(array(
'cli_name' => $clientName,
'cli_mail' => $clientEmail,
'cli_phone' => $clientPhone,
static::TITLE => $title,
'crc' => $crc,
'account' => $clientAccount,
'apiHash' => $this->apiHash,
), true));
$sha1 = sha1($clientName . $clientEmail . $clientPhone . $title . $crc . $clientAccount . $this->apiHash);
$postData = array(
static::APILOGIN => $this->apiLogin,
static::APIPASS => $this->apiPass,
'cli_name' => $clientName,
'cli_email' => $clientEmail,
'cli_phone' => $clientPhone,
static::TITLE => $title,
'crc' => $crc,
'cli_account' => $clientAccount,
'hash' => $sha1,
);
Validate::validateConfig(Validate::PAYMENT_TYPE_SZKWAL, $postData);
$res = $this->request('RegisterClient', $postData);
$this->checkError($res);
preg_match_all('/([0-9]*)/', $res, $matchesCliId);
if (isset($matchesCliId[1]) && isset($matchesCliId[1][0])) {
$clientID = (int)$matchesCliId[1][0];
} else {
throw new TException(static::INVALIDRESPONSE);
}
return array(
'client_id' => $clientID,
static::TITLE => $title,
);
}
/**
* Generate new unique title
*
* @return string
* @todo
*/
public static function generateTitle()
{
return 'KIP' . substr(time(), 1);
}
/**
* Send API request
*
* @param string $method method name
* @param array $postData post data
*
* @return mixed
*/
protected function request($method, $postData)
{
$url = $this->apiUrl . $this->partnerUniqueAddress . '/' . $method;
return Curl::doCurlRequest($url, $postData);
}
/**
* Check for error presence in response
*
* @param string $response
*
* @throws TException
*/
protected function checkError($response)
{
preg_match_all('/(ERR[0-9]*)/', $response, $matchesError);
if (isset($matchesError[1]) && isset($matchesError[1][0])) {
$errorCode = $matchesError[1][0];
throw new TException($this->errorCodes[$errorCode]);
}
}
/**
* Create HTML confirmation block with transaction info and merchant data
*
* @param string $title transaction title
* @param bool|float $amount transaction amount
* @param string $staticFilesURL static file URL
* @param string $merchantData merchant data to display
*
* @return string
*
* @throws TException
*/
public function getConfirmationBlock($title, $amount = false, $staticFilesURL = '', $merchantData = '')
{
$data = array(
static::TITLE => $title,
'banks' => $this->getBanks(),
static::AMOUNT => $amount,
'static_files_url' => $staticFilesURL,
'merchant_data' => $merchantData
);
return Util::parseTemplate('szkwal/_tpl/confirmation', $data);
}
/**
* Method used to receive information about all available bank channels.
*
* @throws TException
*
* @return mixed
*/
public function getBanks()
{
$postData = array(
static::APILOGIN => $this->apiLogin,
static::APIPASS => $this->apiPass,
);
$res = $this->request('GetBanksData', $postData);
$this->checkError($res);
preg_match_all('/(.*)/', $res, $matches);
if (isset($matches[1]) && isset($matches[1][0])) {
$data = json_decode($matches[1][0], true);
foreach ($data as &$d) {
$d['availability'] = json_decode($d['availability'], true);
}
} else {
throw new TException(static::INVALIDRESPONSE);
}
return $data;
}
/**
* Method used to change result URL where payment notifications will be send.
*
* @param string|bool $notifyURL notify url
*
* @throws TException
*
* @return bool
*/
public function changeSellerData($notifyURL)
{
$sha1 = sha1($notifyURL . $this->apiHash);
$postData = array(
static::APILOGIN => $this->apiLogin,
static::APIPASS => $this->apiPass,
'notify_url' => $notifyURL,
'hash' => $sha1,
);
$res = $this->request('ChangeSellerData', $postData);
$this->checkError($res);
if (strpos($res, 'correct') !== -1) {
return true;
} else {
throw new TException(static::INVALIDRESPONSE);
}
}
/**
* Method used to block/unblock payments for specific client.
*
* @param string $title client title according to agreed format
* @param int $status Type 1 to enable client, 0 to disable
*
* @return bool
*/
public function clientStatus($title, $status)
{
$sha1 = sha1($title . $status . $this->apiHash);
$postData = array(
static::APILOGIN => $this->apiLogin,
static::APIPASS => $this->apiPass,
static::TITLE => $title,
'status' => $status,
'hash' => $sha1,
);
return $this->request('ClientStatus', $postData);
}
/**
* Method sed to acquire report of incoming payments. Depending on input parameters, the function can
* return a list of payments for one client (providing cli_id or title) or list of all payments in the specified
* period.
*
* @param int $clientId
* @param string $title
* @param int $startTime time in unix timestamp format
* @param int|bool $endTime time in unix timestamp format, if false than now
*
* @return array
*/
public function paymentsReport($clientId, $title, $startTime, $endTime = false)
{
$postData = array(
static::APILOGIN => $this->apiLogin,
static::APIPASS => $this->apiPass,
);
$postData['from'] = date(static::DATE, $startTime);
if ($clientId !== false) {
$postData['cli_id'] = $clientId;
}
if ($title !== false) {
$postData[static::TITLE] = $title;
}
$endTime = ($endTime !== false) ? $endTime : time();
$postData['to'] = date(static::DATE, $endTime);
$postData['hash'] = sha1(
$postData['cli_id'] . $postData[static::TITLE] . $postData['from'] . $postData['to'] . $this->apiHash
);
return $this->request('PaymentsReport', $postData);
}
/**
* Simulate user payment in test mode
* @param string $title client/transaction title
* @param float $amount amount
*
* @return mixed
*/
public function registerIncome($title, $amount)
{
$postData = array(
static::APILOGIN => $this->apiLogin,
static::APIPASS => $this->apiPass,
static::TITLE => $title,
static::AMOUNT => $amount,
);
$postData['hash'] = sha1($title . $amount . $this->apiHash);
return $this->request('RegisterIncome', $postData);
}
/**
* Generate monthly report
*
* @param int $startTime time in unix timestamp format
* @param int|bool $endTime time in unix timestamp format, if false than now
*
* @return array
*/
public function monthlyReport($startTime, $endTime = false)
{
return $this->generateReport('MonthlyReport', $startTime, $endTime);
}
/**
* Generate monthly report
*
* @param string $type generate daily or monthly report
* @param int $startTime time in unix timestamp format
* @param int|bool $endTime time in unix timestamp format, if false than now
*
* @return array
*/
private function generateReport($type, $startTime, $endTime)
{
$postData = array(
static::APILOGIN => $this->apiLogin,
static::APIPASS => $this->apiPass,
);
$postData['from'] = date(static::DATE, $startTime);
if ($endTime !== false) {
$postData['to'] = date(static::DATE, $endTime);
} else {
$postData['to'] = date(static::DATE);
}
$sha1 = sha1($postData['from'] . $postData['to'] . $this->apiHash);
$postData['hash'] = $sha1;
return $this->request($type, $postData);
}
/**
* Generate daily report
*
* @param int $startTime time in unix timestamp format
* @param int|bool $endTime time in unix timestamp format, if false than now
*
* @return array
*/
public function dailyReport($startTime, $endTime = false)
{
return $this->generateReport('DailyReport', $startTime, $endTime);
}
/**
* Handle response from tpay server
* Check all required fields and sh1 check sum
* Parse variables to valid types
*
* @throws TException
*
* @return array
*/
public function handleNotification()
{
Util::log('szkwal notification', print_r(INPUT_POST, true));
$res = Validate::getResponse(Validate::PAYMENT_TYPE_SZKWAL);
echo '<?xml version="1.0" encoding="UTF-8"?>
<data>
<result>correct</result>
</data>';
return $res;
}
/**
* Check md5 sum to confirm tpay response and value of payment amount
*
* @param string $sign sha1 checksum
* @param string $payId unique szkwal payment id
* @param string $notId unique szkwal notification id
* @param string $title payment title in agreed format
* @param string $crc additional client field
* @param float $amount amount of payment
*
* @throws TException
*/
public function validateSign($sign, $payId, $notId, $title, $crc, $amount)
{
Util::log('Szkwal sign check components', print_r(array(
'sign' => $sign,
'payId' => $payId,
'noti_id' => $notId,
static::TITLE => $title,
'crc' => $crc,
static::AMOUNT => $amount,
'hash' => $this->apiHash,
), true));
$amount = number_format($amount, 2, '.', '');
if ($sign !== sha1($payId . $notId . $title . $crc . $amount . $this->apiHash)) {
throw new TException('invalid checksum');
}
}
}

View File

@@ -0,0 +1,154 @@
<?php
/*
* Created by tpay.com
*/
namespace tpay;
/**
* Class PaymentWhiteLabel
*
* @package tpay
*/
class PaymentWhiteLabel extends PaymentSzkwal
{
const APILOGIN = 'api_login';
const APIPASS = 'api_password';
/**
* PaymentWhiteLabel class constructor
*
* @param string|bool $apiLogin API login
* @param string|bool $apiPass API password
* @param string|bool $apiHash API hash
* @param string|bool $partnerUniqueAddress API partner unique address
* @param string|bool $titleFormat API title format
*/
public function __construct($apiLogin = false, $apiPass = false, $apiHash = false,
$partnerUniqueAddress = false, $titleFormat = false)
{
parent::__construct($apiLogin, $apiPass, $apiHash, $partnerUniqueAddress, $titleFormat);
}
/**
* Method used to add new order to the system
*
* @param string $clientName customer name; up to 96 alphanumeric characters
* @param string $clientEmail customer e-mail; up to 128 alphanumeric characters, must be a valid e-mail address
* @param string $clientPhone customer phone; up to 32 numeric characters
* @param float $amount field containing order amount, dot separated, e.g. 123.45
*
* @throws TException
*
* @return string
*/
public function registerOrder($clientName, $clientEmail, $clientPhone, $amount)
{
$title = $this->generateTitle();
$hash = sha1($clientName . $clientEmail . $clientPhone . $title . $amount . $this->apiHash);
$postData = array(
static::APILOGIN => $this->apiLogin,
static::APIPASS => $this->apiPass,
'cli_name' => $clientName,
'cli_email' => $clientEmail,
'cli_phone' => $clientPhone,
'order' => $title,
'amount' => $amount,
'hash' => $hash,
);
Validate::validateConfig(Validate::PAYMENT_TYPE_WHITE_LABEL, $postData);
Util::log('White label request data ', print_r($postData, true));
$res = $this->request('RegisterOrder', $postData);
$this->checkError($res);
Util::log('White label server resp', print_r($res, true));
if (strpos($res, 'correct') !== -1) {
return $title;
} else {
throw new TException('Invalid server response');
}
}
/**
* Method used to acquire report of incoming payments.
* Method returns list of all payments in the specified period.
*
* @param string $order
* @param int $startTime time in unix timestamp format
* @param int|bool $endTime time in unix timestamp format
* @param string $separator
*
* @return mixed
*/
public function paymentsReport($order, $startTime, $endTime = false, $separator = ';')
{
$postData = array(
static::APILOGIN => $this->apiLogin,
static::APIPASS => $this->apiPass,
'order' => $order,
'separator' => $separator,
);
$postData['from'] = date('Y-m-d', (int)$startTime);
$endTime = ($endTime !== false) ? (int)$endTime : time();
$postData['to'] = date('Y-m-d', $endTime);
$postData['hash'] = sha1($order . $postData['from'] . $postData['to'] . $separator . $this->apiHash);
return $this->request('PaymentsReport', $postData);
}
/**
* Get information about all available bank channels.
*
* @throws TException
*
* @return mixed
*/
public function getBanksData()
{
$data = $this->getBanks();
return array(
'data' => $data,
'html' => Util::parseTemplate('white_label/_tpl/bankList', $data),
);
}
/**
* Bank transfer instruction for specific bank id
*
* @param int $bankID bank id
*
* @throws TException
*
* @return string[]
*/
public function getBankInstr($bankID)
{
$postData = array(
static::APILOGIN => $this->apiLogin,
static::APIPASS => $this->apiPass,
'bank_id' => $bankID,
);
$res = $this->request('GetBankInstr', $postData);
preg_match_all('/(.*)/', $res, $matches);
if (isset($matches[1]) && isset($matches[1][0])) {
$instructions = json_decode($matches[1][0], true);
} else {
throw new TException('Invalid server response');
}
$data = array(
'bank_id' => $bankID,
'instructions' => $instructions,
);
return Util::parseTemplate('white_label/_tpl/bankInstruction', $data);
}
}

View File

@@ -0,0 +1,495 @@
<?php
/*
* Created by tpay.com
*/
namespace tpay;
/**
* Class TransactionAPI
*
* Includes group of methods responsible for connection with tpay Transaction API
*
* @package tpay
*/
class TransactionAPI
{
const RESULT = 'result';
const TITLE = 'title';
const ERROR_CODE = 'error_code';
const REPORT = 'report';
const PACK_ID = 'pack_id';
const ERR = 'err';
const AMOUNT = 'amount';
const PACKS = 'packs';
const TRANSFERS = 'transfers';
const ALIAS = 'alias';
const CODE = 'code';
/**
* Api key
* @var string
*/
private $apiKey;
/**
* Api pass
* @var string
*/
private $apiPass;
/**
* Merchant id
* @var int
*/
private $merchantId;
/**
* Merchant secret
* @var string
*/
private $merchantSecret;
/**
* tpay api url
* @var string
*/
private $apiURL = 'https://secure.tpay.com/api/gw/';
/**
* List of errors
* @var array
*/
private $errorCodes = array(
'ERR44' => 'Invalid transaction id',
'ERR51' => 'Can\'t create transaction for this channel',
'ERR52' => 'Error create a transaction, try again later',
'ERR53' => 'Invalid input data',
'ERR54' => 'Transation with this id not exists',
'ERR55' => 'Invalid range or format for dates',
'ERR99' => 'General error',
'ERR98' => 'Login error, invalid key or password',
'ERR97' => 'No metod',
'ERR31' => 'Access disabled',
'ERR32' => 'Access forbidden',
'ERR96' => 'Invalid transaction id or can\'t make refund',
'ERR4' => 'Nie został przesłany plik o rozszerzeniu csv',
'ERR6' => 'Niepoprawna suma kontrolna (sign)',
'ERR7' => 'Niepoprawny format linii',
'ERR8' => 'Niepoprawny format numeru rachunku',
'ERR9' => 'Nazwa odbiorcy nie może być pusta',
'ERR10' => 'Nazwa odbiorcy 1 jest za długa - maks. 35 znaków',
'ERR11' => 'Nazwa odbiorcy 2 jest za długa - maks. 35 znaków',
'ERR12' => 'Nazwa odbiorcy 3 jest za długa - maks. 35 znaków',
'ERR13' => 'Nazwa odbiorcy 4 jest za długa - maks. 35 znaków',
'ERR14' => 'Niepoprawny format kwoty',
'ERR15' => 'Pole tytuł 1 nie może być puste',
'ERR16' => 'Pole tytuł 1 jest za długie - maks. 35 znaków',
'ERR17' => 'Pole tytuł 2 jest za długie - maks. 35 znaków',
'ERR18' => 'Błąd wewnętrzny',
'ERR19' => 'Nie udało się załadować pliku o rozszerzeniu csv',
'ERR20' => 'Błąd przetwarzania przelewów',
'ERR21' => 'Niepoprawny packId lub nie znaleziono paczki',
'ERR22' => 'Błąd przy autoryzacji paczki',
'ERR23' => 'Za mało środków do autoryzacji paczki',
'ERR24' => 'Paczka została już autoryzowana',
);
/**
* PaymentTransactionAPI class constructor
*
* @param string $apiKey api key
* @param string $apiPass api password
* @param int $merchantId merchant id
* @param string $merchantSecret merchant secret
*
* @throws TException
*/
public function __construct($apiKey, $apiPass, $merchantId, $merchantSecret)
{
if (!is_string($apiKey) || strlen($apiKey) === 0) {
throw new TException('Invalid API key');
}
if (!is_string($apiPass) || strlen($apiPass) === 0) {
throw new TException('Invalid API pass');
}
$this->merchantId = $merchantId;
$this->merchantSecret = $merchantSecret;
$this->apiKey = $apiKey;
$this->apiPass = $apiPass;
require_once(dirname(__FILE__) . '/Util.php');
Util::loadClass('Curl');
Util::loadClass('Exception');
Util::loadClass('Validate');
Util::loadClass('Lang');
Util::checkVersionPHP();
Validate::validateMerchantId($this->merchantId);
Validate::validateMerchantSecret($this->merchantSecret);
}
/**
* Create new transaction
* More information about config fields @see Validate::$panelPaymentRequestField
*
* @param array $config transaction config
*
* @return array
*
* @throws TException
*/
public function create($config)
{
$url = $this->apiURL . $this->apiKey . '/transaction/create';
Validate::validateConfig(Validate::PAYMENT_TYPE_BASIC_API, $config);
$config = $this->prepareConfig($config);
Util::log('Transaction create request params', print_r($config, true));
$response = $this->requests($url, $config);
Util::log('Transaction create response', print_r($response, true));
if ($response[static::RESULT] !== 1) {
throw new TException(sprintf('Error in %s', $response['desc']));
}
return $response;
}
/**
* Prepare and validate passed config
*
* @param array $config
*
* @return array
*
* @throws TException
*/
private function prepareConfig($config)
{
$ready = Validate::validateConfig(Validate::PAYMENT_TYPE_BASIC, $config);
$md5Params = array(
$this->merchantId,
$ready['amount'],
$ready['crc'],
htmlspecialchars_decode($this->merchantSecret),
);
$ready['md5sum'] = md5(implode('&', $md5Params));
$ready['id'] = $this->merchantId;
return $ready;
}
/**
* Execute request to tpay transaction API
*
* @param string $url url
* @param array $params post params
*
* @return bool|mixed
*/
private function requests($url, $params)
{
$params['api_password'] = $this->apiPass;
return Curl::doCurlRequest($url, $params);
}
public function handleBlikPayment($params)
{
if (!is_array($params) || count($params) <= 0) {
throw new TException('Invalid or empty input parameters');
}
if (isset($params['code']) && !isset($params['alias'])) {
$params['code'] = (int)$params['code'];
$response = $this->handleBlik(Validate::PAYMENT_TYPE_BLIK_T6STANDARD, $params);
} elseif (isset($params['code']) && isset($params['alias'])) {
$params['code'] = (int)$params['code'];
$response = $this->handleBlik(Validate::PAYMENT_TYPE_BLIK_T6REGISTER, $params);
} else {
$response = $this->handleBlik(Validate::PAYMENT_TYPE_BLIK_ALIAS, $params);
}
switch ($response['result']) {
case 1:
$success = true;
break;
case 0:
if (isset($response[static::ERR]) && $response[static::ERR] === 'ERR82') {
$apps = array();
foreach ($response['availableUserApps'] as $key => $value) {
$apps[] = get_object_vars($value);
}
return $apps;
} else {
$success = false;
}
break;
default:
$success = false;
break;
}
return $success;
}
public function handleBlik($type, $params)
{
$params = Validate::validateConfig($type, $params);
switch ($type) {
case Validate::PAYMENT_TYPE_BLIK_T6STANDARD:
$response = $this->blik($params[self::CODE], $params[static::TITLE]);
break;
case Validate::PAYMENT_TYPE_BLIK_T6REGISTER:
$response = $this->blik($params[self::CODE], $params[static::TITLE], $params[static::ALIAS]);
break;
case Validate::PAYMENT_TYPE_BLIK_ALIAS:
$response = $this->blik('', $params[static::TITLE], $params[static::ALIAS]);
break;
default:
throw new TException('Undefined transaction type!');
}
return $response;
}
public function blik($code = '', $title, $alias = '')
{
if (empty($title) || !is_string($title)) {
throw new TException('Transaction title is empty or invalid');
}
$config['title'] = $title;
if (!empty($code)) {
$config[self::CODE] = $code;
}
if (!empty($alias)) {
$config[self::ALIAS] = $alias;
}
Util::log('Blik request params', print_r($config, true));
$url = $this->apiURL . $this->apiKey . '/transaction/blik';
$response = $this->requests($url, $config);
Util::log('Blik response', print_r($response, true));
return $response;
}
/**
* Get information about transaction
*
* @param string $transactionId transaction id
*
* @return array
*
* @throws TException
*/
public function get($transactionId)
{
$url = $this->apiURL . $this->apiKey . '/transaction/get';
$response = $this->requests($url, array(static::TITLE => $transactionId));
$this->checkError($response);
return $response;
}
/**
* Check api response error
*
* @param array $response
*
* @throws TException
*/
private function checkError($response)
{
if ($response[static::RESULT] !== 1) {
if (isset($response[static::ERR]) && isset($this->errorCodes[$response[static::ERR]])) {
throw new TException($this->errorCodes[$response[static::ERR]]);
} elseif (isset($response[static::ERROR_CODE]) && isset($this->errorCodes[$response[static::ERROR_CODE]])) {
throw new TException($this->errorCodes[$response[static::ERROR_CODE]]);
} else {
throw new TException('Unexpected error');
}
}
}
/**
* Get transactions report
*
* @param string $fromDate start date in format YYYY-MM-DD
* @param string|bool $toDate end date in format YYYY-MM-DD
*
* @return array
*
* @throws TException
*/
public function report($fromDate, $toDate = false)
{
$url = $this->apiURL . $this->apiKey . '/transaction/report';
$postData = array(
'from_date' => $fromDate
);
if ($toDate !== false) {
$postData['to_date'] = $toDate;
}
$response = $this->requests($url, $postData);
$this->checkError($response);
$response[static::REPORT] = base64_decode($response[static::REPORT]);
return $response;
}
/**
* Refund all amount to customer
*
* @param string $transactionId transaction id
*
* @return bool
*
* @throws TException
*/
public function refund($transactionId)
{
$url = $this->apiURL . $this->apiKey . '/chargeback/transaction';
$response = $this->requests($url, array(static::TITLE => $transactionId));
$this->checkError($response);
return true;
}
/**
* Refund custom amount to customer
*
* @param string $transactionId transaction id
* @param float $amount refund amount
*
* @return bool
*
* @throws TException
*/
public function refundAny($transactionId, $amount)
{
$url = $this->apiURL . $this->apiKey . '/chargeback/any';
$postData = array(
static::TITLE => $transactionId,
'chargeback_amount' => $amount,
);
$response = $this->requests($url, $postData);
$this->checkError($response);
return true;
}
/**
* Create mass payment
*
* @param string $csv content of csv file
*
* @return array
* @throws TException
*/
public function masspaymentCreate($csv)
{
$url = $this->apiURL . $this->apiKey . '/masspayment/create';
$csvEncode = base64_encode($csv);
$postData = array(
'csv' => $csvEncode,
'sign' => sha1($this->merchantId . $csv . $this->merchantSecret),
);
$response = $this->requests($url, $postData);
$this->checkError($response);
return $response;
}
/**
* Authorize mass payment
*
* @param string $packId pack id from masspaymentCreate
*
* @return array
* @throws TException
*/
public function masspaymentAuthorize($packId)
{
$url = $this->apiURL . $this->apiKey . '/masspayment/authorize';
$postData = array(
static::PACK_ID => $packId,
);
$response = $this->requests($url, $postData);
$this->checkError($response);
return $response;
}
/**
* Get information about packs
*
* @param string|bool $packId pack id from masspaymentCreate
* @param string|bool $fromDate start date in format YYYY-MM-DD
* @param string|bool $toDate end date in format YYYY-MM-DD
*
* @return array
* @throws TException
*/
public function masspaymentPacks($packId = false, $fromDate = false, $toDate = false)
{
$url = $this->apiURL . $this->apiKey . '/masspayment/packs';
$postData = array();
if ($packId !== false) {
$postData[static::PACK_ID] = $packId;
}
if ($fromDate !== false) {
$postData['fromDate'] = $fromDate;
}
if ($toDate !== false) {
$postData['toDate'] = $toDate;
}
$response = $this->requests($url, $postData);
$this->checkError($response);
$xml = simplexml_load_string($response[static::PACKS]);
$response[static::PACKS] = unserialize(serialize(json_decode(json_encode((array)$xml), 1)));
return $response;
}
/**
* Authorize mass payment
*
* @param string $packId pack id from masspaymentCreate
* @param string $trId transaction id
*
* @return array
* @throws TException
*/
public function masspaymentTransfers($packId, $trId)
{
$url = $this->apiURL . $this->apiKey . '/masspayment/transfers';
$postData = array(
static::PACK_ID => $packId,
'trId' => $trId,
);
$response = $this->requests($url, $postData);
$this->checkError($response);
$xml = simplexml_load_string($response[static::TRANSFERS]);
$response[static::TRANSFERS] = unserialize(serialize(json_decode(json_encode((array)$xml), 1)));
return $response;
}
}

View File

@@ -0,0 +1,178 @@
<?php
/*
* Created by tpay.com
*/
namespace tpay;
/**
* Class Util
*
* Utility class which helps with:
* - parsing template files
* - class loading
* - log library operations
* - handle POST array
*
* @package tpay
*/
class Util
{
const REMOTE_ADDR = 'REMOTE_ADDR';
/**
* Parse template file
* @param string $templateFileName filename
* @return string
*/
public static function parseTemplate($templateFileName, $data = array())
{
$templateDirectory = dirname(__FILE__) . '/../';
$buffer = false;
if (ob_get_length() > 0) {
$buffer = ob_get_contents();
ob_clean();
}
ob_start();
if (!file_exists($templateDirectory . $templateFileName . '.phtml')) {
return '';
}
include_once $templateDirectory . $templateFileName . '.phtml';
$parsedHTML = ob_get_contents();
ob_clean();
if ($buffer !== false) {
ob_start();
echo $buffer;
}
return $parsedHTML;
}
/**
* Checking installed PHP version
*
* @throws TException
*/
public static function checkVersionPHP()
{
if (version_compare(phpversion(), '5.3.0', '<')) {
throw new TException(sprintf('Your PHP version is too old, please upgrade to a newer version.
Your version is %s, library requires %s', phpversion(), '5.3.0'));
}
}
/**
* Require PHP file
*
* @param string $name file name without php extension
*
* @throws TException
*/
public static function loadClass($name)
{
$classDirectory = dirname(__FILE__) . '/../_class_tpay/';
$filePath = $classDirectory . $name . '.php';
if (!file_exists($classDirectory)) {
throw new TException('directory not found (' . $classDirectory . ')');
}
if (!file_exists($filePath)) {
throw new TException('no such a file (' . $filePath . ')');
}
require_once($filePath);
}
/**
* Save text to log file with details
*
* @param string $title action name
* @param string $text $array text to save
*/
public static function log($title, $text)
{
$text = (string)$text;
$logFilePath = dirname(__FILE__) . '/../log.php';
$ip = (isset($_SERVER[static::REMOTE_ADDR])) ? $_SERVER[static::REMOTE_ADDR] : '';
$logText = "\n===========================";
$logText .= "\n" . $title;
$logText .= "\n===========================";
$logText .= "\n" . date('Y-m-d H:i:s');
$logText .= "\nip: " . $ip;
$logText .= "\n";
$logText .= $text;
$logText .= "\n\n";
if (file_exists($logFilePath) && is_writable($logFilePath)) {
file_put_contents($logFilePath, $logText, FILE_APPEND);
}
}
/**
* Save one line to log file
*
* @param string $text text to save
*/
public static function logLine($text)
{
$text = (string)$text;
$logFilePath = dirname(__FILE__) . '/../log.php';
if (file_exists($logFilePath) && is_writable($logFilePath)) {
file_put_contents($logFilePath, "\n" . $text, FILE_APPEND);
}
}
/**
* Get value from $_POST array.
* If not exists return false
*
* @param string $name
* @param string $type variable type
*
* @return mixed
* @throws TException
*/
public static function post($name, $type)
{
if (!isset($_POST[$name])) {
return false;
}
$val = $_POST[$name];
if ($type === 'int') {
$val = (int)$val;
} elseif ($type === 'float') {
$val = (float)$val;
} elseif ($type === 'string') {
$val = (string)$val;
} elseif ($type === 'array') {
$val = (array)$val;
} else {
throw new TException('Undefined $_POST variable type');
}
return $val;
}
/**
* Get substring by pattern
*
* @param string $pattern pattern
* @param string $string content
*
* @return string
*/
public static function findSubstring($pattern, $string)
{
preg_match_all($pattern, $string, $matches);
if (isset($matches[1]) && isset($matches[1][0])) {
return $matches[1][0];
}
return '';
}
}

View File

@@ -0,0 +1,249 @@
.chromeframe {
position: absolute;
top: 0;
}
#card_payment select, input, textarea {
color: #333;
-moz-box-sizing: border-box;
-webkit-box-sizing: border-box;
box-sizing: border-box;
}
ins {
background-color: #fcd700;
color: #000;
text-decoration: none;
}
mark {
background-color: #fcd700;
color: #000;
font-style: italic;
font-weight: bold;
}
input:-moz-placeholder {
color: #a9a9a9;
}
textarea:-moz-placeholder {
color: #a9a9a9;
}
#powered_by {
max-width: 25em;
height: 3em;
margin: 10px;
background: url(../../common/_img/powered_by_tpay.png);
background-size: 170px 33px;
background-repeat: no-repeat;
margin-bottom: 1em;
}
#card_icons {
max-width: 27em;
margin-top: 2em;
text-align: center;
}
#card_icons .card_icon {
display: inline-block;
width: 44px;
height: 30px;
margin: 0 3px;
opacity: 0.6;
background-image: url(../../common/_img/cards.png);
background-size: 320px;
}
#card_icons .card_icon.hover {
opacity: 1;
}
#card_icons #visa {
background-position: 0px center;
}
#card_icons #visaele {
background-position: -46px center;
}
#card_icons #master {
background-position: -91px center;
}
#card_icons #maestro {
background-position: -139px center;
}
#card_icons #amex {
background-position: -184px center;
}
#card_icons #diners {
background-position: -230px center;
}
#card_icons #jcb {
background-position: -276px center;
}
#card_payment {
max-width: 25em;
background: #3787cc;
background: -moz-linear-gradient(top, #3787cc 0%, #3875c9 100%);
background: -webkit-linear-gradient(top, #3787cc 0%, #3875c9 100%);
background: -o-linear-gradient(top, #3787cc 0%, #3875c9 100%);
background: -ms-linear-gradient(top, #3787cc 0%, #3875c9 100%);
background: linear-gradient(to bottom, #3787cc 0%, #3875c9 100%);
border: 2px solid rgba(0, 0, 0, 0.1);
border-radius: 0.6em;
padding: 1em;
box-shadow: 0px 5px 10px #a2a2a2;
margin-bottom: 2em;
}
#card_payment label {
color: #f6f6f6;
font-size: 1.2em;
margin-top: 8px;
text-shadow: 0px 2px 2px rgba(0, 0, 0, 0.21);
}
#card_payment_form #card_title {
font-size: 1.4em;
font-weight: 700;
padding: 0.5em 0 0.5em 0;
margin: 0;
color: #f6f6f6;
text-shadow: 0px 2px 2px rgba(0, 0, 0, 0.21);
}
#card_payment_form #expiry_date_wrapper {
display: inline-block;
width: 50%;
}
#card_payment_form #expiry_date #transaction_card_expiry_month {
width: 40%;
}
#card_payment_form #expiry_date #transaction_card_expiry_year {
width: 40%;
}
#card_payment_form #expiry_date {
width: 60%;
}
#card_payment_form #cvc_wrapper {
display: inline-block;
width: 40%;
float: right;
}
#card_payment_form input, form #card_payment select {
box-shadow: none;
}
#card_payment_form #part_1, form #part_2 {
display: inline-block;
width: 47%;
}
#card_payment_form #part_1 {
margin-right: 3%;
}
#card_payment_form input[type="text"], input[type="tel"], input[type="email"] form select {
height: 2.8em;
margin: 0.5em 0;
padding: 0.5em 1em;
border: 1px solid #b2b2b2;
border-radius: 0.3em;
box-shadow: 0 1px 3px #dcdcdc;
background: #f9f9f9;
}
#card_payment_form .amPmCheckbox input[type="checkbox"] {
display: none;
}
#card_payment_form .amPmCheckbox input[type="checkbox"] + label {
background: url(../../common/_img/checkbox.png) no-repeat scroll left top transparent;
height: 21px;
width: 22px;
padding-left: 30px;
}
#card_payment_form .amPmCheckbox input[type="checkbox"]:checked + label {
background: url(../../common/_img/checkbox.png) no-repeat scroll left bottom transparent;
height: 21px;
width: 22px;
}
#card_payment_form input.wrong, form select.wrong {
border: 2px solid #ff9696;
box-shadow: 0 1px 3px #dcdcdc;
background: #ffeeee;
}
#card_payment_form p {
padding: 0.5em 0 0.2em 0;
}
#continue_btn {
background-color: #3787cc;
box-shadow: 0px 5px 0px 0px #3875c9;
border-radius: 5px;
padding: 15px 25px;
font-size: 22px;
text-decoration: none;
margin: 20px;
color: #fff;
position: relative;
display: inline-block;
}
#continue_btn:hover {
background-color: #3787cc;
}
#continue_btn:active {
transform: translate(0px, 5px);
-webkit-transform: translate(0px, 5px);
box-shadow: 0px 1px 0px 0px;
}
@media screen and (max-width: 760px) and (max-width: 480px) {
#card_payment #card_payment {
width: 100%;
}
#card_payment #expiry_date_wrapper {
width: 100%;
display: block;
}
#card_payment #cvc_wrapper {
width: 50%;
float: none;
display: block;
}
}
.info_button {
background: rgba(0, 0, 0, 0.35);
border-radius: 50%;
width: 20px;
height: 20px;
display: inline-block;
text-align: center;
color: rgba(255, 255, 255, 0.8);
font-size: 1.1em;
margin-left: 0.5em;
cursor: help;
}

View File

@@ -0,0 +1,75 @@
<?php
/*
* Created by tpay.com
*/
const STATIC_FILES_URL = 'static_files_url';
const CARD_SAVE_ALLOWED = 'card_save_allowed';
?>
<link rel="stylesheet" type="text/css" href="<?php
echo $data[STATIC_FILES_URL] ?>card/_css/gate.css"/>
<form method="post" id="card_payment_form" name="card_payment_form">
<input type="hidden" name="carddata" id="carddata" value=""/>
<div id="powered_by"></div>
<div id="card_payment">
<label for="card_number"><?php tpay\Lang::l('card_number') ?></label>
<input id="card_number" pattern="\d*" autocompletetype="cc-number" size="30" type="tel" autocomplete="off"
maxlength="23" placeholder="0000 0000 0000 0000" tabindex="1" value=""/>
<div id="expiry_date_wrapper">
<label for="transaction_card_expiry_month"><?php tpay\Lang::l('expiration_date') ?></label><br>
<input id="expiry_date" maxlength="9" type="tel" placeholder="00 / 00" autocomplete="off"
autocompletetype="cc-exp" tabindex="2" value=""/>
</div>
<div id="cvc_wrapper">
<label for="cvc">CVC</label><span class="info_button"
title="<?php tpay\Lang::l('signature') ?>">?</span>
<input id="cvc" maxlength="3" type="tel" autocomplete="off" autocompletetype="cc-cvc" placeholder="000"
tabindex="4" value=""/>
</div>
<br>
<label for="c_name"><?php tpay\Lang::l('name_on_card') ?></label>
<input type="tel" id="c_name" placeholder="<?php tpay\Lang::l('name_surname') ?>" autocomplete="off"
name="client_name"
maxlength="64" tabindex="5" value=""/>
<label for="c_email">E-mail</label>
<input type="tel" id="c_email" data-formance_algorithm="complex" autocomplete="off" placeholder="E-mail"
name="client_email" value="" maxlength="64" tabindex="6">
<?php if ($data[CARD_SAVE_ALLOWED]){ ?>
<div class="amPmCheckbox">
<input type="checkbox" id="card_save" name="card_save"/>&nbsp;&nbsp;&nbsp;<label
for="card_save"><?php tpay\Lang::l('save_card') ?></label>
<span class="info_button" title="<?php tpay\Lang::l('save_card_info') ?>">?</span>
</div><?php } ?>
</div>
<div id="card_icons">
<div class="card_icon" id="visa"></div>
<div class="card_icon" id="master"></div>
<div class="card_icon" id="maestro"></div>
<div class="card_icon" id="diners"></div>
<div class="card_icon" id="jcb"></div>
</div>
<p id="info_msg"></p>
<div id="loading_scr" style="display:none">
<img src="<?php echo $data[STATIC_FILES_URL] ?>common/_img/loading.gif"
style="vertical-align: middle;"/>&nbsp;&nbsp;<?php tpay\Lang::l('processing') ?>
</div>
</form>
<button id="continue_btn">&nbsp;<?php tpay\Lang::l('card_payment') ?>&nbsp;</button>
<script type="text/javascript" src="<?php echo $data[STATIC_FILES_URL] ?>common/_js/jquery.min.js"></script>
<script type="text/javascript" src="<?php echo $data[STATIC_FILES_URL] ?>common/_js/jquery.formance.min.js"></script>
<script type="text/javascript" src="<?php echo $data[STATIC_FILES_URL] ?>common/_js/cardpayment.js"></script>
<script type="text/javascript" src="<?php echo $data[STATIC_FILES_URL] ?>common/_js/jsencrypt.min.js"></script>
<script type="text/javascript" src="<?php echo $data[STATIC_FILES_URL] ?>common/_js/string_routines.js"></script>
<script type="text/javascript">
$(document).ready(function () {
new CardPayment('<?php echo $data['payment_redirect_path'] ?>', "<?php echo $data['rsa_key'] ?>");
});
</script>

View File

@@ -0,0 +1,10 @@
<?php
/*
* Created by tpay.com
*/
?><form id="tpay-payment" class="tpay-form" action="<?php echo $data['action_url'] ?>" method="POST">
<input type="hidden" name="sale_auth" value="<?php echo $data['sale_auth'] ?>"/>
<input id="tpay-payment-submit" type="submit" value="<?php tpay\Lang::l('pay') ?>">
</form>

View File

@@ -0,0 +1,11 @@
<?php
/*
* Created by tpay.com
*/
?><form id="tpay-payment" action="<?php echo $data['confirmation_url'] ?>" method="POST">
<input type="hidden" name="sale_auth" value="<?php echo $data['sale_auth'] ?>">
<input type="hidden" name="order_id" value="<?php echo $data['order_id'] ?>">
<button class="tpay" type="submit"><?php tpay\Lang::l('debit') ?></button>
</form>

File diff suppressed because one or more lines are too long

Binary file not shown.

After

Width:  |  Height:  |  Size: 55 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 8.4 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 877 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.4 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 8.6 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.9 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 11 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 19 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 56 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 6.0 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 6.5 KiB

View File

@@ -0,0 +1,100 @@
/**
* Created by tpay.com
*/
var blikResult, button, register = 0, attempt = 0, title;
var buttonDiv = document.getElementById('tpayBlikButton');
var loaderGif = '<img src="https://tpay.com/wp-content/themes/corpress/assets/images/loading.gif">';
var code = document.getElementById("blikcode");
function showHide(ID, bool) {
document.getElementById(ID).style.visibility = bool ? "visible" : "hidden";
}
function showT6() {
showHide("codeFields", true);
showHide("alias", false);
showHide("t6InputMsg", false);
if (code.value !== '') {
attempt = 2;
}
}
function checkRegister() {
var checkbox = document.getElementById("register");
checkbox.value = checkbox.checked ? 1 : 0;
register = checkbox.value;
}
function showAliases() {
var x = document.getElementById("blikSwitch");
for (var i = 1; i < blikResult.length - 1;) {
var option = document.createElement("option");
option.text = blikResult[i];
option.value = blikResult[i + 1];
x.add(option);
i = i + 2
}
showHide("alias", true);
}
function ajax(data) {
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function () {
if (this.readyState === 4 && this.status === 200) {
console.log(xhr.responseText);
blikResult = xhr.responseText.split(",");
}
};
xhr.open("GET", "OneClick.php?" + data, true);
xhr.send();
}
$( document ).ready(function() {
ajax(('getTitle'));
setTimeout(function () {
title = blikResult[0];
}, 5000);
});
function blikHandler() {
// call first function and pass in a callback function which
// first function runs when it has completed
button = buttonDiv.innerHTML;
buttonDiv.innerHTML = loaderGif;
if (attempt === 0) {
ajax('tryOneClick&title=' + title);
setTimeout(function () {
checkResponse();
}, 5000);
} else if (attempt === 1) {
var e = document.getElementById("blikSwitch");
var key = e.options[e.selectedIndex].value;
ajax('aliasKey=' + key + '&title=' + title);
setTimeout(function () {
checkResponse();
}, 5000);
} else {
ajax('code=' + code.value + '&title=' + title + '&register=' + register);
setTimeout(function () {
checkResponse();
}, 5000);
}
}
function checkResponse() {
var i = 0;
if (attempt === 0) {
i = 1;
}
if (blikResult[i] === '1') {
document.getElementById("blikOneClickForm").innerHTML = "<p>SUKCES!</p>";
} else if (blikResult[i] === '0') {
showT6();
attempt = 2;
} else {
alert('alias niejednoznaczny');
showAliases();
attempt = 1;
}
buttonDiv.innerHTML = button;
}

View File

@@ -0,0 +1,130 @@
function CardPayment(url, pubkey) {
this.url = url;
this.pubkey = pubkey;
$("#card_payment_form").attr("action", url);
function SubmitPayment() {
$("#continue_btn").fadeOut();
$("#loading_scr").fadeIn();
var cd = $('#card_number').val() + '|' + $('#expiry_date').val() + '|' + $('#cvc').val() + '|' + document.location.origin;
var encrypt = new JSEncrypt();
var decoded = Base64.decode(pubkey);
encrypt.setPublicKey(decoded);
var encrypted = encrypt.encrypt(cd);
$("#carddata").val(encrypted);
$("#card_number").val('');
$("#cvc").val('');
$("#expiry_date").val('');
$('#card_payment_form').submit();
}
var DINERS = /^(30|36|38)/,
ELECTRON = /^(4026|417500|4508|4844|4913|4917)/,
JCB = /^35(2[8-9]|[3-8])/,
MAESTRO = /^(50(18|20|38)|6304|67(59|6[1-3])|0604)/,
MASTERCARD = /^5[1-5]/,
VISA = /^40([0-1]|2[0-5]|2[7-9]|[3-9])|41([0-6]|7[0-4])|41(75(0[1-9]|[1-9])|7[6-9]|[8-9])|4[2-4]|450[0-7]|4509|45[1-9]|4[6-7]|48[0-3]|484[0-3]|484[5-9]|48[5-9]|490|491[0-2]|491[4-6]|491[8-9]|49[2-9]/;
var goon = false;
$('input#card_number').formance('format_credit_card_number').on('keyup change blur', function (event) {
$('div.card_icon').removeClass('hover');
if (!$(this).formance('validate_credit_card_number')) {
$(this).addClass('wrong');
goon = false;
} else {
$(this).removeClass('wrong');
goon = true;
var type = '';
var cc_number = $(this).val();
if (DINERS.test(cc_number)) {
type = 'diners';
} else if (ELECTRON.test(cc_number) || (VISA.test(cc_number))){
type = 'visa';
} else if (JCB.test(cc_number)) {
type = 'jcb';
} else if (MAESTRO.test(cc_number)) {
type = 'maestro';
} else if (MASTERCARD.test(cc_number)) {
type = 'master';
}
if (type !== '')
$('#' + type).addClass('hover');
}
});
$('input#cvc').formance('format_credit_card_cvc').on('keyup change blur', function (event) {
if (!$(this).formance('validate_credit_card_cvc')) {
$(this).addClass('wrong');
goon = false;
} else
$(this).removeClass('wrong');
});
function validationExpired(mm, yy) {
var today = new Date();
var expiry = new Date();
var expired = false, mm = Math.floor(parseFloat(mm)), yy = Math.floor(parseFloat(yy)) + (Math.floor(today.getFullYear() / 100) * 100);
if (!isNaN(mm) && !isNaN(yy)) {
expiry.setYear(mm === 12 ? yy + 1 : yy);
expiry.setMonth(mm === 12 ? 0 : mm);
expiry.setDate(1);
expiry.setHours(0);
expiry.setMinutes(0);
expiry.setSeconds(0);
expiry.setMilliseconds(0);
expired = !(expiry.getTime() > today.getTime());
}
return expired;
}
$('select#cc_month,select#cc_year').on('keyup change blur', function (event) {
mm = $('#cc_month option:selected').val();
yy = $('#cc_year option:selected').val();
if (validationExpired(mm, yy)) {
$('select#cc_month,select#cc_year').addClass('wrong');
goon = false;
} else
$('select#cc_month,select#cc_year').removeClass('wrong');
});
$('input#expiry_date').formance('format_credit_card_expiry').on('keyup change blur', function (event) {
if (!$(this).formance('validate_credit_card_expiry')) {
$(this).addClass('wrong');
goon = false;
} else
$(this).removeClass('wrong');
});
$('input#c_name').on('keyup change blur', function (event) {
if ($(this).val().length < 3) {
$(this).addClass('wrong');
goon = false;
} else
$(this).removeClass('wrong');
});
$('input#c_email').on('keyup change blur', function (event) {
if (!$(this).formance('validate_email')) {
$(this).addClass('wrong');
goon = false;
} else
$(this).removeClass('wrong');
});
$('#continue_btn').click(function () {
$('input').each(function () {
$(this).trigger('keyup');
});
if (document.getElementById("cc_month"))
$('select#cc_month,select#cc_year').trigger('keyup');
if (goon)
SubmitPayment();
});
}

View File

@@ -0,0 +1,652 @@
// Generated by CoffeeScript 1.7.1
(function() {
var $, cardFromNumber, cardFromType, cards, defaultFormat, formatBackCardNumber, formatBackExpiry, formatCardNumber, formatExpiry, formatForwardExpiry, formatForwardSlashAndSpace, hasTextSelected, luhnCheck, reFormatCVC, reFormatCardNumber, reFormatExpiry, reFormatNumeric, replaceFullWidthChars, restrictCVC, restrictCardNumber, restrictExpiry, restrictNumeric, safeVal, setCardType,
__slice = [].slice,
__indexOf = [].indexOf || function(item) { for (var i = 0, l = this.length; i < l; i++) { if (i in this && this[i] === item) return i; } return -1; };
$ = window.jQuery || window.Zepto || window.$;
$.payment = {};
$.payment.fn = {};
$.fn.payment = function() {
var args, method;
method = arguments[0], args = 2 <= arguments.length ? __slice.call(arguments, 1) : [];
return $.payment.fn[method].apply(this, args);
};
defaultFormat = /(\d{1,4})/g;
$.payment.cards = cards = [
{
type: 'maestro',
patterns: [5018, 502, 503, 506, 56, 58, 639, 6220, 67],
format: defaultFormat,
length: [12, 13, 14, 15, 16, 17, 18, 19],
cvcLength: [3],
luhn: true
}, {
type: 'forbrugsforeningen',
patterns: [600],
format: defaultFormat,
length: [16],
cvcLength: [3],
luhn: true
}, {
type: 'dankort',
patterns: [5019],
format: defaultFormat,
length: [16],
cvcLength: [3],
luhn: true
}, {
type: 'visa',
patterns: [4],
format: defaultFormat,
length: [13, 16],
cvcLength: [3],
luhn: true
}, {
type: 'mastercard',
patterns: [51, 52, 53, 54, 55, 22, 23, 24, 25, 26, 27],
format: defaultFormat,
length: [16],
cvcLength: [3],
luhn: true
}, {
type: 'amex',
patterns: [34, 37],
format: /(\d{1,4})(\d{1,6})?(\d{1,5})?/,
length: [15],
cvcLength: [3, 4],
luhn: true
}, {
type: 'dinersclub',
patterns: [30, 36, 38, 39],
format: /(\d{1,4})(\d{1,6})?(\d{1,4})?/,
length: [14],
cvcLength: [3],
luhn: true
}, {
type: 'discover',
patterns: [60, 64, 65, 622],
format: defaultFormat,
length: [16],
cvcLength: [3],
luhn: true
}, {
type: 'unionpay',
patterns: [62, 88],
format: defaultFormat,
length: [16, 17, 18, 19],
cvcLength: [3],
luhn: false
}, {
type: 'jcb',
patterns: [35],
format: defaultFormat,
length: [16],
cvcLength: [3],
luhn: true
}
];
cardFromNumber = function(num) {
var card, p, pattern, _i, _j, _len, _len1, _ref;
num = (num + '').replace(/\D/g, '');
for (_i = 0, _len = cards.length; _i < _len; _i++) {
card = cards[_i];
_ref = card.patterns;
for (_j = 0, _len1 = _ref.length; _j < _len1; _j++) {
pattern = _ref[_j];
p = pattern + '';
if (num.substr(0, p.length) === p) {
return card;
}
}
}
};
cardFromType = function(type) {
var card, _i, _len;
for (_i = 0, _len = cards.length; _i < _len; _i++) {
card = cards[_i];
if (card.type === type) {
return card;
}
}
};
luhnCheck = function(num) {
var digit, digits, odd, sum, _i, _len;
odd = true;
sum = 0;
digits = (num + '').split('').reverse();
for (_i = 0, _len = digits.length; _i < _len; _i++) {
digit = digits[_i];
digit = parseInt(digit, 10);
if ((odd = !odd)) {
digit *= 2;
}
if (digit > 9) {
digit -= 9;
}
sum += digit;
}
return sum % 10 === 0;
};
hasTextSelected = function($target) {
var _ref;
if (($target.prop('selectionStart') != null) && $target.prop('selectionStart') !== $target.prop('selectionEnd')) {
return true;
}
if ((typeof document !== "undefined" && document !== null ? (_ref = document.selection) != null ? _ref.createRange : void 0 : void 0) != null) {
if (document.selection.createRange().text) {
return true;
}
}
return false;
};
safeVal = function(value, $target) {
var currPair, cursor, digit, error, last, prevPair;
try {
cursor = $target.prop('selectionStart');
} catch (_error) {
error = _error;
cursor = null;
}
last = $target.val();
$target.val(value);
if (cursor !== null && $target.is(":focus")) {
if (cursor === last.length) {
cursor = value.length;
}
if (last !== value) {
prevPair = last.slice(cursor - 1, +cursor + 1 || 9e9);
currPair = value.slice(cursor - 1, +cursor + 1 || 9e9);
digit = value[cursor];
if (/\d/.test(digit) && prevPair === ("" + digit + " ") && currPair === (" " + digit)) {
cursor = cursor + 1;
}
}
$target.prop('selectionStart', cursor);
return $target.prop('selectionEnd', cursor);
}
};
replaceFullWidthChars = function(str) {
var chars, chr, fullWidth, halfWidth, idx, value, _i, _len;
if (str == null) {
str = '';
}
fullWidth = '\uff10\uff11\uff12\uff13\uff14\uff15\uff16\uff17\uff18\uff19';
halfWidth = '0123456789';
value = '';
chars = str.split('');
for (_i = 0, _len = chars.length; _i < _len; _i++) {
chr = chars[_i];
idx = fullWidth.indexOf(chr);
if (idx > -1) {
chr = halfWidth[idx];
}
value += chr;
}
return value;
};
reFormatNumeric = function(e) {
var $target;
$target = $(e.currentTarget);
return setTimeout(function() {
var value;
value = $target.val();
value = replaceFullWidthChars(value);
value = value.replace(/\D/g, '');
return safeVal(value, $target);
});
};
reFormatCardNumber = function(e) {
var $target;
$target = $(e.currentTarget);
return setTimeout(function() {
var value;
value = $target.val();
value = replaceFullWidthChars(value);
value = $.payment.formatCardNumber(value);
return safeVal(value, $target);
});
};
formatCardNumber = function(e) {
var $target, card, digit, length, re, upperLength, value;
digit = String.fromCharCode(e.which);
if (!/^\d+$/.test(digit)) {
return;
}
$target = $(e.currentTarget);
value = $target.val();
card = cardFromNumber(value + digit);
length = (value.replace(/\D/g, '') + digit).length;
upperLength = 16;
if (card) {
upperLength = card.length[card.length.length - 1];
}
if (length >= upperLength) {
return;
}
if (($target.prop('selectionStart') != null) && $target.prop('selectionStart') !== value.length) {
return;
}
if (card && card.type === 'amex') {
re = /^(\d{4}|\d{4}\s\d{6})$/;
} else {
re = /(?:^|\s)(\d{4})$/;
}
if (re.test(value)) {
e.preventDefault();
return setTimeout(function() {
return $target.val(value + ' ' + digit);
});
} else if (re.test(value + digit)) {
e.preventDefault();
return setTimeout(function() {
return $target.val(value + digit + ' ');
});
}
};
formatBackCardNumber = function(e) {
var $target, value;
$target = $(e.currentTarget);
value = $target.val();
if (e.which !== 8) {
return;
}
if (($target.prop('selectionStart') != null) && $target.prop('selectionStart') !== value.length) {
return;
}
if (/\d\s$/.test(value)) {
e.preventDefault();
return setTimeout(function() {
return $target.val(value.replace(/\d\s$/, ''));
});
} else if (/\s\d?$/.test(value)) {
e.preventDefault();
return setTimeout(function() {
return $target.val(value.replace(/\d$/, ''));
});
}
};
reFormatExpiry = function(e) {
var $target;
$target = $(e.currentTarget);
return setTimeout(function() {
var value;
value = $target.val();
value = replaceFullWidthChars(value);
value = $.payment.formatExpiry(value);
return safeVal(value, $target);
});
};
formatExpiry = function(e) {
var $target, digit, val;
digit = String.fromCharCode(e.which);
if (!/^\d+$/.test(digit)) {
return;
}
$target = $(e.currentTarget);
val = $target.val() + digit;
if (/^\d$/.test(val) && (val !== '0' && val !== '1')) {
e.preventDefault();
return setTimeout(function() {
return $target.val("0" + val + " / ");
});
} else if (/^\d\d$/.test(val)) {
e.preventDefault();
return setTimeout(function() {
var m1, m2;
m1 = parseInt(val[0], 10);
m2 = parseInt(val[1], 10);
if (m2 > 2 && m1 !== 0) {
return $target.val("0" + m1 + " / " + m2);
} else {
return $target.val("" + val + " / ");
}
});
}
};
formatForwardExpiry = function(e) {
var $target, digit, val;
digit = String.fromCharCode(e.which);
if (!/^\d+$/.test(digit)) {
return;
}
$target = $(e.currentTarget);
val = $target.val();
if (/^\d\d$/.test(val)) {
return $target.val("" + val + " / ");
}
};
formatForwardSlashAndSpace = function(e) {
var $target, val, which;
which = String.fromCharCode(e.which);
if (!(which === '/' || which === ' ')) {
return;
}
$target = $(e.currentTarget);
val = $target.val();
if (/^\d$/.test(val) && val !== '0') {
return $target.val("0" + val + " / ");
}
};
formatBackExpiry = function(e) {
var $target, value;
$target = $(e.currentTarget);
value = $target.val();
if (e.which !== 8) {
return;
}
if (($target.prop('selectionStart') != null) && $target.prop('selectionStart') !== value.length) {
return;
}
if (/\d\s\/\s$/.test(value)) {
e.preventDefault();
return setTimeout(function() {
return $target.val(value.replace(/\d\s\/\s$/, ''));
});
}
};
reFormatCVC = function(e) {
var $target;
$target = $(e.currentTarget);
return setTimeout(function() {
var value;
value = $target.val();
value = replaceFullWidthChars(value);
value = value.replace(/\D/g, '').slice(0, 4);
return safeVal(value, $target);
});
};
restrictNumeric = function(e) {
var input;
if (e.metaKey || e.ctrlKey) {
return true;
}
if (e.which === 32) {
return false;
}
if (e.which === 0) {
return true;
}
if (e.which < 33) {
return true;
}
input = String.fromCharCode(e.which);
return !!/[\d\s]/.test(input);
};
restrictCardNumber = function(e) {
var $target, card, digit, value;
$target = $(e.currentTarget);
digit = String.fromCharCode(e.which);
if (!/^\d+$/.test(digit)) {
return;
}
if (hasTextSelected($target)) {
return;
}
value = ($target.val() + digit).replace(/\D/g, '');
card = cardFromNumber(value);
if (card) {
return value.length <= card.length[card.length.length - 1];
} else {
return value.length <= 16;
}
};
restrictExpiry = function(e) {
var $target, digit, value;
$target = $(e.currentTarget);
digit = String.fromCharCode(e.which);
if (!/^\d+$/.test(digit)) {
return;
}
if (hasTextSelected($target)) {
return;
}
value = $target.val() + digit;
value = value.replace(/\D/g, '');
if (value.length > 6) {
return false;
}
};
restrictCVC = function(e) {
var $target, digit, val;
$target = $(e.currentTarget);
digit = String.fromCharCode(e.which);
if (!/^\d+$/.test(digit)) {
return;
}
if (hasTextSelected($target)) {
return;
}
val = $target.val() + digit;
return val.length <= 4;
};
setCardType = function(e) {
var $target, allTypes, card, cardType, val;
$target = $(e.currentTarget);
val = $target.val();
cardType = $.payment.cardType(val) || 'unknown';
if (!$target.hasClass(cardType)) {
allTypes = (function() {
var _i, _len, _results;
_results = [];
for (_i = 0, _len = cards.length; _i < _len; _i++) {
card = cards[_i];
_results.push(card.type);
}
return _results;
})();
$target.removeClass('unknown');
$target.removeClass(allTypes.join(' '));
$target.addClass(cardType);
$target.toggleClass('identified', cardType !== 'unknown');
return $target.trigger('payment.cardType', cardType);
}
};
$.payment.fn.formatCardCVC = function() {
this.on('keypress', restrictNumeric);
this.on('keypress', restrictCVC);
this.on('paste', reFormatCVC);
this.on('change', reFormatCVC);
this.on('input', reFormatCVC);
return this;
};
$.payment.fn.formatCardExpiry = function() {
this.on('keypress', restrictNumeric);
this.on('keypress', restrictExpiry);
this.on('keypress', formatExpiry);
this.on('keypress', formatForwardSlashAndSpace);
this.on('keypress', formatForwardExpiry);
this.on('keydown', formatBackExpiry);
this.on('change', reFormatExpiry);
this.on('input', reFormatExpiry);
return this;
};
$.payment.fn.formatCardNumber = function() {
this.on('keypress', restrictNumeric);
this.on('keypress', restrictCardNumber);
this.on('keypress', formatCardNumber);
this.on('keydown', formatBackCardNumber);
this.on('keyup', setCardType);
this.on('paste', reFormatCardNumber);
this.on('change', reFormatCardNumber);
this.on('input', reFormatCardNumber);
this.on('input', setCardType);
return this;
};
$.payment.fn.restrictNumeric = function() {
this.on('keypress', restrictNumeric);
this.on('paste', reFormatNumeric);
this.on('change', reFormatNumeric);
this.on('input', reFormatNumeric);
return this;
};
$.payment.fn.cardExpiryVal = function() {
return $.payment.cardExpiryVal($(this).val());
};
$.payment.cardExpiryVal = function(value) {
var month, prefix, year, _ref;
_ref = value.split(/[\s\/]+/, 2), month = _ref[0], year = _ref[1];
if ((year != null ? year.length : void 0) === 2 && /^\d+$/.test(year)) {
prefix = (new Date).getFullYear();
prefix = prefix.toString().slice(0, 2);
year = prefix + year;
}
month = parseInt(month, 10);
year = parseInt(year, 10);
return {
month: month,
year: year
};
};
$.payment.validateCardNumber = function(num) {
var card, _ref;
num = (num + '').replace(/\s+|-/g, '');
if (!/^\d+$/.test(num)) {
return false;
}
card = cardFromNumber(num);
if (!card) {
return false;
}
return (_ref = num.length, __indexOf.call(card.length, _ref) >= 0) && (card.luhn === false || luhnCheck(num));
};
$.payment.validateCardExpiry = function(month, year) {
var currentTime, expiry, _ref;
if (typeof month === 'object' && 'month' in month) {
_ref = month, month = _ref.month, year = _ref.year;
}
if (!(month && year)) {
return false;
}
month = $.trim(month);
year = $.trim(year);
if (!/^\d+$/.test(month)) {
return false;
}
if (!/^\d+$/.test(year)) {
return false;
}
if (!((1 <= month && month <= 12))) {
return false;
}
if (year.length === 2) {
if (year < 70) {
year = "20" + year;
} else {
year = "19" + year;
}
}
if (year.length !== 4) {
return false;
}
expiry = new Date(year, month);
currentTime = new Date;
expiry.setMonth(expiry.getMonth() - 1);
expiry.setMonth(expiry.getMonth() + 1, 1);
return expiry > currentTime;
};
$.payment.validateCardCVC = function(cvc, type) {
var card, _ref;
cvc = $.trim(cvc);
if (!/^\d+$/.test(cvc)) {
return false;
}
card = cardFromType(type);
if (card != null) {
return _ref = cvc.length, __indexOf.call(card.cvcLength, _ref) >= 0;
} else {
return cvc.length >= 3 && cvc.length <= 4;
}
};
$.payment.cardType = function(num) {
var _ref;
if (!num) {
return null;
}
return ((_ref = cardFromNumber(num)) != null ? _ref.type : void 0) || null;
};
$.payment.formatCardNumber = function(num) {
var card, groups, upperLength, _ref;
num = num.replace(/\D/g, '');
card = cardFromNumber(num);
if (!card) {
return num;
}
upperLength = card.length[card.length.length - 1];
num = num.slice(0, upperLength);
if (card.format.global) {
return (_ref = num.match(card.format)) != null ? _ref.join(' ') : void 0;
} else {
groups = card.format.exec(num);
if (groups == null) {
return;
}
groups.shift();
groups = $.grep(groups, function(n) {
return n;
});
return groups.join(' ');
}
};
$.payment.formatExpiry = function(expiry) {
var mon, parts, sep, year;
parts = expiry.match(/^\D*(\d{1,2})(\D+)?(\d{1,4})?/);
if (!parts) {
return '';
}
mon = parts[1] || '';
sep = parts[2] || '';
year = parts[3] || '';
if (year.length > 0) {
sep = ' / ';
} else if (sep === ' /') {
mon = mon.substring(0, 1);
sep = '';
} else if (mon.length === 2 || sep.length > 0) {
sep = ' / ';
} else if (mon.length === 1 && (mon !== '0' && mon !== '1')) {
mon = "0" + mon;
sep = ' / ';
}
return mon + sep + year;
};
}).call(this);

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,15 @@
var count = 1;
var contentTpay;
window.onload = function () {
contentTpay = document.getElementById("kanaly_v").innerHTML;
};
document.getElementById("blikcode").onkeyup = function () {
if (document.getElementById("blikcode").value !== "") {
document.getElementById("kanaly_v").innerHTML = "";
count = 0;
} else if (count === 0) {
document.getElementById("kanaly_v").innerHTML = contentTpay;
count = 1;
}
};

View File

@@ -0,0 +1,73 @@
var Base64 = {};
Base64.code = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
Base64.encode = function (e, t) {
t = typeof t === "undefined" ? false : t;
var n, r, i, s, o, u, a, f, l = [], c = "", h, p, d;
var v = Base64.code;
p = t ? Utf8.encode(e) : e;
h = p.length % 3;
if (h > 0) {
while (h++ < 3) {
c += "=";
p += "\0"
}
}
for (h = 0; h < p.length; h += 3) {
n = p.charCodeAt(h);
r = p.charCodeAt(h + 1);
i = p.charCodeAt(h + 2);
s = n << 16 | r << 8 | i;
o = s >> 18 & 63;
u = s >> 12 & 63;
a = s >> 6 & 63;
f = s & 63;
l[h / 3] = v.charAt(o) + v.charAt(u) + v.charAt(a) + v.charAt(f)
}
d = l.join("");
d = d.slice(0, d.length - c.length) + c;
return d
};
Base64.decode = function (e, t) {
t = typeof t === "undefined" ? false : t;
var n, r, i, s, o, u, a, f, l = [], c, h;
var p = Base64.code;
h = t ? Utf8.decode(e) : e;
for (var d = 0; d < h.length; d += 4) {
s = p.indexOf(h.charAt(d));
o = p.indexOf(h.charAt(d + 1));
u = p.indexOf(h.charAt(d + 2));
a = p.indexOf(h.charAt(d + 3));
f = s << 18 | o << 12 | u << 6 | a;
n = f >>> 16 & 255;
r = f >>> 8 & 255;
i = f & 255;
l[d / 4] = String.fromCharCode(n, r, i);
if (a === 64)l[d / 4] = String.fromCharCode(n, r);
if (u === 64)l[d / 4] = String.fromCharCode(n)
}
c = l.join("");
return t ? Utf8.decode(c) : c
};
var Utf8 = {};
Utf8.encode = function (e) {
var t = e.replace(/[\u0080-\u07ff]/g, function (e) {
var t = e.charCodeAt(0);
return String.fromCharCode(192 | t >> 6, 128 | t & 63)
});
t = t.replace(/[\u0800-\uffff]/g, function (e) {
var t = e.charCodeAt(0);
return String.fromCharCode(224 | t >> 12, 128 | t >> 6 & 63, 128 | t & 63)
});
return t
};
Utf8.decode = function (e) {
var t = e.replace(/[\u00e0-\u00ef][\u0080-\u00bf][\u0080-\u00bf]/g, function (e) {
var t = (e.charCodeAt(0) & 15) << 12 | (e.charCodeAt(1) & 63) << 6 | e.charCodeAt(2) & 63;
return String.fromCharCode(t)
});
t = t.replace(/[\u00c0-\u00df][\u0080-\u00bf]/g, function (e) {
var t = (e.charCodeAt(0) & 31) << 6 | e.charCodeAt(1) & 63;
return String.fromCharCode(t)
});
return t
};

View File

@@ -0,0 +1,130 @@
<?php
/*
* Created by tpay.com
*/
?>
<style>
<?php include_once dirname(__FILE__) . '/../_css/style.css'; ?>
</style>
<div class="insidebg" id="main-payment">
<img src="https://tpay.com/img/logo/tpaycom.png" height="145" width="250"/>
<div id="kanaly_v">
<div class="separator"><span><p class="font"><br/><?php tpay\Lang::l('cards_and_transfers') ?></p></span></div>
<center>
<div id="bank-selection-form"></div>
<div class="separator"><span><p class="font"><br/><?php tpay\Lang::l('other_methods') ?></p></span></div>
<div id="bank-selection-form2"></div>
<br/>
<?php echo $data['form'] ?>
</center>
<div class="regulations" style="padding-top: 20px; margin-bottom: 20px">
<?php if ($data['show_regulations_checkbox'] === true) { ?>
<p>
<input id="tpay-accept-regulations-checkbox" type="checkbox" name="regulations" value="0">
<?php tpay\Lang::l('accept') ?> <a href="<?php echo $data['regulation_url'] ?>"
target="_blank"><?php tpay\Lang::l('regulations_url') ?></a>
<?php tpay\Lang::l('regulations'); ?>
</p>
<?php } ?>
</div>
</div>
</div>
<script>
var s = document.createElement('script');
function renderTpayChannels(installmentsActive) {
var regulation_checkbox = document.getElementById('tpay-accept-regulations-checkbox'),
submit_form_input = document.getElementById('tpay-payment-submit'),
regulations_form_input = document.getElementById('tpay-regulations-input'),
bank_selection_form = document.getElementById('bank-selection-form'),
bank_selection_form2 = document.getElementById('bank-selection-form2');
changeBank = function (bank_id) {
var input = document.getElementById('tpay-channel-input'),
bank_block = document.getElementById('bank-' + bank_id),
active_bank_blocks = document.getElementsByClassName('bank-active'),
class_name = 'bank-active', cn;
input.value = bank_id;
if (active_bank_blocks.length > 0) {
cn = active_bank_blocks[0].className;
cn = cn.replace(new RegExp("\\s?\\b" + class_name + "\\b", "g"), '');
active_bank_blocks[0].className = cn;
}
if (bank_block !== null) {
bank_block.className = bank_block.className + ' bank-active';
}
};
s.src = 'https://secure.tpay.com/groups-<?php echo $data['merchant_id'] . $data['online'] ?>.js';
s.onload = function () {
var str = '', first = true, i, str2 = '', temp;
var others = [157, 106, 109, 148, 104];
for (i in tr_groups) {
var channel = tr_groups[i],
id = channel[0],
width_style = (channel[0] == 40) ? 'width:270px' : '',
checked, class_name;
if (id === '109' && installmentsActive === false) {
continue;
}
if (first) {
checked = ' checked';
class_name = ' bank-active';
first = false;
changeBank(id);
} else {
checked = '';
class_name = ''
}
temp = '<div class="bank-block' + class_name + '" id="bank-' + id +
'" style="background-image:url(' + channel[3] + ');' + width_style +
'"><label onclick="changeBank(' + id + ')"><input type="radio" name="bank-select" value="' +
id + '" ' + checked + ' style="visibility: hidden" /></label></div>';
if (inArray(id, others) === false) {
str += temp;
} else {
str2 += temp;
}
}
bank_selection_form.innerHTML = str;
bank_selection_form2.innerHTML = str2;
};
document.getElementsByTagName('head')[0].appendChild(s);
<?php if ($data['show_regulations_checkbox'] === true){ ?>
submit_form_input.onclick = function () {
if (regulations_form_input.value == 0) {
alert('<?php tpay\Lang::l('acceptance_is_required') ?>');
return false;
}
return true;
};
regulation_checkbox.onchange = function () {
regulations_form_input.value = (this.checked) ? 1 : 0;
};
<?php } ?>
}
function inArray(needle, haystack) {
var length = haystack.length;
for (var i = 0; i < length; i++) {
if (haystack[i] == needle) return true;
}
return false;
}
</script>

View File

@@ -0,0 +1,68 @@
<?php
/*
* Created by tpay.com
*/
?>
<style>
<?php include_once dirname(__FILE__) . '/../_css/style.css'; ?>
</style>
<div class="insidebg" id="main-payment">
<div id="kanaly_v">
<select name="bank_list" id="tpay-bank-list" onchange="changeBank()"></select>
<?php if ($data['show_regulations_checkbox'] === true) { ?>
<p>
<input id="tpay-accept-regulations-checkbox" type="checkbox" name="regulations" value="0">
<?php tpay\Lang::l('accept') ?> <a href="<?php echo $data['regulation_url'] ?>"
target="_blank"><?php tpay\Lang::l('regulations_url') ?></a>
<?php tpay\Lang::l('regulations'); ?>
</p>
<?php } ?>
</div>
</div>
<?php echo $data['form'] ?>
<script>
var s = document.createElement('script');
function renderTpayChannels(installmentsActive) {
var submit_form_input = document.getElementById('tpay-payment-submit'),
regulations_form_input = document.getElementById('tpay-regulations-input'),
regulation_checkbox = document.getElementById('tpay-accept-regulations-checkbox');
changeBank = function () {
document.getElementById('tpay-channel-input').value = document.getElementById('tpay-bank-list').value;
};
s.src = 'https://secure.tpay.com/groups-<?php echo $data['merchant_id'] . $data['online'] ?>.js';
s.onload = function () {
var str = '', i;
for (i in tr_groups) {
var channel = tr_groups[i],
id = channel[0],
name = channel[1];
if (id === '109' && installmentsActive === false) {
continue;
}
str += '<option value="' + id + '" >' + name + '</option>';
}
document.getElementById('tpay-bank-list').innerHTML = str;
changeBank();
};
document.getElementsByTagName('head')[0].appendChild(s);
<?php if ($data['show_regulations_checkbox'] === true){ ?>
submit_form_input.onclick = function () {
if (regulations_form_input.value == 0) {
alert('<?php tpay\Lang::l('acceptance_is_required') ?>');
return false;
}
return true;
};
regulation_checkbox.onchange = function () {
regulations_form_input.value = (this.checked) ? 1 : 0;
};
<?php } ?>
}
</script>

View File

@@ -0,0 +1,44 @@
<?php
?>
<script src="https://code.jquery.com/jquery-1.9.1.min.js"></script>
<div class="insidebg" id="blikOneClickForm">
<img src="https://secure.tpay.com/_/banks/b64.png"/><br>
<div id="codeFields" style="visibility: hidden">
<label for="blikcode" class="form_input_label">Wpisz kod blik:</label>
<input type="text" id="blikcode" name="blikcode" value="" maxlength="6" pattern=".{6,}"
title="Kod blik powinien składać się z 6 cyfr!"/>
<label for="register" class="form_input_label">Chcę zapamiętać to
urządzenie:</label>
<input type="checkbox" value="0" id="register" onchange="checkRegister()">
</div>
<div id="alias" style="visibility: hidden">
<p>
<label for="blikSwitch" class="form_input_label">Wybierz alias:</label>
<select name="blikSwitch" id="blikSwitch" class="form_input"></select>
</p>
</div>
<div id="tpayBlikButton">
<input type="button" value="<?php echo tpay\Lang::l('pay') ?>" onclick="blikHandler()"
id="tpayBlikButton">
</div>
<div id="t6InputMsg">
<small>
<a href="#" onclick="showT6()">Chcę wprowadzić kod blik</a>
</small>
</div>
<div>
<br/>
<small>
<?php tpay\Lang::l('blik_accept') ?>
<a href="<?php echo $data['regulation_url'] ?>"
target="_blank"><?php tpay\Lang::l('regulations_url') ?></a>
<?php tpay\Lang::l('regulations'); ?>
</small>
</div>
</div>
<script src="../src/common/_js/blikHandler.js"></script>
<?php

View File

@@ -0,0 +1,28 @@
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8" />
</head>
<script type="text/javascript">
function redirect() {
document.getElementById('tpay-payment').submit();
}
</script>
<body onload="redirect()">
<form id="tpay-payment" class="tpay-form" action="<?php echo $data['action_url'] ?>" method="POST"
accept-charset="UTF-8">
<?php foreach ($data['fields'] as $name => $value) { ?>
<input <?php if ($name === 'kanal') {
echo ' id="tpay-channel-input" ';
}
if ($name === 'akceptuje_regulamin') {
echo ' id="tpay-regulations-input" ';
} ?> type="hidden"
name="<?php echo $name ?>"
value="<?php echo $value ?>">
<?php
}
?>
<input class="button" style="width: 500px ; height:50px"
id="tpay-payment-submit" type="submit" value="<?php tpay\Lang::l('pay') ?>">
</form>
</body>

View File

@@ -0,0 +1,31 @@
#transferuj-dac-confirmation {
border: 1px solid #B2B2B2;
padding: 10px;
background: #FFFFF0;
max-width: 500px;
}
#transferuj-dac-confirmation .transferuj-row {
overflow: hidden;
margin-bottom: 10px;
}
#transferuj-dac-confirmation .transferuj-row > div {
float: left;
box-sizing: border-box;
}
#transferuj-dac-confirmation .transferuj-row .col-l {
float: left;
width: 40%;
}
#transferuj-dac-confirmation .transferuj-row .col-r {
float: left;
width: 60%;
}
#transferuj-dac-confirmation .transferuj-header {
border-bottom: 1px solid #B2B2B2;
padding-bottom: 10px;
font-weight: bold;
}

View File

@@ -0,0 +1,36 @@
<?php
/*
* Created by tpay.com
*/
?>
<link rel="stylesheet" type="text/css" href="<?php echo $data['static_files_url'] ?>dac/_css/confirmation.css"/>
<div id="tpay-dac-confirmation">
<div class="tpay-row tpay-header"><?php tpay\Lang::l('transfer_details') ?></div>
<div class="tpay-row">
<div class="col-l">
<?php tpay\Lang::l('merchant_info') ?>:
</div>
<div class="col-r">
<?php echo $data['merchant_data'] ?>
</div>
</div>
<div class="tpay-row">
<div class="col-l">
<?php tpay\Lang::l('payment_amount') ?>:
</div>
<div class="col-r">
<?php echo $data['transaction']['amount'] ?>
</div>
</div>
<div class="tpay-row">
<div class="col-l">
<?php tpay\Lang::l('disposable_account') ?>:
</div>
<div class="col-r">
<?php echo $data['transaction']['account_number'] ?>
</div>
</div>
</div>

View File

@@ -0,0 +1,30 @@
#transferuj-szkwal-confirmation {
border: 1px solid #B2B2B2;
padding: 10px;
background: #FFFFF0;
max-width: 500px;
}
#transferuj-szkwal-confirmation .transferuj-row {
overflow: hidden;
margin-bottom: 10px;
}
#transferuj-szkwal-confirmation .transferuj-row > div {
float: left;
box-sizing: border-box;
}
#transferuj-szkwal-confirmation .transferuj-row .col-l {
float: left;
width: 30%;
}
#transferuj-szkwal-confirmation .transferuj-row .col-r {
float: left;
width: 70%;
}
#transferuj-szkwal-confirmation .client-title {
font-weight: bold;
}

View File

@@ -0,0 +1,7 @@
var bank_account_div = document.getElementById('transferuj-bank-account'),
bank_select = document.getElementById('transferuj-bank-select');
bank_select.onchange = function () {
bank_account_div.innerText = this.value;
};
bank_account_div.innerText = bank_select.value;

View File

@@ -0,0 +1,49 @@
<?php
/*
* Created by tpay.com
*/
const AMOUNT = 'amount';
?>
<link rel="stylesheet" type="text/css" href="<?php echo $data['static_files_url'] ?>szkwal/_css/confirmation.css"/>
<div id="tpay-szkwal-confirmation">
<div class="tpay-row">
<?php tpay\Lang::l('payment_method') ?>:
</div>
<div class="tpay-row">
<select id="tpay-bank-select">
<?php foreach ($data['banks'] as $b) { ?>
<option value="<?php echo $b['account_number'] ?>"><?php echo $b['fullname'] ?></option>
<?php } ?>
</select>
</div>
<div class="tpay-row">
<div class="col-l"><?php tpay\Lang::l('merchant_info') ?></div>
<div class="col-r"><?php echo $data['merchant_data'] ?></div>
</div>
<div class="tpay-row">
<div class="col-l"><?php tpay\Lang::l('account_number') ?></div>
<div id="tpay-bank-account" class="col-r"></div>
</div>
<div class="tpay-row">
<div class="col-l"><?php tpay\Lang::l('payment_title') ?></div>
<div class="col-r client-title"><?php echo $data['title'] ?></div>
</div>
<?php if ($data[AMOUNT] !== false) { ?>
<div class="tpay-row">
<div class="col-l"><?php tpay\Lang::l(AMOUNT) ?></div>
<div class="col-r"><?php echo $data[AMOUNT]
?>
</div>
</div>
<?php
}
?>
<div>
<?php tpay\Lang::l('szkwal_info') ?>
</div>
</div>
<script type="text/javascript" src="<?php echo $data['static_files_url'] ?>szkwal/_js/confirmation.js"></script>

View File

@@ -0,0 +1,4 @@
#white-label-bank-instruction {
clear: both;
}

View File

@@ -0,0 +1,23 @@
#white-label-info {
clear: both;
}
.bank-block {
float: left;
border: 1px solid #B2B2B2;
margin: 6px;
padding: 10px;
padding-top: 5px;
min-height: 210px;
font-size: 13px;
}
.availability {
margin-top: 10px;
}
.bank-block a {
padding-top: 10px;
display: inline-block;
text-align: center;
}

View File

@@ -0,0 +1,18 @@
<?php
/*
* Created by tpay.com
*/
?>
<link rel="stylesheet" type="text/css" href="../_css/bank_instruction.css"/>
<div id="white-label-bank-instruction">
<div class="bank-block">
<img src="https://secure.tpay.com/_/banks/b<?php echo $data['bank_id'] ?>.png" alt=""/>
<?php foreach ($data['instructions'] as $paragraph) { ?>
<p><?php echo $paragraph ?></p>
<?php
}
?>
</div>
</div>

View File

@@ -0,0 +1,26 @@
<?php
/*
* Created by tpay.com
*/
?>
<link rel="stylesheet" type="text/css" href="white_label/_css/bank_list.css"/>
<div id="white-label-info">
<?php foreach ($data as $bank) { ?>
<div class="bank-block">
<img src="https://secure.tpay.com/_/banks/b<?php echo $bank['bank_id'] ?>.png" alt=""/>
<div class="fullname"><?php echo $bank['fullname'] ?></div>
<div class="account_number"><?php echo $bank['account_number'] ?></div>
<div class="availability">
<?php foreach ($bank['availability'] as $date => $availability) { ?>
<?php foreach ($availability as $time) { ?>
<div><?php echo $date . ' : ' . $time ?></div>
<?php } ?>
<?php } ?>
</div>
<a href="<?php echo $bank['login_url'] ?>" target="_blank"><?php tpay\Lang::l('go_to_bank') ?></a>
</div>
<?php } ?>
</div>