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,20 @@
<?php
class OauthCacheWP implements OauthCacheInterface
{
public function get($key)
{
$cache = get_transient($key);
return $cache === false ? null : unserialize($cache);
}
public function set($key, $value)
{
return set_transient($key, serialize($value));
}
public function invalidate($key)
{
return delete_transient($key);
}
}

View File

@@ -0,0 +1,255 @@
<?php
class PayUSettings
{
private $payu_settings_options;
private $fields;
public function __construct()
{
$this->fields = $this->payu_fields();
add_action('admin_menu', [$this, 'payu_settings_add_plugin_page']);
add_action('admin_init', [$this, 'payu_settings_page_init']);
}
/**
* @return array
*/
public static function payu_fields()
{
return [
'pos_id' => [
'label' => __('Id point of sales', 'woo-payu-payment-gateway'),
'description' => __('Pos identifier from "Configuration Keys" section of PayU management panel.',
'woo-payu-payment-gateway')
],
'md5' => [
'label' => __('Second key (MD5)', 'woo-payu-payment-gateway'),
'description' => __('Second key from "Configuration Keys" section of PayU management panel.', 'woo-payu-payment-gateway')
],
'client_id' => [
'label' => __('OAuth - client_id', 'woo-payu-payment-gateway'),
'description' => __('Client Id for OAuth identifier from "Configuration Keys" section of PayU management panel.',
'woo-payu-payment-gateway')
],
'client_secret' => [
'label' => __('OAuth - client_secret', 'woo-payu-payment-gateway'),
'description' => __('First key from "Configuration Keys" section of PayU management panel.', 'woo-payu-payment-gateway'),
],
'sandbox_pos_id' => [
'label' => __('Sandbox - Id point of sales', 'woo-payu-payment-gateway'),
'description' => __('Pos identifier from "Configuration Keys" section of PayU management panel.',
'woo-payu-payment-gateway'),
],
'sandbox_md5' => [
'label' => __('Sandbox - Second key (MD5):', 'woo-payu-payment-gateway'),
'description' => __('Second key from "Configuration Keys" section of PayU management panel.', 'woo-payu-payment-gateway'),
],
'sandbox_client_id' => [
'label' => __('Sandbox - OAuth - client_id:', 'woo-payu-payment-gateway'),
'description' => __('Client Id for OAuth identifier from "Configuration Keys" section of PayU management panel.',
'woo-payu-payment-gateway'),
],
'sandbox_client_secret' => [
'label' => __('Sandbox - OAuth - client_secret:', 'woo-payu-payment-gateway'),
'description' => __('First key from "Configuration Keys" section of PayU management panel.', 'woo-payu-payment-gateway'),
],
];
}
/**
* @return null
*/
public function payu_settings_add_plugin_page()
{
add_submenu_page(
'woocommerce',
__('PayU settings', 'woo-payu-payment-gateway'), // page_title
__('PayU settings', 'woo-payu-payment-gateway'), // menu_title
'manage_options', // capability
'payu-settings', // menu_slug
[$this, 'payu_settings_create_admin_page'], // function
100
);
}
/**
* @return void
*/
public function payu_settings_create_admin_page()
{
$this->payu_settings_options = get_option('payu_settings_option_name'); ?>
<div class="wrap">
<h2><?php esc_html_e('PayU settings', 'woo-payu-payment-gateway') ?></h2>
<p></p>
<?php settings_errors(); ?>
<form method="post" action="options.php">
<?php
settings_fields('payu_settings_option_group');
do_settings_sections('payu-settings-admin');
submit_button();
?>
</form>
</div>
<?php
}
/**
* @return void
*/
public function payu_settings_page_init()
{
global $woocommerce_wpml;
register_setting(
'payu_settings_option_group', // option_group
'payu_settings_option_name', // option_name
[$this, 'payu_settings_sanitize'] // sanitize_callback
);
//global
add_settings_section(
'payu_settings_setting_section', // id
__('PayU config global', 'woo-payu-payment-gateway'), // title
[], // callback
'payu-settings-admin' // page
);
$currencies = woocommerce_payu_get_currencies();
if (count($currencies) < 2) {
$currencies = [''];
}
foreach ($currencies as $code) {
$idSuffix = ($code ? '_' : '') . $code;
$namePrefix = $code . ($code ? ' - ' : '');
foreach ($this->fields as $field => $desc) {
$args = [
'id' => 'global_' . $field . $idSuffix,
'desc' => $namePrefix . $desc['label'],
'name' => 'payu_settings_option_name'
];
add_settings_field(
$args['id'], // id
$args['desc'], // title
[$this, 'global_callback'], // callback
'payu-settings-admin', // page
'payu_settings_setting_section',
$args
);
}
}
add_settings_field(
'global_default_on_hold_status', // id
__('Default on-hold status', 'woo-payu-payment-gateway'), // title
[$this, 'global_default_on_hold_status_callback'], // callback
'payu-settings-admin', // page
'payu_settings_setting_section' // section
);
add_settings_field(
'global_repayment', // id
__('Enable repayment', 'woo-payu-payment-gateway'), // title
[$this, 'global_repayment_callback'], // callback
'payu-settings-admin', // page
'payu_settings_setting_section' // section
);
}
/**
* @param array $args
* @return void
*/
public function global_callback($args)
{
$id = $args['id'];
$value = isset($this->payu_settings_options[$id]) ? esc_attr($this->payu_settings_options[$id]) : '';
printf('<input type="text" class="regular-text" value="%s" name="payu_settings_option_name[%s]" id="%s" />',
$value, $id, $id);
}
/**
* @param array $input
* @return array
*/
public function payu_settings_sanitize($input)
{
$sanitary_values = [];
$currencies = woocommerce_payu_get_currencies();
if (count($currencies) < 2) {
$currencies = [''];
}
foreach ($currencies as $code) {
$idSuffix = ($code ? '_' : '') . $code;
foreach ($this->fields as $field => $desc) {
$field = $field . $idSuffix;
if (isset($input['global_' . $field])) {
$sanitary_values['global_' . $field] = sanitize_text_field($input['global_' . $field]);
}
}
}
if (isset($input['global_default_on_hold_status'])) {
$sanitary_values['global_default_on_hold_status'] = sanitize_text_field($input['global_default_on_hold_status']);
}
if (isset($input['global_repayment'])) {
$sanitary_values['global_repayment'] = sanitize_text_field($input['global_repayment']);
}
return $sanitary_values;
}
/**
* @return null
*/
public function global_repayment_callback()
{
printf(
'<input type="checkbox" name="payu_settings_option_name[global_repayment]" id="global_repayment" value="global_repayment" %s>',
(isset($this->payu_settings_options['global_repayment']) && $this->payu_settings_options['global_repayment'] === 'global_repayment') ? 'checked' : ''
);
?>
<span class="description payu-red">
<span class="dashicons dashicons-warning"></span>
<?php echo wp_kses(__('Before enabling repayment, read <a target="_blank" href="https://github.com/PayU-EMEA/woo-payu-payment-gateway#ponawianie-p%C5%82atno%C5%9Bci">the documentation</a> and disable <strong>automatic collection</strong> in POS configuration.', 'woo-payu-payment-gateway'), ['a' => ['target' => [], 'href' => []], 'strong' => []]); ?>
</span>
<?php
}
/**
* @return null
*/
public function global_default_on_hold_status_callback()
{
?>
<select class="regular-text" type="text" name="payu_settings_option_name[global_default_on_hold_status]"
id="global_default_on_hold_status">
<?php foreach ($this->before_payment_statuses() as $key => $value): ?>
<option <?php if (@$this->payu_settings_options['global_default_on_hold_status'] === $key) echo 'selected="selected"' ?>
value="<?php echo esc_attr($key) ?>"><?php echo esc_html($value) ?></option>
<?php endforeach; ?>
</select>
<?php
}
/**
* @return array
*/
public function before_payment_statuses()
{
$statuses = wc_get_order_statuses();
$available = [];
foreach ($statuses as $key => $value) {
if (in_array($key, ['wc-pending', 'wc-on-hold'])) {
$available[str_replace('wc-', '', $key)] = $value;
}
}
ksort($available);
return $available;
}
}
if (is_admin()) {
$payu_settings = new PayUSettings();
}

View File

@@ -0,0 +1,28 @@
<?php
class WC_Gateway_PayuBlik extends WC_PayUGateways
{
protected $paytype = 'blik';
function __construct()
{
parent::__construct('payublik');
if ($this->is_enabled()) {
$this->show_terms_info = true;
$this->icon = apply_filters('woocommerce_payu_icon', plugins_url( '/assets/images/blik.svg', PAYU_PLUGIN_FILE ));
if (!is_admin()) {
if (!$this->try_retrieve_banks()) {
add_filter('woocommerce_available_payment_gateways', [$this, 'unset_gateway']);
}
}
}
}
public function payment_fields()
{
parent::payment_fields();
$this->agreements_field();
}
}

View File

@@ -0,0 +1,28 @@
<?php
class WC_Gateway_PayuCreditCard extends WC_PayUGateways
{
protected $paytype = 'c';
function __construct()
{
parent::__construct('payucreditcard');
if ($this->is_enabled()) {
$this->show_terms_info = false;
$this->icon = apply_filters('woocommerce_payu_icon', plugins_url( '/assets/images/card-visa-mc.svg', PAYU_PLUGIN_FILE ));
if (!is_admin()) {
if (!$this->try_retrieve_banks()) {
add_filter('woocommerce_available_payment_gateways', [$this, 'unset_gateway']);
}
}
}
}
public function payment_fields()
{
parent::payment_fields();
$this->agreements_field();
}
}

View File

@@ -0,0 +1,88 @@
<?php
class WC_Gateway_PayuInstallments extends WC_PayUGateways
{
protected $paytype = 'ai';
function __construct()
{
parent::__construct('payuinstallments');
if ($this->is_enabled()) {
if (!is_admin()) {
if (!$this->try_retrieve_banks()) {
add_filter('woocommerce_available_payment_gateways', [$this, 'unset_gateway']);
} else {
wp_enqueue_style('payu-installments-widget', plugins_url( '/assets/css/payu-installments-widget.css', PAYU_PLUGIN_FILE ), [], PAYU_PLUGIN_VERSION);
add_filter('woocommerce_gateway_description', [$this, 'installments_filter_gateway_description'], 10, 2);
}
}
}
}
public function installments_filter_gateway_description($description, $id)
{
if ($this->should_display_installments_widget($id)) {
wp_enqueue_script('payu-installments-widget', 'https://static.payu.com/res/v2/widget-mini-installments.js', [], PAYU_PLUGIN_VERSION);
wp_enqueue_script('payu-installments-widget-checkout', plugins_url( '/assets/js/payu-installments-widget-checkout.js', PAYU_PLUGIN_FILE ), ['jquery', 'payu-installments-widget'], PAYU_PLUGIN_VERSION);
$posId = $this->pos_id;
$widgetKey = $this->pos_widget_key;
$priceTotal = WC()->cart->get_total('');
$transformedDescription =
$description.
'<script type="text/javascript">'.
'var PayUInstallmentsWidgetCartData = {'.
' priceTotal: '.$priceTotal.','.
' posId: \''.$posId.'\','.
' widgetKey: \''.$widgetKey.'\''.
'}'.
'</script>';
return $transformedDescription;
}
return $description;
}
function should_display_installments_widget($id)
{
return $id === 'payuinstallments' &&
get_option('woocommerce_payuinstallments_settings')['credit_widget_on_checkout_page'] === 'yes' &&
get_woocommerce_currency() === 'PLN';
}
public function payment_fields()
{
parent::payment_fields();
$this->agreements_field();
}
protected function get_additional_gateway_fields()
{
return [
'credit_widget_on_listings' => [
'title' => __('Installments widget', 'woo-payu-payment-gateway'),
'type' => 'checkbox',
'label' => __('Enabled on product listings', 'woo-payu-payment-gateway'),
'default' => 'yes'
],
'credit_widget_on_product_page' => [
'title' => __('Installments widget', 'woo-payu-payment-gateway'),
'type' => 'checkbox',
'label' => __('Enabled on product page', 'woo-payu-payment-gateway'),
'default' => 'yes'
],
'credit_widget_on_cart_page' => [
'title' => __('Installments widget', 'woo-payu-payment-gateway'),
'type' => 'checkbox',
'label' => __('Enabled on cart page', 'woo-payu-payment-gateway'),
'default' => 'yes'
],
'credit_widget_on_checkout_page' => [
'title' => __('Installments widget', 'woo-payu-payment-gateway'),
'type' => 'checkbox',
'label' => __('Enabled on checkout page', 'woo-payu-payment-gateway'),
'default' => 'yes'
],
];
}
}

View File

@@ -0,0 +1,217 @@
<?php
class WC_Gateway_PayuListBanks extends WC_PayUGateways
{
private $unset_banks = [];
function __construct()
{
parent::__construct('payulistbanks');
if ($this->is_enabled()) {
$this->show_terms_info = true;
if (!is_admin()) {
if (!$this->try_retrieve_banks()) {
add_filter('woocommerce_available_payment_gateways', [$this, 'unset_gateway']);
}
}
}
}
function init_form_fields() {
parent::payu_init_form_fields(true);
}
/**
* @return bool
*/
protected function try_retrieve_banks()
{
$response = $this->get_payu_response();
if (isset($response) && $response->getStatus() === 'SUCCESS') {
$payMethods = $response->getResponse();
return $payMethods->payByLinks;
}
return false;
}
public function payment_fields()
{
parent::payment_fields();
$response = $this->get_payu_response();
if (isset($response) && $response->getStatus() === 'SUCCESS') {
$this->retrieve_methods($response);
$this->agreements_field();
}
}
/**
* @param OpenPayU_Result $response
*
* @return null
*/
private function retrieve_methods($response)
{
$payMethods = $response->getResponse();
$custom_order = '';
if (get_option('woocommerce_' . $this->id . '_settings')['custom_order']) {
$custom_order = get_option('woocommerce_' . $this->id . '_settings')['custom_order'];
}
?>
<script>
jQuery(document).ready(function () {
if (!window.ApplePaySession || !window.ApplePaySession.canMakePayments() && jQuery(".payu-list-banks").is(":visible")) {
jQuery(".payu-bank-jp").remove();
}
})
</script>
<div class="pbl-container">
<ul class="payu-list-banks">
<?php if ($payMethods->payByLinks):
$payByLinks = $this->process_pay_methods($payMethods->payByLinks, $custom_order);
if ($payByLinks):
foreach ($payByLinks as $key => $value):
?>
<li class="payu-bank payu-bank-<?php echo esc_attr($key . ' ' . $value['active']) ?>"
title="<?php echo esc_attr($value['name']) ?>">
<label>
<input type="radio"
value="<?php if ($value['active'] === 'payu-active') echo esc_attr($key) ?>"
name="selected-bank"/>
<div><img src="<?php echo esc_url($value['brandImageUrl']); ?>"></div>
</label>
</li>
<?php
endforeach;
endif;
endif;
?>
</ul>
<ul class="pbl-error woocommerce-error" role="alert">
<li><?php esc_html_e('Choose payment method.', 'woo-payu-payment-gateway') ?></li>
</ul>
</div>
<?php
}
/**
* @param array $payMethods
* @param string|null $sort
*
* @return array
*/
function process_pay_methods($payMethods, $sort = null)
{
$result_methods = [];
$available_gateways = WC()->payment_gateways->get_available_payment_gateways();
if ($available_gateways) {
foreach ($available_gateways as $available_gateway => $data) {
if ($available_gateway === 'payucreditcard' && $data->enabled === 'yes') {
array_push($this->unset_banks, 'c');
}
if ($available_gateway === 'payusecureform' && $data->enabled === 'yes') {
array_push($this->unset_banks, 'c');
}
if ($available_gateway === 'payublik' && $data->enabled === 'yes') {
array_push($this->unset_banks, 'blik');
}
if ($available_gateway === 'payuinstallments' && $data->enabled === 'yes') {
array_push($this->unset_banks, 'ai');
}
if ($available_gateway === 'payupaypo' && $data->enabled === 'yes') {
array_push($this->unset_banks, 'dpp');
}
if ($available_gateway === 'payutwistopl' && $data->enabled === 'yes') {
array_push($this->unset_banks, 'dpt');
}
}
}
$show_inactive = @get_option('woocommerce_' . $this->id . '_settings')['show_inactive_methods'];
foreach ($payMethods as $payMethod) {
if (!in_array($payMethod->value, $this->unset_banks)) {
if ($show_inactive === 'yes' && $payMethod->value != 't') {
$show_method = true;
if ($payMethod->status !== 'ENABLED') {
$show_method = false;
} else {
if (!$this->check_min_max($payMethod)) {
$show_method = false;
}
}
$result_methods[$payMethod->value] = [
'brandImageUrl' => $payMethod->brandImageUrl,
'name' => $payMethod->name,
'active' => $show_method ? 'payu-active' : 'payu-inactive'
];
} else {
if ($payMethod->status === 'ENABLED') {
$can_be_use = true;
if (!$this->check_min_max($payMethod)) {
$can_be_use = false;
}
if ($can_be_use) {
$result_methods[$payMethod->value] = [
'brandImageUrl' => $payMethod->brandImageUrl,
'name' => $payMethod->name,
'active' => 'payu-active'
];
}
}
}
}
}
if (!$sort) {
$first_paytypes = ['c','ap','jp','vc'];
$last_paytypes = ['b', 'pt', 'bt'];
} else {
$first_paytypes = explode(',', str_replace(' ', '', $sort));
$last_paytypes = [];
}
list($first, $result_methods) = $this->extract_paytypes($result_methods, $first_paytypes);
list($last, $result_methods) = $this->extract_paytypes($result_methods, $last_paytypes);
$result_methods = array_merge($first, $result_methods, $last);
return $result_methods;
}
/**
* @param $result_methods
* @param $paytypes
* @return array
*/
private function extract_paytypes($result_methods, $paytypes)
{
$extracted = [];
foreach ($paytypes as $item) {
if (@$result_methods[$item]) {
$extracted[$item] = [
'brandImageUrl' => $result_methods[$item]['brandImageUrl'],
'name' => $result_methods[$item]['name'],
'active' => $result_methods[$item]['active'],
];
unset($result_methods[$item]);
}
}
return [$extracted, $result_methods];
}
/**
* @return array
*/
protected function get_payu_pay_method()
{
$selected_method = sanitize_text_field($_POST['selected-bank']);
return $this->get_payu_pay_method_array('PBL', $selected_method ? $selected_method : -1, $selected_method);
}
}

View File

@@ -0,0 +1,28 @@
<?php
class WC_Gateway_PayuPaypo extends WC_PayUGateways
{
protected $paytype = 'dpp';
function __construct()
{
parent::__construct('payupaypo');
if ($this->is_enabled()) {
$this->show_terms_info = false;
$this->icon = apply_filters('woocommerce_payu_icon', plugins_url( '/assets/images/paypo.svg', PAYU_PLUGIN_FILE ));
if (!is_admin()) {
if (!$this->try_retrieve_banks()) {
add_filter('woocommerce_available_payment_gateways', [$this, 'unset_gateway']);
}
}
}
}
public function payment_fields()
{
parent::payment_fields();
$this->agreements_field();
}
}

View File

@@ -0,0 +1,133 @@
<?php
class WC_Gateway_PayuSecureForm extends WC_PayUGateways
{
protected $paytype = 'c';
function __construct()
{
parent::__construct('payusecureform');
if ($this->is_enabled()) {
$this->show_terms_info = true;
$this->icon = apply_filters('woocommerce_payu_icon', plugins_url( '/assets/images/card-visa-mc.svg', PAYU_PLUGIN_FILE ));
add_action('wp_enqueue_scripts', [$this, 'include_payu_sf_scripts']);
//refresh card iframe after checkout change
if (!is_admin()) {
add_action('wp_footer', [$this, 'minicart_checkout_refresh_script']);
if (!$this->try_retrieve_banks()) {
add_filter('woocommerce_available_payment_gateways', [$this, 'unset_gateway']);
}
}
}
}
/**
* @return null
*/
function minicart_checkout_refresh_script()
{
if (is_checkout() || is_wc_endpoint_url()) :
?>
<script type="text/javascript">
(function ($) {
$(document.body).on('change', '#shipping_method input', function () {
$(document.body).trigger('update_checkout').trigger('wc_fragment_refresh');
sf_init();
});
$(document).ready(function(){
if($('form#order_review').length > 0) {
sf_init();
}
});
})(jQuery);
</script>
<?php
endif;
}
public function payment_fields()
{
parent::payment_fields();
$response = $this->get_payu_response();
if (isset($response) && $response->getStatus() === 'SUCCESS') {
$this->retrieve_methods($response);
$this->agreements_field();
echo '<script>try{sf_init();}catch(e){}</script>';
}
}
/**
* @param OpenPayU_Result $response
*
* @return null
*/
private function retrieve_methods($response)
{
$payMethods = $response->getResponse();
if ($payMethods->payByLinks) {
$payByLinks = $this->process_pay_methods($payMethods->payByLinks);
if ($payByLinks) {
?>
<div class="card-container" id="payu-card-container" data-payu-posid="<?php echo esc_attr($this->pos_id) ?>"
data-lang="<?php echo esc_attr(explode('_', get_locale())[0]) ?>">
<div class="payu-sf-technical-error"
data-type="technical"><?php esc_html_e('The card could not be sent', 'woo-payu-payment-gateway') ?></div>
<label for="payu-card-number"><?php esc_html_e('Card number', 'woo-payu-payment-gateway') ?></label>
<div class="payu-card-form" id="payu-card-number"></div>
<div class="payu-sf-validation-error" data-type="number"></div>
<div class="card-details clearfix">
<div class="expiration">
<label for="payu-card-date"><?php esc_html_e('Expire date', 'woo-payu-payment-gateway') ?></label>
<div class="payu-card-form" id="payu-card-date"></div>
<div class="payu-sf-validation-error" data-type="date"></div>
</div>
<div class="cvv">
<label for="payu-card-cvv"><?php esc_html_e('CVV', 'woo-payu-payment-gateway') ?></label>
<div class="payu-card-form" id="payu-card-cvv"></div>
<div class="payu-sf-validation-error" data-type="cvv"></div>
</div>
</div>
</div>
<input type="hidden" name="payu_sf_token" value=""/>
<input type="hidden" name="payu_browser[screenWidth]" value=""/>
<input type="hidden" name="payu_browser[javaEnabled]" value=""/>
<input type="hidden" name="payu_browser[timezoneOffset]" value=""/>
<input type="hidden" name="payu_browser[screenHeight]" value=""/>
<input type="hidden" name="payu_browser[userAgent]" value=""/>
<input type="hidden" name="payu_browser[colorDepth]" value=""/>
<input type="hidden" name="payu_browser[language]" value=""/>
<?php
}
}
}
/**
* @return array
*/
protected function get_payu_pay_method()
{
$token = sanitize_text_field($_POST['payu_sf_token']);
return $this->get_payu_pay_method_array('CARD_TOKEN', $token ? $token : -1, $this->paytype);
}
/**
* @return void
*/
public function include_payu_sf_scripts()
{
$payu_sdk_url = $this->sandbox==='yes'?'https://secure.snd.payu.com/javascript/sdk':'https://secure.payu.com/javascript/sdk';
wp_enqueue_script('payu-sfsdk', $payu_sdk_url, [], null);
wp_enqueue_script('payu-promise-polyfill', plugins_url( '/assets/js/es6-promise.auto.min.js', PAYU_PLUGIN_FILE ), [], null);
wp_enqueue_script('payu-sf-init', plugins_url( '/assets/js/sf-init.js', PAYU_PLUGIN_FILE ), [], PAYU_PLUGIN_VERSION,
true);
}
}

View File

@@ -0,0 +1,41 @@
<?php
class WC_Gateway_PayuStandard extends WC_PayUGateways
{
function __construct()
{
parent::__construct('payustandard');
if ($this->is_enabled()) {
$this->show_terms_info = false;
if (!is_admin()) {
if (!$this->try_retrieve_banks()) {
add_filter('woocommerce_available_payment_gateways', [$this, 'unset_gateway']);
}
}
}
}
/**
* @return bool
*/
public function try_retrieve_banks()
{
$response = $this->get_payu_response();
if (isset($response) && $response->getStatus() === 'SUCCESS') {
$payMethods = $response->getResponse();
return isset($payMethods->payByLinks);
}
return false;
}
public function payment_fields()
{
parent::payment_fields();
$this->agreements_field();
}
}

View File

@@ -0,0 +1,28 @@
<?php
class WC_Gateway_PayuTwistoPl extends WC_PayUGateways
{
protected $paytype = 'dpt';
function __construct()
{
parent::__construct('payutwistopl');
if ($this->is_enabled()) {
$this->show_terms_info = false;
$this->icon = apply_filters('woocommerce_payu_icon', plugins_url( '/assets/images/twisto-pl.svg', PAYU_PLUGIN_FILE ));
if (!is_admin()) {
if (!$this->try_retrieve_banks()) {
add_filter('woocommerce_available_payment_gateways', [$this, 'unset_gateway']);
}
}
}
}
public function payment_fields()
{
parent::payment_fields();
$this->agreements_field();
}
}

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,2 @@
order deny,allow
deny from all

View File

@@ -0,0 +1,12 @@
<?php
interface AuthType
{
/**
* @return array
*/
public function getHeaders();
}

View File

@@ -0,0 +1,33 @@
<?php
class AuthType_Basic implements AuthType
{
/**
* @var string
*/
private $authBasicToken;
public function __construct($posId, $signatureKey)
{
if (empty($posId)) {
throw new OpenPayU_Exception_Configuration('PosId is empty');
}
if (empty($signatureKey)) {
throw new OpenPayU_Exception_Configuration('SignatureKey is empty');
}
$this->authBasicToken = base64_encode($posId . ':' . $signatureKey);
}
public function getHeaders()
{
return array(
'Content-Type: application/json',
'Accept: application/json',
'Authorization: Basic ' . $this->authBasicToken
);
}
}

View File

@@ -0,0 +1,35 @@
<?php
class AuthType_Oauth implements AuthType
{
/**
* @var OauthResultClientCredentials
*/
private $oauthResult;
public function __construct($clientId, $clientSecret)
{
if (empty($clientId)) {
throw new OpenPayU_Exception_Configuration('ClientId is empty');
}
if (empty($clientSecret)) {
throw new OpenPayU_Exception_Configuration('ClientSecret is empty');
}
try {
$this->oauthResult = OpenPayU_Oauth::getAccessToken();
} catch (OpenPayU_Exception $e) {
throw new OpenPayU_Exception('Oauth error: [code=' . $e->getCode() . '], [message=' . $e->getMessage() . ']');
}
}
public function getHeaders()
{
return array(
'Content-Type: application/json',
'Accept: application/json',
'Authorization: Bearer ' . $this->oauthResult->getAccessToken()
);
}
}

View File

@@ -0,0 +1,14 @@
<?php
class AuthType_TokenRequest implements AuthType
{
public function getHeaders()
{
return array(
'Content-Type: application/x-www-form-urlencoded',
'Accept: */*'
);
}
}

View File

@@ -0,0 +1,423 @@
<?php
/**
* OpenPayU Standard Library
*
* @copyright Copyright (c)
* http://www.payu.com
* http://developers.payu.com
*/
class OpenPayU_Configuration
{
private static $_availableEnvironment = array('custom', 'secure', 'sandbox');
private static $_availableHashAlgorithm = array('SHA', 'SHA-256', 'SHA-384', 'SHA-512');
private static $env = 'secure';
/**
* Merchant Pos ID for Auth Basic and Notification Consume
*/
private static $merchantPosId = '';
/**
* Signature Key for Auth Basic and Notification Consume
*/
private static $signatureKey = '';
/**
* OAuth protocol - default type
*/
private static $oauthGrantType = OauthGrantType::CLIENT_CREDENTIAL;
/**
* OAuth protocol - client_id
*/
private static $oauthClientId = '';
/**
* OAuth protocol - client_secret
*/
private static $oauthClientSecret = '';
/**
* OAuth protocol - email
*/
private static $oauthEmail = '';
/**
* OAuth protocol - extCustomerId
*/
private static $oauthExtCustomerId;
/**
* OAuth protocol - endpoint address
*/
private static $oauthEndpoint = '';
/**
* OAuth protocol - methods for token cache
*/
private static $oauthTokenCache = null;
/**
* Proxy - host
*/
private static $proxyHost = null;
/**
* Proxy - port
*/
private static $proxyPort = null;
/**
* Proxy - user
*/
private static $proxyUser = null;
/**
* Proxy - password
*/
private static $proxyPassword = null;
private static $serviceUrl = '';
private static $hashAlgorithm = 'SHA-256';
private static $sender = 'Generic';
const API_VERSION = '2.1';
const COMPOSER_JSON = "/composer.json";
const DEFAULT_SDK_VERSION = 'PHP SDK 2.3.6';
const OAUTH_CONTEXT = 'pl/standard/user/oauth/authorize';
/**
* @return string
*/
public static function getApiVersion()
{
return self::API_VERSION;
}
/**
* @param string
* @throws OpenPayU_Exception_Configuration
*/
public static function setHashAlgorithm($value)
{
if (!in_array($value, self::$_availableHashAlgorithm)) {
throw new OpenPayU_Exception_Configuration('Hash algorithm "' . $value . '"" is not available');
}
self::$hashAlgorithm = $value;
}
/**
* @return string
*/
public static function getHashAlgorithm()
{
return self::$hashAlgorithm;
}
/**
* @param string $environment
* @param string $domain
* @param string $api
* @param string $version
* @throws OpenPayU_Exception_Configuration
*/
public static function setEnvironment($environment = 'secure', $domain = 'payu.com', $api = 'api/', $version = 'v2_1/')
{
$environment = strtolower($environment);
$domain = strtolower($domain) . '/';
if (!in_array($environment, self::$_availableEnvironment)) {
throw new OpenPayU_Exception_Configuration($environment . ' - is not valid environment');
}
self::$env = $environment;
if ($environment == 'secure') {
self::$serviceUrl = 'https://' . $environment . '.' . $domain . $api . $version;
self::$oauthEndpoint = 'https://' . $environment . '.' . $domain . self::OAUTH_CONTEXT;
} else if ($environment == 'sandbox') {
self::$serviceUrl = 'https://secure.snd.' . $domain . $api . $version;
self::$oauthEndpoint = 'https://secure.snd.' . $domain . self::OAUTH_CONTEXT;
} else if ($environment == 'custom') {
self::$serviceUrl = $domain . $api . $version;
self::$oauthEndpoint = $domain . self::OAUTH_CONTEXT;
}
}
/**
* @return string
*/
public static function getServiceUrl()
{
return self::$serviceUrl;
}
/**
* @return string
*/
public static function getOauthEndpoint()
{
return self::$oauthEndpoint;
}
/**
* @return string
*/
public static function getEnvironment()
{
return self::$env;
}
/**
* @param string
*/
public static function setMerchantPosId($value)
{
self::$merchantPosId = trim($value);
}
/**
* @return string
*/
public static function getMerchantPosId()
{
return self::$merchantPosId;
}
/**
* @param string
*/
public static function setSignatureKey($value)
{
self::$signatureKey = trim($value);
}
/**
* @return string
*/
public static function getSignatureKey()
{
return self::$signatureKey;
}
/**
* @return string
*/
public static function getOauthGrantType()
{
return self::$oauthGrantType;
}
/**
* @param string $oauthGrantType
* @throws OpenPayU_Exception_Configuration
*/
public static function setOauthGrantType($oauthGrantType)
{
if ($oauthGrantType !== OauthGrantType::CLIENT_CREDENTIAL && $oauthGrantType !== OauthGrantType::TRUSTED_MERCHANT) {
throw new OpenPayU_Exception_Configuration('Oauth grand type "' . $oauthGrantType . '"" is not available');
}
self::$oauthGrantType = $oauthGrantType;
}
/**
* @return string
*/
public static function getOauthClientId()
{
return self::$oauthClientId;
}
/**
* @return string
*/
public static function getOauthClientSecret()
{
return self::$oauthClientSecret;
}
/**
* @param mixed $oauthClientId
*/
public static function setOauthClientId($oauthClientId)
{
self::$oauthClientId = trim($oauthClientId);
}
/**
* @param mixed $oauthClientSecret
*/
public static function setOauthClientSecret($oauthClientSecret)
{
self::$oauthClientSecret = trim($oauthClientSecret);
}
/**
* @return mixed
*/
public static function getOauthEmail()
{
return self::$oauthEmail;
}
/**
* @param mixed $oauthEmail
*/
public static function setOauthEmail($oauthEmail)
{
self::$oauthEmail = $oauthEmail;
}
/**
* @return mixed
*/
public static function getOauthExtCustomerId()
{
return self::$oauthExtCustomerId;
}
/**
* @param mixed $oauthExtCustomerId
*/
public static function setOauthExtCustomerId($oauthExtCustomerId)
{
self::$oauthExtCustomerId = $oauthExtCustomerId;
}
/**
* @return null | OauthCacheInterface
*/
public static function getOauthTokenCache()
{
return self::$oauthTokenCache;
}
/**
* @param OauthCacheInterface $oauthTokenCache
* @throws OpenPayU_Exception_Configuration
*/
public static function setOauthTokenCache($oauthTokenCache)
{
if (!$oauthTokenCache instanceof OauthCacheInterface) {
throw new OpenPayU_Exception_Configuration('Oauth token cache class is not instance of OauthCacheInterface');
}
self::$oauthTokenCache = $oauthTokenCache;
}
/**
* @return string | null
*/
public static function getProxyHost()
{
return self::$proxyHost;
}
/**
* @param string | null $proxyHost
*/
public static function setProxyHost($proxyHost)
{
self::$proxyHost = $proxyHost;
}
/**
* @return int | null
*/
public static function getProxyPort()
{
return self::$proxyPort;
}
/**
* @param int | null $proxyPort
*/
public static function setProxyPort($proxyPort)
{
self::$proxyPort = $proxyPort;
}
/**
* @return string | null
*/
public static function getProxyUser()
{
return self::$proxyUser;
}
/**
* @param string | null $proxyUser
*/
public static function setProxyUser($proxyUser)
{
self::$proxyUser = $proxyUser;
}
/**
* @return string | null
*/
public static function getProxyPassword()
{
return self::$proxyPassword;
}
/**
* @param string | null $proxyPassword
*/
public static function setProxyPassword($proxyPassword)
{
self::$proxyPassword = $proxyPassword;
}
/**
* @param string $sender
*/
public static function setSender($sender)
{
self::$sender = $sender;
}
/**
* @return string
*/
public static function getSender()
{
return self::$sender;
}
/**
* @return string
*/
public static function getFullSenderName()
{
return sprintf("%s@%s", self::getSender(), self::getSdkVersion());
}
/**
* @return string
*/
public static function getSdkVersion()
{
$composerFilePath = self::getComposerFilePath();
if (file_exists($composerFilePath)) {
$fileContent = file_get_contents($composerFilePath);
$composerData = json_decode($fileContent);
if (isset($composerData->version) && isset($composerData->extra[0]->engine)) {
return sprintf("%s %s", $composerData->extra[0]->engine, $composerData->version);
}
}
return self::DEFAULT_SDK_VERSION;
}
/**
* @return string
*/
private static function getComposerFilePath()
{
return realpath(dirname(__FILE__)) . '/../../' . self::COMPOSER_JSON;
}
}

View File

@@ -0,0 +1,166 @@
<?php
/**
* OpenPayU Standard Library
*
* @copyright Copyright (c) PayU
* http://www.payu.com
* http://developers.payu.com
*/
class OpenPayU_Http
{
/**
* @param string $pathUrl
* @param string $data
* @param AuthType $authType
* @return mixed
* @throws OpenPayU_Exception_Configuration
* @throws OpenPayU_Exception_Network
*/
public static function doPost($pathUrl, $data, $authType)
{
$response = OpenPayU_HttpCurl::doPayuRequest('POST', $pathUrl, $authType, $data);
return $response;
}
/**
* @param string $pathUrl
* @param AuthType $authType
* @return mixed
* @throws OpenPayU_Exception_Configuration
* @throws OpenPayU_Exception_Network
*/
public static function doGet($pathUrl, $authType)
{
$response = OpenPayU_HttpCurl::doPayuRequest('GET', $pathUrl, $authType);
return $response;
}
/**
* @param string $pathUrl
* @param AuthType $authType
* @return mixed
* @throws OpenPayU_Exception_Configuration
* @throws OpenPayU_Exception_Network
*/
public static function doDelete($pathUrl, $authType)
{
$response = OpenPayU_HttpCurl::doPayuRequest('DELETE', $pathUrl, $authType);
return $response;
}
/**
* @param string $pathUrl
* @param string $data
* @param AuthType $authType
* @return mixed
* @throws OpenPayU_Exception_Configuration
* @throws OpenPayU_Exception_Network
*/
public static function doPut($pathUrl, $data, $authType)
{
$response = OpenPayU_HttpCurl::doPayuRequest('PUT', $pathUrl, $authType, $data);
return $response;
}
/**
* @param $statusCode
* @param null $message
* @throws OpenPayU_Exception
* @throws OpenPayU_Exception_Request
* @throws OpenPayU_Exception_Authorization
* @throws OpenPayU_Exception_Network
* @throws OpenPayU_Exception_ServerMaintenance
* @throws OpenPayU_Exception_ServerError
*/
public static function throwHttpStatusException($statusCode, $message = null)
{
$response = $message->getResponse();
$statusDesc = isset($response->status->statusDesc) ? $response->status->statusDesc : '';
switch ($statusCode) {
case 400:
throw new OpenPayU_Exception_Request($message, $message->getStatus().' - '.$statusDesc, $statusCode);
break;
case 401:
case 403:
throw new OpenPayU_Exception_Authorization($message->getStatus().' - '.$statusDesc, $statusCode);
break;
case 404:
throw new OpenPayU_Exception_Network($message->getStatus().' - '.$statusDesc, $statusCode);
break;
case 408:
throw new OpenPayU_Exception_ServerError('Request timeout', $statusCode);
break;
case 500:
throw new OpenPayU_Exception_ServerError('PayU system is unavailable or your order is not processed.
Error:
[' . $statusDesc . ']', $statusCode);
break;
case 503:
throw new OpenPayU_Exception_ServerMaintenance('Service unavailable', $statusCode);
break;
default:
throw new OpenPayU_Exception_Network('Unexpected HTTP code response', $statusCode);
break;
}
}
/**
* @param $statusCode
* @param ResultError $resultError
* @throws OpenPayU_Exception
* @throws OpenPayU_Exception_Authorization
* @throws OpenPayU_Exception_Network
* @throws OpenPayU_Exception_ServerError
* @throws OpenPayU_Exception_ServerMaintenance
*/
public static function throwErrorHttpStatusException($statusCode, $resultError)
{
switch ($statusCode) {
case 400:
throw new OpenPayU_Exception($resultError->getError().' - '.$resultError->getErrorDescription(), $statusCode);
break;
case 401:
case 403:
throw new OpenPayU_Exception_Authorization($resultError->getError().' - '.$resultError->getErrorDescription(), $statusCode);
break;
case 404:
throw new OpenPayU_Exception_Network($resultError->getError().' - '.$resultError->getErrorDescription(), $statusCode);
break;
case 408:
throw new OpenPayU_Exception_ServerError('Request timeout', $statusCode);
break;
case 500:
throw new OpenPayU_Exception_ServerError('PayU system is unavailable. Error: [' . $resultError->getErrorDescription() . ']', $statusCode);
break;
case 503:
throw new OpenPayU_Exception_ServerMaintenance('Service unavailable', $statusCode);
break;
default:
throw new OpenPayU_Exception_Network('Unexpected HTTP code response', $statusCode);
break;
}
}
}

View File

@@ -0,0 +1,111 @@
<?php
/**
* OpenPayU Standard Library
*
* @copyright Copyright (c) PayU
* http://www.payu.com
* http://developers.payu.com
*/
if (!defined('CURL_SSLVERSION_TLSv1_2')) {
define('CURL_SSLVERSION_TLSv1_2', 6);
}
class OpenPayU_HttpCurl
{
/**
* @var
*/
static $headers;
/**
* @param $requestType
* @param $pathUrl
* @param $data
* @param AuthType $auth
* @return array
* @throws OpenPayU_Exception_Configuration
* @throws OpenPayU_Exception_Network
*/
public static function doPayuRequest($requestType, $pathUrl, $auth, $data = null)
{
if (empty($pathUrl)) {
throw new OpenPayU_Exception_Configuration('The endpoint is empty');
}
$ch = curl_init($pathUrl);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, $requestType);
curl_setopt($ch, CURLOPT_ENCODING, 'gzip');
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, false);
curl_setopt($ch, CURLOPT_HEADER, false);
curl_setopt($ch, CURLOPT_HTTPHEADER, $auth->getHeaders());
curl_setopt($ch, CURLOPT_HEADERFUNCTION, 'OpenPayU_HttpCurl::readHeader');
if ($data) {
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
}
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 10);
curl_setopt($ch, CURLOPT_TIMEOUT, 60);
curl_setopt($ch, CURLOPT_SSLVERSION, CURL_SSLVERSION_TLSv1_2);
if ($proxy = self::getProxy()) {
curl_setopt($ch, CURLOPT_PROXY, $proxy);
if ($proxyAuth = self::getProxyAuth()) {
curl_setopt($ch, CURLOPT_PROXYUSERPWD, $proxyAuth);
}
}
$response = curl_exec($ch);
$httpStatus = curl_getinfo($ch, CURLINFO_HTTP_CODE);
if($response === false) {
throw new OpenPayU_Exception_Network(curl_error($ch));
}
curl_close($ch);
return array('code' => $httpStatus, 'response' => trim($response));
}
/**
* @param array $headers
*
* @return mixed
*/
public static function getSignature($headers)
{
foreach($headers as $name => $value)
{
if(preg_match('/X-OpenPayU-Signature/i', $name) || preg_match('/OpenPayu-Signature/i', $name))
return $value;
}
return null;
}
/**
* @param resource $ch
* @param string $header
* @return int
*/
public static function readHeader($ch, $header)
{
if( preg_match('/([^:]+): (.+)/m', $header, $match) ) {
self::$headers[$match[1]] = trim($match[2]);
}
return strlen($header);
}
private static function getProxy()
{
return OpenPayU_Configuration::getProxyHost() != null ? OpenPayU_Configuration::getProxyHost()
. (OpenPayU_Configuration::getProxyPort() ? ':' . OpenPayU_Configuration::getProxyPort() : '') : false;
}
private static function getProxyAuth()
{
return OpenPayU_Configuration::getProxyUser() != null ? OpenPayU_Configuration::getProxyUser()
. (OpenPayU_Configuration::getProxyPassword() ? ':' . OpenPayU_Configuration::getProxyPassword() : '') : false;
}
}

View File

@@ -0,0 +1,100 @@
<?php
class PayuShop
{
/** @var string */
private $shopId;
/** @var string */
private $name;
/** @var string */
private $currencyCode;
/** @var PayuShopBalance */
private $balance;
/**
* @return string
*/
public function getShopId()
{
return $this->shopId;
}
/**
* @param string $shopId
* @return PayuShop
*/
public function setShopId($shopId)
{
$this->shopId = $shopId;
return $this;
}
/**
* @return string
*/
public function getName()
{
return $this->name;
}
/**
* @param string $name
* @return PayuShop
*/
public function setName($name)
{
$this->name = $name;
return $this;
}
/**
* @return string
*/
public function getCurrencyCode()
{
return $this->currencyCode;
}
/**
* @param string $currencyCode
* @return PayuShop
*/
public function setCurrencyCode($currencyCode)
{
$this->currencyCode = $currencyCode;
return $this;
}
/**
* @return PayuShopBalance
*/
public function getBalance()
{
return $this->balance;
}
/**
* @param PayuShopBalance $balance
* @return PayuShop
*/
public function setBalance($balance)
{
$this->balance = $balance;
return $this;
}
/**
* @return string
*/
public function __toString()
{
return 'PayuShop [shopId=' . $this->shopId .
', name=' . $this->name .
', currencyCode=' . $this->currencyCode .
', balance=' . $this->balance .
']';
}
}

View File

@@ -0,0 +1,78 @@
<?php
class PayuShopBalance
{
/** @var string */
private $currencyCode;
/** @var int */
private $total;
/** @var int */
private $available;
/**
* @return string
*/
public function getCurrencyCode()
{
return $this->currencyCode;
}
/**
* @param string $currencyCode
* @return PayuShopBalance
*/
public function setCurrencyCode($currencyCode)
{
$this->currencyCode = $currencyCode;
return $this;
}
/**
* @return int
*/
public function getTotal()
{
return $this->total;
}
/**
* @param int $total
* @return PayuShopBalance
*/
public function setTotal($total)
{
$this->total = $total;
return $this;
}
/**
* @return int
*/
public function getAvailable()
{
return $this->available;
}
/**
* @param int $available
* @return PayuShopBalance
*/
public function setAvailable($available)
{
$this->available = $available;
return $this;
}
/**
* @return string
*/
public function __toString()
{
return 'PayuShopBalance [currencyCode=' . $this->currencyCode .
', total=' . $this->total .
', available=' . $this->available .
']';
}
}

View File

@@ -0,0 +1,40 @@
<?php
class OauthCacheFile implements OauthCacheInterface
{
private $directory;
/**
* @param string $directory
* @throws OpenPayU_Exception_Configuration
*/
public function __construct($directory = null)
{
if ($directory === null) {
$directory = dirname(__FILE__).'/../../../Cache';
}
if (!is_dir($directory) || !is_writable($directory)) {
throw new OpenPayU_Exception_Configuration('Cache directory [' . $directory . '] not exist or not writable.');
}
$this->directory = $directory . (substr($directory, -1) != '/' ? '/' : '');
}
public function get($key)
{
$cache = @file_get_contents($this->directory . md5($key));
return $cache === false ? null : unserialize($cache);
}
public function set($key, $value)
{
return @file_put_contents($this->directory . md5($key), serialize($value));
}
public function invalidate($key)
{
return @unlink($this->directory . md5($key));
}
}

View File

@@ -0,0 +1,26 @@
<?php
interface OauthCacheInterface
{
/**
* @param string $key
* @return null | object
*/
public function get($key);
/**
* @param string $key
* @param object $value
* @return bool
*/
public function set($key, $value);
/**
* @param string $key
* @return bool
*/
public function invalidate($key);
}

View File

@@ -0,0 +1,43 @@
<?php
class OauthCacheMemcached implements OauthCacheInterface
{
private $memcached;
/**
* @param string $host
* @param int $port
* @param int $weight
* @throws OpenPayU_Exception_Configuration
*/
public function __construct($host = 'localhost', $port = 11211, $weight = 0)
{
if (!class_exists('Memcached')) {
throw new OpenPayU_Exception_Configuration('PHP Memcached extension not installed.');
}
$this->memcached = new Memcached('PayU');
$this->memcached->addServer($host, $port, $weight);
$stats = $this->memcached->getStats();
if ($stats[$host . ':' . $port]['pid'] == -1) {
throw new OpenPayU_Exception_Configuration('Problem with connection to memcached server [host=' . $host . '] [port=' . $port . '] [weight=' . $weight . ']');
}
}
public function get($key)
{
$cache = $this->memcached->get($key);
return $cache === false ? null : unserialize($cache);
}
public function set($key, $value)
{
return $this->memcached->set($key, serialize($value));
}
public function invalidate($key)
{
return $this->memcached->delete($key);
}
}

View File

@@ -0,0 +1,123 @@
<?php
class OpenPayU_Oauth
{
/**
* @var OauthCacheInterface
*/
private static $oauthTokenCache;
const CACHE_KEY = 'AccessToken';
/**
* @param string $clientId
* @param string $clientSecret
* @return OauthResultClientCredentials
* @throws OpenPayU_Exception_ServerError
*/
public static function getAccessToken($clientId = null, $clientSecret = null)
{
if (OpenPayU_Configuration::getOauthGrantType() === OauthGrantType::TRUSTED_MERCHANT) {
return self::retrieveAccessToken($clientId, $clientSecret);
}
$cacheKey = self::CACHE_KEY . OpenPayU_Configuration::getOauthClientId();
self::getOauthTokenCache();
$tokenCache = self::$oauthTokenCache->get($cacheKey);
if ($tokenCache instanceof OauthResultClientCredentials && !$tokenCache->hasExpire()) {
return $tokenCache;
}
self::$oauthTokenCache->invalidate($cacheKey);
$response = self::retrieveAccessToken($clientId, $clientSecret);
self::$oauthTokenCache->set($cacheKey, $response);
return $response;
}
/**
* @param $clientId
* @param $clientSecret
* @return OauthResultClientCredentials
* @throws OpenPayU_Exception_ServerError
*/
private static function retrieveAccessToken($clientId, $clientSecret)
{
$authType = new AuthType_TokenRequest();
$oauthUrl = OpenPayU_Configuration::getOauthEndpoint();
$data = array(
'grant_type' => OpenPayU_Configuration::getOauthGrantType(),
'client_id' => $clientId ? $clientId : OpenPayU_Configuration::getOauthClientId(),
'client_secret' => $clientSecret ? $clientSecret : OpenPayU_Configuration::getOauthClientSecret()
);
if (OpenPayU_Configuration::getOauthGrantType() === OauthGrantType::TRUSTED_MERCHANT) {
$data['email'] = OpenPayU_Configuration::getOauthEmail();
$data['ext_customer_id'] = OpenPayU_Configuration::getOauthExtCustomerId();
}
return self::parseResponse(OpenPayU_Http::doPost($oauthUrl, http_build_query($data, '', '&'), $authType));
}
/**
* Parse response from PayU
*
* @param array $response
* @return OauthResultClientCredentials
* @throws OpenPayU_Exception
* @throws OpenPayU_Exception_Authorization
* @throws OpenPayU_Exception_Network
* @throws OpenPayU_Exception_ServerError
* @throws OpenPayU_Exception_ServerMaintenance
*/
private static function parseResponse($response)
{
$httpStatus = $response['code'];
if ($httpStatus == 500) {
$result = new ResultError();
$result->setErrorDescription($response['response']);
OpenPayU_Http::throwErrorHttpStatusException($httpStatus, $result);
}
$message = OpenPayU_Util::convertJsonToArray($response['response'], true);
if (json_last_error() == JSON_ERROR_SYNTAX) {
throw new OpenPayU_Exception_ServerError('Incorrect json response. Response: [' . $response['response'] . ']');
}
if ($httpStatus == 200) {
$result = new OauthResultClientCredentials();
$result->setAccessToken($message['access_token'])
->setTokenType($message['token_type'])
->setExpiresIn($message['expires_in'])
->setGrantType($message['grant_type'])
->calculateExpireDate(new \DateTime());
return $result;
}
$result = new ResultError();
$result->setError($message['error'])
->setErrorDescription($message['error_description']);
OpenPayU_Http::throwErrorHttpStatusException($httpStatus, $result);
}
private static function getOauthTokenCache()
{
$oauthTokenCache = OpenPayU_Configuration::getOauthTokenCache();
if (!$oauthTokenCache instanceof OauthCacheInterface) {
$oauthTokenCache = new OauthCacheFile();
OpenPayU_Configuration::setOauthTokenCache($oauthTokenCache);
}
self::$oauthTokenCache = $oauthTokenCache;
}
}

View File

@@ -0,0 +1,7 @@
<?php
abstract class OauthGrantType
{
const CLIENT_CREDENTIAL = 'client_credentials';
const TRUSTED_MERCHANT = 'trusted_merchant';
}

View File

@@ -0,0 +1,121 @@
<?php
class OauthResultClientCredentials
{
/**
* @var string
*/
private $accessToken;
/**
* @var string
*/
private $tokenType;
/**
* @var string
*/
private $expiresIn;
/**
* @var string
*/
private $grantType;
/**
* @var DateTime
*/
private $expireDate;
/**
* @return string
*/
public function getAccessToken()
{
return $this->accessToken;
}
/**
* @param string $accessToken
* @return OauthResultClientCredentials
*/
public function setAccessToken($accessToken)
{
$this->accessToken = $accessToken;
return $this;
}
/**
* @return string
*/
public function getTokenType()
{
return $this->tokenType;
}
/**
* @param string $tokenType
* @return OauthResultClientCredentials
*/
public function setTokenType($tokenType)
{
$this->tokenType = $tokenType;
return $this;
}
/**
* @return string
*/
public function getExpiresIn()
{
return $this->expiresIn;
}
/**
* @param string $expiresIn
* @return OauthResultClientCredentials
*/
public function setExpiresIn($expiresIn)
{
$this->expiresIn = $expiresIn;
return $this;
}
/**
* @return string
*/
public function getGrantType()
{
return $this->grantType;
}
/**
* @param string $grantType
* @return OauthResultClientCredentials
*/
public function setGrantType($grantType)
{
$this->grantType = $grantType;
return $this;
}
/**
* @return DateTime
*/
public function getExpireDate()
{
return $this->expireDate;
}
/**
* @param DateTime $date
*/
public function calculateExpireDate($date)
{
$this->expireDate = $date->add(new DateInterval('PT' . ($this->expiresIn - 60) . 'S'));
}
public function hasExpire()
{
return ($this->expireDate <= new DateTime());
}
}

View File

@@ -0,0 +1,65 @@
<?php
/**
* OpenPayU Standard Library
*
* @copyright Copyright (c) PayU
* http://www.payu.com
* http://developers.payu.com
*/
class OpenPayU
{
protected static function build($data)
{
$instance = new OpenPayU_Result();
if (array_key_exists('status', $data) && $data['status'] == 'WARNING_CONTINUE_REDIRECT') {
$data['status'] = 'SUCCESS';
$data['response']['status']['statusCode'] = 'SUCCESS';
}
$instance->init($data);
return $instance;
}
/**
* @param $data
* @param $incomingSignature
* @throws OpenPayU_Exception_Authorization
*/
public static function verifyDocumentSignature($data, $incomingSignature)
{
$sign = OpenPayU_Util::parseSignature($incomingSignature);
if ($sign === null || !array_key_exists('signature', $sign) || !array_key_exists('algorithm', $sign)) {
throw new OpenPayU_Exception_Authorization('Signature not found');
}
if (false === OpenPayU_Util::verifySignature(
$data,
$sign['signature'],
OpenPayU_Configuration::getSignatureKey(),
$sign['algorithm'])
) {
throw new OpenPayU_Exception_Authorization('Invalid signature - ' . $sign['signature']);
}
}
/**
* @return AuthType
* @throws OpenPayU_Exception
*/
protected static function getAuth()
{
if (OpenPayU_Configuration::getOauthClientId() && OpenPayU_Configuration::getOauthClientSecret()) {
$authType = new AuthType_Oauth(OpenPayU_Configuration::getOauthClientId(), OpenPayU_Configuration::getOauthClientSecret());
} else {
$authType = new AuthType_Basic(OpenPayU_Configuration::getMerchantPosId(), OpenPayU_Configuration::getSignatureKey());
}
return $authType;
}
}

View File

@@ -0,0 +1,57 @@
<?php
/**
* OpenPayU Standard Library
*
* @copyright Copyright (c) PayU
* http://www.payu.com
* http://developers.payu.com
*/
class OpenPayU_Exception extends \Exception
{
}
class OpenPayU_Exception_Request extends OpenPayU_Exception
{
/** @var stdClass|null */
private $originalResponseMessage;
public function __construct($originalResponseMessage, $message = "", $code = 0, $previous = null)
{
$this->originalResponseMessage = $originalResponseMessage;
parent::__construct($message, $code, $previous);
}
/** @return null|stdClass */
public function getOriginalResponse()
{
return $this->originalResponseMessage;
}
}
class OpenPayU_Exception_Configuration extends OpenPayU_Exception
{
}
class OpenPayU_Exception_Network extends OpenPayU_Exception
{
}
class OpenPayU_Exception_ServerError extends OpenPayU_Exception
{
}
class OpenPayU_Exception_ServerMaintenance extends OpenPayU_Exception
{
}
class OpenPayU_Exception_Authorization extends OpenPayU_Exception
{
}

View File

@@ -0,0 +1,23 @@
<?php
/**
* OpenPayU Standard Library
*
* @copyright Copyright (c) PayU
* http://www.payu.com
* http://developers.payu.com
*/
/**
* Class OpenPayuOrderStatus
*/
abstract class OpenPayuOrderStatus
{
const STATUS_NEW = 'NEW';
const STATUS_PENDING = 'PENDING';
const STATUS_CANCELED = 'CANCELED';
const STATUS_REJECTED = 'REJECTED';
const STATUS_COMPLETED = 'COMPLETED';
const STATUS_WAITING_FOR_CONFIRMATION = 'WAITING_FOR_CONFIRMATION';
}

View File

@@ -0,0 +1,19 @@
<?php
/**
* OpenPayU Standard Library
*
* @copyright Copyright (c) PayU
* http://www.payu.com
* http://developers.payu.com
*/
/**
* Class OpenPayuOrderStatus
*/
abstract class OpenPayuRefundStatus
{
const STATUS_PENDING = 'PENDING';
const STATUS_CANCELED = 'CANCELED';
const STATUS_FINALIZED = 'FINALIZED';
}

View File

@@ -0,0 +1,224 @@
<?php
/**
* OpenPayU Standard Library
*
* @copyright Copyright (c) PayU
* http://www.payu.com
* http://developers.payu.com
*/
class OpenPayU_Result
{
private $status = '';
private $error = '';
private $success = 0;
private $request = '';
/** @var object */
private $response;
private $sessionId = '';
private $message = '';
private $countryCode = '';
private $reqId = '';
/**
* @access public
* @return string
*/
public function getStatus()
{
return $this->status;
}
/**
* @access public
* @param $value
*/
public function setStatus($value)
{
$this->status = $value;
}
/**
* @access public
* @return string
*/
public function getError()
{
return $this->error;
}
/**
* @access public
* @param $value
*/
public function setError($value)
{
$this->error = $value;
}
/**
* @access public
* @return int
*/
public function getSuccess()
{
return $this->success;
}
/**
* @access public
* @param $value
*/
public function setSuccess($value)
{
$this->success = $value;
}
/**
* @access public
* @return string
*/
public function getRequest()
{
return $this->request;
}
/**
* @access public
* @param $value
*/
public function setRequest($value)
{
$this->request = $value;
}
/**
* @access public
* @return object
*/
public function getResponse()
{
return $this->response;
}
/**
* @access public
* @param $value
*/
public function setResponse($value)
{
$this->response = $value;
}
/**
* @access public
* @return string
*/
public function getSessionId()
{
return $this->sessionId;
}
/**
* @access public
* @param $value
*/
public function setSessionId($value)
{
$this->sessionId = $value;
}
/**
* @access public
* @return string
*/
public function getMessage()
{
return $this->message;
}
/**
* @access public
* @param $value
*/
public function setMessage($value)
{
$this->message = $value;
}
/**
* @access public
* @return string
*/
public function getCountryCode()
{
return $this->countryCode;
}
/**
* @access public
* @param $value
*/
public function setCountryCode($value)
{
$this->countryCode = $value;
}
/**
* @access public
* @return string
*/
public function getReqId()
{
return $this->reqId;
}
/**
* @access public
* @param $value
*/
public function setReqId($value)
{
$this->reqId = $value;
}
public function init($attributes)
{
$attributes = OpenPayU_Util::parseArrayToObject($attributes);
if (!empty($attributes)) {
foreach ($attributes as $name => $value) {
$this->set($name, $value);
}
}
}
public function set($name, $value)
{
$this->{$name} = $value;
}
public function __get($name)
{
if (isset($this->{$name}))
return $this->name;
return null;
}
public function __call($methodName, $args) {
if (preg_match('~^(set|get)([A-Z])(.*)$~', $methodName, $matches)) {
$property = strtolower($matches[2]) . $matches[3];
if (!property_exists($this, $property)) {
throw new Exception('Property ' . $property . ' not exists');
}
switch($matches[1]) {
case 'get':
$this->checkArguments($args, 0, 0, $methodName);
return $this->get($property);
case 'default':
throw new Exception('Method ' . $methodName . ' not exists');
}
}
}
}

View File

@@ -0,0 +1,58 @@
<?php
/**
* OpenPayU Standard Library
*
* @copyright Copyright (c) PayU
* http://www.payu.com
* http://developers.payu.com
*/
class ResultError
{
/**
* @var string
*/
private $error;
/**
* @var string
*/
private $errorDescription;
/**
* @return string
*/
public function getError()
{
return $this->error;
}
/**
* @param string $error
* @return ResultError
*/
public function setError($error)
{
$this->error = $error;
return $this;
}
/**
* @return string
*/
public function getErrorDescription()
{
return $this->errorDescription;
}
/**
* @param string $errorDescription
* @return ResultError
*/
public function setErrorDescription($errorDescription)
{
$this->errorDescription = $errorDescription;
return $this;
}
}

View File

@@ -0,0 +1,300 @@
<?php
/**
* OpenPayU Standard Library
*
* @copyright Copyright (c) PayU
* http://www.payu.com
* http://developers.payu.com
*/
class OpenPayU_Util
{
/**
* Function generate sign data
*
* @param array $data
* @param string $algorithm
* @param string $merchantPosId
* @param string $signatureKey
*
* @return string
*
* @throws OpenPayU_Exception_Configuration
*/
public static function generateSignData(array $data, $algorithm = 'SHA-256', $merchantPosId = '', $signatureKey = '')
{
if (empty($signatureKey))
throw new OpenPayU_Exception_Configuration('Merchant Signature Key should not be null or empty.');
if (empty($merchantPosId))
throw new OpenPayU_Exception_Configuration('MerchantPosId should not be null or empty.');
$contentForSign = '';
ksort($data);
foreach ($data as $key => $value) {
$contentForSign .= $key . '=' . urlencode($value) . '&';
}
if (in_array($algorithm, array('SHA-256', 'SHA'))) {
$hashAlgorithm = 'sha256';
$algorithm = 'SHA-256';
} else if ($algorithm == 'SHA-384') {
$hashAlgorithm = 'sha384';
$algorithm = 'SHA-384';
} else if ($algorithm == 'SHA-512') {
$hashAlgorithm = 'sha512';
$algorithm = 'SHA-512';
}
$signature = hash($hashAlgorithm, $contentForSign . $signatureKey);
$signData = 'sender=' . $merchantPosId . ';algorithm=' . $algorithm . ';signature=' . $signature;
return $signData;
}
/**
* Function returns signature data object
*
* @param string $data
*
* @return null|array
*/
public static function parseSignature($data)
{
if (empty($data)) {
return null;
}
$signatureData = array();
$list = explode(';', rtrim($data, ';'));
if (empty($list)) {
return null;
}
foreach ($list as $value) {
$explode = explode('=', $value);
if (count($explode) != 2) {
return null;
}
$signatureData[$explode[0]] = $explode[1];
}
return $signatureData;
}
/**
* Function returns signature validate
*
* @param string $message
* @param string $signature
* @param string $signatureKey
* @param string $algorithm
*
* @return bool
*/
public static function verifySignature($message, $signature, $signatureKey, $algorithm = 'MD5')
{
if (isset($signature)) {
if ($algorithm === 'MD5') {
$hash = md5($message . $signatureKey);
} else if (in_array($algorithm, array('SHA', 'SHA1', 'SHA-1'))) {
$hash = sha1($message . $signatureKey);
} else {
$hash = hash('sha256', $message . $signatureKey);
}
if (strcmp($signature, $hash) == 0) {
return true;
}
}
return false;
}
/**
* Function builds OpenPayU Json Document
*
* @param array $data
* @param string $rootElement
*
* @return null|string
*/
public static function buildJsonFromArray($data, $rootElement = '')
{
if (!is_array($data)) {
return null;
}
if (!empty($rootElement)) {
$data = array($rootElement => $data);
}
$data = self::setSenderProperty($data);
return json_encode($data, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
}
/**
* @param string $data
* @param bool $assoc
* @return mixed|null
*/
public static function convertJsonToArray($data, $assoc = false)
{
if (empty($data)) {
return null;
}
return json_decode($data, $assoc);
}
/**
* @param array $array
* @return bool|stdClass
*/
public static function parseArrayToObject($array)
{
if (!is_array($array)) {
return $array;
}
if (self::isAssocArray($array)) {
$object = new stdClass();
} else {
$object = array();
}
if (is_array($array) && count($array) > 0) {
foreach ($array as $name => $value) {
$name = trim($name);
if (isset($name)) {
if (is_numeric($name)) {
$object[] = self::parseArrayToObject($value);
} else {
$object->$name = self::parseArrayToObject($value);
}
}
}
return $object;
}
return false;
}
/**
* @return mixed
*/
public static function getRequestHeaders()
{
if (!function_exists('apache_request_headers')) {
$headers = array();
foreach ($_SERVER as $key => $value) {
if (substr($key, 0, 5) == 'HTTP_') {
$headers[str_replace(' ', '-', ucwords(str_replace('_', ' ', strtolower(substr($key, 5)))))] = $value;
}
}
return $headers;
} else {
return apache_request_headers();
}
}
/**
* @param $array
* @param string $namespace
* @param array $outputFields
* @return string
*/
public static function convertArrayToHtmlForm($array, $namespace = '', &$outputFields = [])
{
$i = 0;
$htmlOutput = "";
$assoc = self::isAssocArray($array);
foreach ($array as $key => $value) {
if ($namespace && $assoc) {
$key = $namespace . '.' . $key;
} elseif ($namespace && !$assoc) {
$key = $namespace . '[' . $i++ . ']';
}
if (is_array($value)) {
$htmlOutput .= self::convertArrayToHtmlForm($value, $key, $outputFields);
} else {
$htmlOutput .= sprintf("<input type=\"hidden\" name=\"%s\" value=\"%s\" />\n", htmlspecialchars($key)
, htmlspecialchars($value));
$outputFields[$key] = $value;
}
}
return $htmlOutput;
}
/**
* @param $arr
* @return bool
*/
public static function isAssocArray($arr)
{
$arrKeys = array_keys($arr);
sort($arrKeys, SORT_NUMERIC);
return $arrKeys !== range(0, count($arr) - 1);
}
/**
* @param array $data
* @return array
*/
private static function setSenderProperty($data)
{
$data['properties'][0] = array(
'name' => 'sender',
'value' => OpenPayU_Configuration::getFullSenderName()
);
return $data;
}
public static function statusDesc($response)
{
$msg = '';
switch ($response) {
case 'SUCCESS':
$msg = 'Request has been processed correctly.';
break;
case 'DATA_NOT_FOUND':
$msg = 'Data indicated in the request is not available in the PayU system.';
break;
case 'WARNING_CONTINUE_3DS':
$msg = '3DS authorization required. Redirect the Buyer to PayU to continue the 3DS process.';
break;
case 'WARNING_CONTINUE_CVV':
$msg = 'CVV/CVC authorization required.';
break;
case 'ERROR_SYNTAX':
$msg = 'BIncorrect request syntax. Supported formats are JSON or XML.';
break;
case 'ERROR_VALUE_INVALID':
$msg = 'One or more required values are incorrect.';
break;
case 'ERROR_VALUE_MISSING':
$msg = 'One or more required values are missing.';
break;
case 'BUSINESS_ERROR':
case 'ERROR_INTERNAL':
$msg = 'PayU system is unavailable. Try again later.';
break;
case 'GENERAL_ERROR':
$msg = 'Unexpected error. Try again later.';
break;
}
return $msg;
}
}

View File

@@ -0,0 +1,293 @@
<?php
/**
* OpenPayU Standard Library
*
* @copyright Copyright (c) PayU
* http://www.payu.com
* http://developers.payu.com
*/
/**
* Class OpenPayU_Order
*/
class OpenPayU_Order extends OpenPayU
{
const ORDER_SERVICE = 'orders/';
const ORDER_TRANSACTION_SERVICE = 'transactions';
const ORDER_REFUND_SERVICE = 'refunds';
const SUCCESS = 'SUCCESS';
/**
* @var array Default form parameters
*/
protected static $defaultFormParams = array(
'formClass' => '',
'formId' => 'payu-payment-form',
'submitClass' => '',
'submitId' => '',
'submitContent' => '',
'submitTarget' => '_blank'
);
/**
* Creates new Order
* - Sends to PayU OrderCreateRequest
*
* @param array $order A array containing full Order
* @return object $result Response array with OrderCreateResponse
* @throws OpenPayU_Exception
*/
public static function create($order)
{
$data = OpenPayU_Util::buildJsonFromArray($order);
if (empty($data)) {
throw new OpenPayU_Exception('Empty message OrderCreateRequest');
}
try {
$authType = self::getAuth();
} catch (OpenPayU_Exception $e) {
throw new OpenPayU_Exception($e->getMessage(), $e->getCode());
}
$pathUrl = OpenPayU_Configuration::getServiceUrl() . self::ORDER_SERVICE;
$result = self::verifyResponse(OpenPayU_Http::doPost($pathUrl, $data, $authType), 'OrderCreateResponse');
return $result;
}
/**
* Retrieves information about the order
* - Sends to PayU OrderRetrieveRequest
*
* @param string $orderId PayU OrderId sent back in OrderCreateResponse
* @return OpenPayU_Result $result Response array with OrderRetrieveResponse
* @throws OpenPayU_Exception
*/
public static function retrieve($orderId)
{
if (empty($orderId)) {
throw new OpenPayU_Exception('Empty value of orderId');
}
try {
$authType = self::getAuth();
} catch (OpenPayU_Exception $e) {
throw new OpenPayU_Exception($e->getMessage(), $e->getCode());
}
$pathUrl = OpenPayU_Configuration::getServiceUrl() . self::ORDER_SERVICE . $orderId;
$result = self::verifyResponse(OpenPayU_Http::doGet($pathUrl, $authType), 'OrderRetrieveResponse');
return $result;
}
/**
* Retrieves information about the order transaction
* - Sends to PayU TransactionRetrieveRequest
*
* @param string $orderId PayU OrderId sent back in OrderCreateResponse
* @return OpenPayU_Result $result Response array with TransactionRetrieveResponse
* @throws OpenPayU_Exception
*/
public static function retrieveTransaction($orderId)
{
if (empty($orderId)) {
throw new OpenPayU_Exception('Empty value of orderId');
}
try {
$authType = self::getAuth();
} catch (OpenPayU_Exception $e) {
throw new OpenPayU_Exception($e->getMessage(), $e->getCode());
}
$pathUrl = OpenPayU_Configuration::getServiceUrl() . self::ORDER_SERVICE . $orderId . '/' . self::ORDER_TRANSACTION_SERVICE;
$result = self::verifyResponse(OpenPayU_Http::doGet($pathUrl, $authType), 'TransactionRetrieveResponse');
return $result;
}
/**
* Retrieves information about the order transaction
* - Sends to PayU TransactionRetrieveRequest
*
* @param string $orderId PayU OrderId sent back in OrderCreateResponse
* @return OpenPayU_Result $result Response array with TransactionRetrieveResponse
* @throws OpenPayU_Exception
*/
public static function retrieveRefund($orderId)
{
if (empty($orderId)) {
throw new OpenPayU_Exception('Empty value of orderId');
}
try {
$authType = self::getAuth();
} catch (OpenPayU_Exception $e) {
throw new OpenPayU_Exception($e->getMessage(), $e->getCode());
}
$pathUrl = OpenPayU_Configuration::getServiceUrl() . self::ORDER_SERVICE . $orderId . '/' . self::ORDER_REFUND_SERVICE;
$result = self::verifyResponse(OpenPayU_Http::doGet($pathUrl, $authType), 'TransactionRetrieveResponse');
return $result;
}
/**
* Cancels Order
* - Sends to PayU OrderCancelRequest
*
* @param string $orderId PayU OrderId sent back in OrderCreateResponse
* @return OpenPayU_Result $result Response array with OrderCancelResponse
* @throws OpenPayU_Exception
*/
public static function cancel($orderId)
{
if (empty($orderId)) {
throw new OpenPayU_Exception('Empty value of orderId');
}
try {
$authType = self::getAuth();
} catch (OpenPayU_Exception $e) {
throw new OpenPayU_Exception($e->getMessage(), $e->getCode());
}
$pathUrl = OpenPayU_Configuration::getServiceUrl() . self::ORDER_SERVICE . $orderId;
$result = self::verifyResponse(OpenPayU_Http::doDelete($pathUrl, $authType), 'OrderCancelResponse');
return $result;
}
/**
* Updates Order status
* - Sends to PayU OrderStatusUpdateRequest
*
* @param array $orderStatusUpdate A array containing full OrderStatus
* @return OpenPayU_Result $result Response array with OrderStatusUpdateResponse
* @throws OpenPayU_Exception
*/
public static function statusUpdate($orderStatusUpdate)
{
if (empty($orderStatusUpdate)) {
throw new OpenPayU_Exception('Empty order status data');
}
try {
$authType = self::getAuth();
} catch (OpenPayU_Exception $e) {
throw new OpenPayU_Exception($e->getMessage(), $e->getCode());
}
$data = OpenPayU_Util::buildJsonFromArray($orderStatusUpdate);
$pathUrl = OpenPayU_Configuration::getServiceUrl() . self::ORDER_SERVICE . $orderStatusUpdate['orderId'] . '/status';
$result = self::verifyResponse(OpenPayU_Http::doPut($pathUrl, $data, $authType), 'OrderStatusUpdateResponse');
return $result;
}
/**
* Consume notification message
*
* @access public
* @param $data string Request array received from with PayU OrderNotifyRequest
* @return null|OpenPayU_Result Response array with OrderNotifyRequest
* @throws OpenPayU_Exception
*/
public static function consumeNotification($data)
{
if (empty($data)) {
throw new OpenPayU_Exception('Empty value of data');
}
$headers = OpenPayU_Util::getRequestHeaders();
$incomingSignature = OpenPayU_HttpCurl::getSignature($headers);
self::verifyDocumentSignature($data, $incomingSignature);
return OpenPayU_Order::verifyResponse(array('response' => $data, 'code' => 200), 'OrderNotifyRequest');
}
/**
* Verify response from PayU
*
* @param array $response
* @param string $messageName
* @return null|OpenPayU_Result
* @throws OpenPayU_Exception
* @throws OpenPayU_Exception_Authorization
* @throws OpenPayU_Exception_Network
* @throws OpenPayU_Exception_ServerError
* @throws OpenPayU_Exception_ServerMaintenance
*/
public static function verifyResponse($response, $messageName)
{
$data = array();
$httpStatus = $response['code'];
$message = OpenPayU_Util::convertJsonToArray($response['response'], true);
$data['status'] = isset($message['status']['statusCode']) ? $message['status']['statusCode'] : null;
if (json_last_error() == JSON_ERROR_SYNTAX) {
$data['response'] = $response['response'];
} elseif (isset($message[$messageName])) {
unset($message[$messageName]['Status']);
$data['response'] = $message[$messageName];
} elseif (isset($message)) {
$data['response'] = $message;
unset($message['status']);
}
$result = self::build($data);
if ($httpStatus == 200 || $httpStatus == 201 || $httpStatus == 422 || $httpStatus == 301 || $httpStatus == 302) {
return $result;
}
OpenPayU_Http::throwHttpStatusException($httpStatus, $result);
}
/**
* Generate a form body for hosted order
*
* @access public
* @param array $order an array containing full Order
* @param array $params an optional array with form elements' params
* @return string Response html form
* @throws OpenPayU_Exception_Configuration
*/
public static function hostedOrderForm($order, $params = array())
{
$orderFormUrl = OpenPayU_Configuration::getServiceUrl() . 'orders';
$formFieldValuesAsArray = array();
$htmlFormFields = OpenPayU_Util::convertArrayToHtmlForm($order, '', $formFieldValuesAsArray);
$signature = OpenPayU_Util::generateSignData(
$formFieldValuesAsArray,
OpenPayU_Configuration::getHashAlgorithm(),
OpenPayU_Configuration::getMerchantPosId(),
OpenPayU_Configuration::getSignatureKey()
);
$formParams = array_merge(self::$defaultFormParams, $params);
$htmlOutput = sprintf("<form method=\"POST\" action=\"%s\" id=\"%s\" class=\"%s\">\n", $orderFormUrl, $formParams['formId'], $formParams['formClass']);
$htmlOutput .= $htmlFormFields;
$htmlOutput .= sprintf("<input type=\"hidden\" name=\"OpenPayu-Signature\" value=\"%s\" />", $signature);
$htmlOutput .= sprintf("<button type=\"submit\" formtarget=\"%s\" id=\"%s\" class=\"%s\">%s</button>", $formParams['submitTarget'], $formParams['submitId'], $formParams['submitClass'], $formParams['submitContent']);
$htmlOutput .= "</form>\n";
return $htmlOutput;
}
}

View File

@@ -0,0 +1,96 @@
<?php
/**
* OpenPayU Standard Library
*
* @copyright Copyright (c) PayU
* http://www.payu.com
* http://developers.payu.com
*/
class OpenPayU_Refund extends OpenPayU
{
/**
* Function make refund for order
* @param $orderId
* @param $description
* @param null|int $amount Amount of refund in pennies
* @param null|string $extCustomerId Marketplace external customer ID
* @param null|string $extRefundId Marketplace external refund ID
* @return null|OpenPayU_Result
* @throws OpenPayU_Exception
*/
public static function create($orderId, $description, $amount = null, $extCustomerId = null, $extRefundId = null)
{
if (empty($orderId)) {
throw new OpenPayU_Exception('Invalid orderId value for refund');
}
if (empty($description)) {
throw new OpenPayU_Exception('Invalid description of refund');
}
$refund = array(
'orderId' => $orderId,
'refund' => array('description' => $description)
);
if (!empty($amount)) {
$refund['refund']['amount'] = $amount;
}
if (!empty($extCustomerId)) {
$refund['refund']['extCustomerId'] = $extCustomerId;
}
if (!empty($extRefundId)) {
$refund['refund']['extRefundId'] = $extRefundId;
}
try {
$authType = self::getAuth();
} catch (OpenPayU_Exception $e) {
throw new OpenPayU_Exception($e->getMessage(), $e->getCode());
}
$pathUrl = OpenPayU_Configuration::getServiceUrl().'orders/'. $refund['orderId'] . '/refund';
$data = OpenPayU_Util::buildJsonFromArray($refund);
$result = self::verifyResponse(OpenPayU_Http::doPost($pathUrl, $data, $authType), 'RefundCreateResponse');
return $result;
}
/**
* @param string $response
* @param string $messageName
* @return OpenPayU_Result
*/
public static function verifyResponse($response, $messageName='')
{
$data = array();
$httpStatus = $response['code'];
$message = OpenPayU_Util::convertJsonToArray($response['response'], true);
$data['status'] = isset($message['status']['statusCode']) ? $message['status']['statusCode'] : null;
if (json_last_error() == JSON_ERROR_SYNTAX) {
$data['response'] = $response['response'];
} elseif (isset($message[$messageName])) {
unset($message[$messageName]['Status']);
$data['response'] = $message[$messageName];
} elseif (isset($message)) {
$data['response'] = $message;
unset($message['status']);
}
$result = self::build($data);
if ($httpStatus == 200 || $httpStatus == 201 || $httpStatus == 422 || $httpStatus == 302) {
return $result;
} else {
OpenPayU_Http::throwHttpStatusException($httpStatus, $result);
}
}
}

View File

@@ -0,0 +1,74 @@
<?php
/**
* OpenPayU Standard Library
*
* @copyright Copyright (c) PayU
* http://www.payu.com
* http://developers.payu.com
*/
class OpenPayU_Retrieve extends OpenPayU
{
const PAYMETHODS_SERVICE = 'paymethods';
/**
* Get Pay Methods from POS
* @param string $lang
* @return null|OpenPayU_Result
* @throws OpenPayU_Exception
* @throws OpenPayU_Exception_Configuration
*/
public static function payMethods($lang = null)
{
try {
$authType = self::getAuth();
} catch (OpenPayU_Exception $e) {
throw new OpenPayU_Exception($e->getMessage(), $e->getCode());
}
if (!$authType instanceof AuthType_Oauth) {
throw new OpenPayU_Exception_Configuration('Retrieve works only with OAuth');
}
$pathUrl = OpenPayU_Configuration::getServiceUrl() . self::PAYMETHODS_SERVICE;
if ($lang !== null) {
$pathUrl .= '?lang=' . $lang;
}
$response = self::verifyResponse(OpenPayU_Http::doGet($pathUrl, $authType));
return $response;
}
/**
* @param string $response
* @return null|OpenPayU_Result
*/
public static function verifyResponse($response)
{
$data = array();
$httpStatus = $response['code'];
$message = OpenPayU_Util::convertJsonToArray($response['response'], true);
$data['status'] = isset($message['status']['statusCode']) ? $message['status']['statusCode'] : null;
if (json_last_error() == JSON_ERROR_SYNTAX) {
$data['response'] = $response['response'];
} elseif (isset($message)) {
$data['response'] = $message;
unset($message['status']);
}
$result = self::build($data);
if ($httpStatus == 200 || $httpStatus == 201 || $httpStatus == 422 || $httpStatus == 302 || $httpStatus == 400 || $httpStatus == 404) {
return $result;
} else {
OpenPayU_Http::throwHttpStatusException($httpStatus, $result);
}
}
}

View File

@@ -0,0 +1,78 @@
<?php
/**
* OpenPayU Standard Library
*
* @copyright Copyright (c) PayU
* http://www.payu.com
* http://developers.payu.com
*/
class OpenPayU_Shop extends OpenPayU
{
const SHOPS_SERVICE = 'shops';
/**
* Retrieving shop data
* @param string $publicShopId
* @return PayuShop
* @throws OpenPayU_Exception
* @throws OpenPayU_Exception_Configuration
*/
public static function get($publicShopId)
{
try {
$authType = self::getAuth();
} catch (OpenPayU_Exception $e) {
throw new OpenPayU_Exception($e->getMessage(), $e->getCode());
}
if (!$authType instanceof AuthType_Oauth) {
throw new OpenPayU_Exception_Configuration('Get shop works only with OAuth');
}
$pathUrl = OpenPayU_Configuration::getServiceUrl() . self::SHOPS_SERVICE . '/' . $publicShopId;
return self::verifyResponse(OpenPayU_Http::doGet($pathUrl, $authType));
}
/**
* @param array $response
* @return PayuShop
* @throws OpenPayU_Exception
*/
public static function verifyResponse($response)
{
$httpStatus = $response['code'];
if ($httpStatus == 500) {
$result = (new ResultError())
->setErrorDescription($response['response']);
OpenPayU_Http::throwErrorHttpStatusException($httpStatus, $result);
}
$message = json_decode($response['response'], true);
if (json_last_error() === JSON_ERROR_SYNTAX) {
throw new OpenPayU_Exception_ServerError('Incorrect json response. Response: [' . $response['response'] . ']');
}
if ($httpStatus == 200) {
return (new PayuShop())
->setShopId($message['shopId'])
->setName($message['name'])
->setCurrencyCode($message['currencyCode'])
->setBalance(
(new PayuShopBalance())
->setCurrencyCode($message['balance']['currencyCode'])
->setTotal($message['balance']['total'])
->setAvailable($message['balance']['available'])
);
}
$result = (new ResultError())
->setError($message['error'])
->setErrorDescription($message['error_description']);
OpenPayU_Http::throwErrorHttpStatusException($httpStatus, $result);
}
}

View File

@@ -0,0 +1,74 @@
<?php
/**
* OpenPayU Standard Library
*
* @copyright Copyright (c)
* http://www.payu.com
* http://developers.payu.com
*/
class OpenPayU_Token extends OpenPayU
{
const TOKENS_SERVICE = 'tokens';
/**
* Deleting a payment token
* @param string $token
* @return null|OpenPayU_Result
* @throws OpenPayU_Exception
* @throws OpenPayU_Exception_Configuration
*/
public static function delete($token)
{
try {
$authType = self::getAuth();
} catch (OpenPayU_Exception $e) {
throw new OpenPayU_Exception($e->getMessage(), $e->getCode());
}
if (!$authType instanceof AuthType_Oauth) {
throw new OpenPayU_Exception_Configuration('Delete token works only with OAuth');
}
if (OpenPayU_Configuration::getOauthGrantType() !== OauthGrantType::TRUSTED_MERCHANT) {
throw new OpenPayU_Exception_Configuration('Token delete request is available only for trusted_merchant');
}
$pathUrl = OpenPayU_Configuration::getServiceUrl() . self::TOKENS_SERVICE . '/' . $token;
$response = self::verifyResponse(OpenPayU_Http::doDelete($pathUrl, $authType));
return $response;
}
/**
* @param string $response
* @return null|OpenPayU_Result
*/
public static function verifyResponse($response)
{
$data = array();
$httpStatus = $response['code'];
$message = OpenPayU_Util::convertJsonToArray($response['response'], true);
$data['status'] = isset($message['status']['statusCode']) ? $message['status']['statusCode'] : null;
if (json_last_error() == JSON_ERROR_SYNTAX) {
$data['response'] = $response['response'];
} elseif (isset($message)) {
$data['response'] = $message;
unset($message['status']);
}
$result = self::build($data);
if ($httpStatus == 204) {
return $result;
} else {
OpenPayU_Http::throwHttpStatusException($httpStatus, $result);
}
}
}

View File

@@ -0,0 +1,44 @@
<?php
/**
* OpenPayU Standard Library
* ver. 2.1.3
*
* @copyright Copyright (c) PayU
* http://www.payu.com
* http://developers.payu.com
*/
include_once('OpenPayU/Configuration.php');
include_once('OpenPayU/OpenPayUException.php');
include_once('OpenPayU/Util.php');
include_once('OpenPayU/OpenPayU.php');
include_once('OpenPayU/OpenPayuOrderStatus.php');
include_once('OpenPayU/Result.php');
require_once('OpenPayU/Http.php');
require_once('OpenPayU/HttpCurl.php');
require_once('OpenPayU/Oauth/Oauth.php');
require_once('OpenPayU/Oauth/OauthGrantType.php');
require_once('OpenPayU/Oauth/OauthResultClientCredentials.php');
require_once('OpenPayU/Oauth/Cache/OauthCacheInterface.php');
require_once('OpenPayU/Oauth/Cache/OauthCacheFile.php');
require_once('OpenPayU/Oauth/Cache/OauthCacheMemcached.php');
require_once('OpenPayU/ResultError.php');
require_once('OpenPayU/AuthType/AuthType.php');
require_once('OpenPayU/AuthType/Basic.php');
require_once('OpenPayU/AuthType/TokenRequest.php');
require_once('OpenPayU/AuthType/Oauth.php');
include_once('OpenPayU/v2/Refund.php');
include_once('OpenPayU/v2/Order.php');
include_once('OpenPayU/v2/Retrieve.php');
include_once('OpenPayU/v2/Token.php');
include_once('OpenPayU/v2/Shop.php');
include_once('OpenPayU/Model/PayuShop.php');
include_once('OpenPayU/Model/PayuShop/PayuShopBalance.php');