Plugin Directory

Changeset 3266993


Ignore:
Timestamp:
04/04/2025 03:16:57 PM (9 months ago)
Author:
best2pay
Message:

version 3.2.14

Location:
best2pay-payment-method-visamastercard
Files:
997 added
5 edited

Legend:

Unmodified
Added
Removed
  • best2pay-payment-method-visamastercard/trunk/best2pay-payment.php

    r3213969 r3266993  
    11<?php
    2 declare(strict_types = 1);
    3 
    42/*
    53 * Plugin Name: Best2Pay payment module
    64 * Plugin URI: https://best2pay.net/
    75 * Description: Receive payments via Visa / Mastercard / MIR easily with Best2Pay bank cards processing
    8  * Version: 3.0.1
    9  * Author: Best2Pay
     6 * Version: 3.2.14
     7 * Author: Best2pay
    108 * Tested up to: 6.6.1
    11  * License: GPLv3
     9 * License: GPL3
    1210 *
    1311 * Text Domain: best2pay-payment
     
    1513 */
    1614
    17 if(!class_exists('B2P\Client'))
    18     require_once __DIR__ . '/sdk/sdk_autoload.php';
     15// Exit if accessed directly.
     16if ( ! defined( 'ABSPATH' ) ) {
     17    exit;
     18}
    1919
    20 use B2P\Client;
    21 use B2P\Responses\Error;
    22 use B2P\Models\Enums\CurrencyCode;
    23 use B2P\Models\Interfaces\CreditOrder;
    24 
    25 defined('ABSPATH') or die("No script kiddies please!");
    26 
    27 add_action('plugins_loaded', 'init_woocommerce_best2pay', 0);
    28 
    29 function init_woocommerce_best2pay() {
    30     if(!class_exists('WC_Payment_Gateway')) return;
    31 
    32     load_plugin_textdomain('best2pay-payment', false, dirname(plugin_basename(__FILE__)) . '/languages');
    33 
    34     class woocommerce_best2pay extends WC_Payment_Gateway {
    35         const PLUGIN_URL = 'https://best2pay.net';
    36 
    37         protected string $api_operation;
    38         protected array $query_params = [];
    39         protected string $notify_url;
    40         protected string $sector;
    41         protected string $password;
    42         protected string $testmode;
    43         protected string $hash_algo;
    44         protected bool $notify_customer_enabled;
    45         protected string $registered_status;
    46         protected string $authorized_status;
    47         protected string $loan_status;
    48         protected string $completed_status;
    49         protected string $agreement_status;
    50         protected string $payment_expected_status;
    51         protected string $canceled_status;
    52         protected string $payment_method;
    53         protected string $tax;
    54         protected int $currency;
    55         protected array $fiscal_positions;
    56         protected array $shop_cart;
    57         protected string $logo_field;
    58         protected string $remove_logo_field;
    59 
    60         public function __construct() {
    61             require_once ABSPATH . 'wp-admin/includes/file.php';
    62 
    63             $this->id = 'best2pay';
    64             $this->method_title = __('Best2Pay', 'best2pay-payment');
    65             $this->method_description = sprintf(__('To accept payments through the plugin, you need to apply to connect to Best2pay on the website <a href="%1$s" target="_blank">%1$s</a> and enter into an agreement with the company.<br/>Support email: <a href="mailto:%2$s">%2$s</a>', 'best2pay-payment'), self::PLUGIN_URL, '[email protected]');
    66             $this->icon = plugins_url('assets/img/best2pay.png', __FILE__);
    67             $this->has_fields = true;
    68             $this->notify_url = add_query_arg('wc-api', 'best2pay_notify', home_url('/'));
    69             $this->supports = ['refunds', 'products'];
    70 
    71             $this->init_form_fields();
    72             $this->init_settings();
    73 
    74             $this->title = $this->settings['title'] ? $this->settings['title'] : $this->method_title;
    75             $this->description = $this->settings['description'] ? $this->settings['description'] : sprintf(__('Payments with bank cards via the <a href="%s" target="_blank">Best2Pay</a> payment system.', 'best2pay-payment'), self::PLUGIN_URL);
    76             $this->logo = $this->settings['logo'] ?? '';
    77             $this->sector = $this->settings['sector'];
    78             $this->password = $this->settings['password'];
    79             $this->testmode = $this->settings['testmode'];
    80             $this->hash_algo = ($this->settings['hash_algo'] === 'sha256') ? '1' : '0';
    81             $this->payment_method = $this->settings['payment_method'] ?? '';
    82             $this->tax = $this->settings['tax'] ?? '6';
    83             $this->notify_customer_enabled = $this->settings['notify_customer_enabled'] === 'yes';
    84             $this->currency = $this->get_currency(get_woocommerce_currency());
    85             $this->logo_field = $this->plugin_id . $this->id . '_logo';
    86             $this->remove_logo_field = $this->plugin_id . $this->id . '_remove_logo';
    87             $this->registered_status = $this->settings['registered_status'] ?? '';
    88             $this->authorized_status = $this->settings['authorized_status'] ?? '';
    89             $this->loan_status = $this->settings['loan_status'] ?? '';
    90             $this->completed_status = $this->settings['completed_status'] ?? '';
    91             $this->canceled_status = $this->settings['canceled_status'] ?? '';
    92             $this->agreement_status = $this->settings['agreement_status'] ?? '';
    93             $this->payment_expected_status = $this->settings['payment_expected_status'] ?? '';
    94 
    95             switch($this->payment_method) {
    96                 case 'purchaseWithInstallment':
    97                 case 'authorizeWithInstallment':
    98                     $this->title = __('Pay for your order in installments', 'best2pay-payment');
    99                     $this->icon = plugins_url('assets/img/svkb.svg', __FILE__);
    100                     break;
    101                 default:
    102                     if($this->logo)
    103                         $this->icon = wp_get_attachment_url($this->logo);
    104                     break;
     20class WC_Best2pay_Payments {
     21   
     22    /**
     23     * Plugin bootstrapping.
     24     */
     25    public static function init() {
     26       
     27        // Best2pay Payment gateway class.
     28        add_action( 'plugins_loaded', array( __CLASS__, 'includes' ), 0 );
     29       
     30        // Make the Best2pay Payment gateway available to WC.
     31        add_filter( 'woocommerce_payment_gateways', array( __CLASS__, 'add_gateway' ) );
     32       
     33        // Registers WooCommerce Blocks integration.
     34        add_action( 'woocommerce_blocks_loaded', array( __CLASS__, 'woocommerce_gateway_best2pay_woocommerce_block_support' ) );
     35       
     36        // Loading languages
     37        load_plugin_textdomain('best2pay-payment', false, dirname(plugin_basename(__FILE__)) . '/languages');
     38       
     39        add_filter('plugin_action_links_' . plugin_basename(__FILE__),
     40            function ($links) {
     41                if(!class_exists('woocommerce')){
     42                    return $links;
     43                }
     44               
     45                array_unshift($links, sprintf('<a href="%1$s">%2$s</a>', admin_url('admin.php?page=wc-settings&tab=checkout&section=best2pay'), __('Settings', 'best2pay-payment')));
     46               
     47                return $links;
    10548            }
    106 
    107             $this->getClient();
    108 
    109             add_action('woocommerce_api_best2pay_notify', [$this, 'callback_notify']);
    110             add_action('woocommerce_api_best2pay_complete_action', [$this, 'process_complete']);
    111             add_action("woocommerce_api_best2pay_skvb_widget", [$this, 'skvb_widget']);
    112             add_action('woocommerce_update_options_payment_gateways_' . $this->id, [$this, 'process_admin_options']);
    113             add_action('woocommerce_order_item_add_action_buttons', [$this, 'wc_order_item_add_complete_button']);
    114             add_filter('woocommerce_generate_image_html', 'woocommerce_generate_image_html');
    115             add_action("woocommerce_order_status_changed", [$this, 'wc_best2pay_order_payment_change'], 10, 4);
    116         }
    117 
    118         public function init_form_fields() {
    119             $wc_statuses = wc_get_order_statuses();
    120 
    121             $this->form_fields = [
    122                 'enabled' => [
    123                     'title' => __('Enable/Disable', 'best2pay-payment'),
    124                     'type' => 'checkbox',
    125                     'label' => __('Enable Best2Pay checkout method', 'best2pay-payment'),
    126                     'default' => 'yes'
    127                 ],
    128                 'title' => [
    129                     'title' => __('Title', 'best2pay-payment'),
    130                     'type' => 'text',
    131                     'description' => __('Custom title for payment type', 'best2pay-payment'),
    132                     'desc_tip' => true,
    133                     'placeholder' => $this->method_title,
    134                     'default' => ''
    135                 ],
    136                 'description' => [
    137                     'title' => __('Description', 'best2pay-payment'),
    138                     'type' => 'textarea',
    139                     'description' => __('Custom description for payment type', 'best2pay-payment'),
    140                     'desc_tip' => true,
    141                     'css' => 'width: 400px;',
    142                     'default' => ''
    143                 ],
    144                 'logo' => [
    145                     'title' => __('Logo', 'best2pay-payment'),
    146                     'type' => 'image',
    147                     'description' => __('Custom logo for payment type', 'best2pay-payment'),
    148                     'desc_tip' => true,
    149                     'default' => ''
    150                 ],
    151                 'sector' => [
    152                     'title' => __('Sector ID', 'best2pay-payment'),
    153                     'type' => 'text',
    154                     'description' => __('Your shop identifier at Best2Pay', 'best2pay-payment'),
    155                     'desc_tip' => true,
    156                     'placeholder' => '1234',
    157                     'default' => ''
    158                 ],
    159                 'password' => [
    160                     'title' => __('Password', 'best2pay-payment'),
    161                     'type' => 'text',
    162                     'description' => __('Password to use for digital signature', 'best2pay-payment'),
    163                     'desc_tip' => true,
    164                     'placeholder' => 'test',
    165                     'default' => ''
    166                 ],
    167                 'testmode' => [
    168                     'title' => __('Test Mode', 'best2pay-payment'),
    169                     'type' => 'select',
    170                     'options' => [
    171                         '1' => __('Test mode - real payments will not be processed', 'best2pay-payment'),
    172                         '0' => __('Production mode - payments will be processed', 'best2pay-payment')
    173                     ],
    174                     'description' => __('Select test or live mode', 'best2pay-payment'),
    175                     'desc_tip' => true,
    176                     'default' => '1'
    177                 ],
    178                 'payment_method' => [
    179                     'title' => __('Payment method', 'best2pay-payment'),
    180                     'type' => 'select',
    181                     'options' => [
    182                         'purchase' => __('Standard acquiring (one-stage payment)', 'best2pay-payment'),
    183                         'authorize' => __('Standard acquiring (two-stage payment)', 'best2pay-payment') . ' *',
    184                         'purchaseWithInstallment' => __('Plait (one-stage payment)', 'best2pay-payment'),
    185                         'authorizeWithInstallment' => __('Plait (two-stage payment)', 'best2pay-payment') . ' *',
    186                         'purchaseSBP' => __('Fast Payment System', 'best2pay-payment'),
    187                         'loan' => __('Loan', 'best2pay-payment')
    188                     ],
    189                     'description' => '* ' . __('Payment occurs after confirmation by the manager in the personal account', 'best2pay-payment'),
    190                     'desc_tip' => true,
    191                     'default' => 'purchase'
    192                 ],
    193                 'tax' => [
    194                     'title' => __('TAX', 'best2pay-payment'),
    195                     'type' => 'select',
    196                     'options' => [
    197                         1 => __('VAT rate 20%', 'best2pay-payment'),
    198                         2 => __('VAT rate 10%', 'best2pay-payment'),
    199                         3 => __('VAT rate calc. 20/120', 'best2pay-payment'),
    200                         4 => __('VAT rate calc. 10/110', 'best2pay-payment'),
    201                         5 => __('VAT rate 0%', 'best2pay-payment'),
    202                         7 => __('VAT rate 5%', 'best2pay-payment'),
    203                         8 => __('VAT rate 7%', 'best2pay-payment'),
    204                         9 => __('VAT rate calc. 5/105', 'best2pay-payment'),
    205                         10 => __('VAT rate calc. 7/107', 'best2pay-payment'),
    206                         6 => __('Not subject to VAT', 'best2pay-payment'),
    207                     ],
    208                     'default' => '6'
    209                 ],
    210                 'notify_url' => [
    211                     'title' => __('Notify URL', 'best2pay-payment'),
    212                     'type' => 'text',
    213                     'description' => __('Report this URL to Best2Pay technical support to receive payment notifications', 'best2pay-payment'),
    214                     'desc_tip' => true,
    215                     'custom_attributes' => [
    216                         'readonly' => 'readonly',
    217                     ],
    218                     'default' => $this->notify_url
    219                 ],
    220                 'hash_algo' => [
    221                     'title' => __('Data encryption algorithm', 'best2pay-payment'),
    222                     'type' => 'select',
    223                     'options' => [
    224                         'md5' => 'MD5',
    225                         'sha256' => 'SHA256',
    226                     ],
    227                     'description' => __('Must match your sector encryption settings in your personal account', 'best2pay-payment'),
    228                     'desc_tip' => true,
    229                     'default' => 'md5'
    230                 ],
    231                 'custom_statuses_header' => [
    232                     'title' => __('Custom statuses for orders', 'best2pay-payment'),
    233                     'type' => 'title'
    234                 ],
    235                 'registered_status' => [
    236                     'title' => __('Order registered', 'best2pay-payment'),
    237                     'type' => 'select',
    238                     'options' => $wc_statuses,
    239                     'default' => 'wc-pending'
    240                 ],
    241                 'authorized_status' => [
    242                     'title' => __('Order authorized', 'best2pay-payment'),
    243                     'type' => 'select',
    244                     'options' => $wc_statuses,
    245                     'default' => 'wc-on-hold'
    246                 ],
    247                 'loan_status' => [
    248                     'title' => __('Loan agreement approved but not signed', 'best2pay-payment'),
    249                     'type' => 'select',
    250                     'options' => $wc_statuses,
    251                     'default' => 'wc-processing'
    252                 ],
    253                 'completed_status' => [
    254                     'title' => __('Order successfully paid', 'best2pay-payment'),
    255                     'type' => 'select',
    256                     'options' => $wc_statuses,
    257                     'default' => 'wc-completed'
    258                 ],
    259                 'canceled_status' => [
    260                     'title' => __('Order canceled', 'best2pay-payment'),
    261                     'type' => 'select',
    262                     'options' => $wc_statuses,
    263                     'default' => 'wc-refunded'
    264                 ],
    265                 'notify_customer_enabled' => [
    266                     'title' => __('Issuing an invoice for payment', 'best2pay-payment'),
    267                     'type' => 'checkbox',
    268                     'label' => __('Enable issuing an invoice for payment by email of the payer', 'best2pay-payment'),
    269                     'default' => 'no'
    270                 ],
    271                 'agreement_status' => [
    272                     'title' => __('Order agreement', 'best2pay-payment'),
    273                     'type' => 'select',
    274                     'options' => $wc_statuses,
    275                     'default' => 'wc-on-hold'
    276                 ],
    277                 'payment_expected_status' => [
    278                     'title' => __('Payment expected', 'best2pay-payment'),
    279                     'type' => 'select',
    280                     'options' => $wc_statuses,
    281                     'default' => 'wc-pending'
    282                 ]
    283             ];
    284 
    285             wp_enqueue_script('admin-best2pay-script', plugins_url('assets/js/admin.js', __FILE__));
    286         }
    287 
    288         protected function getClient() {
    289             try {
    290                 if (isset($this->sector) && isset($this->password))
    291                     $this->client = new Client((int)$this->sector, $this->password, (bool)$this->testmode, (bool)$this->hash_algo);
    292             } catch (Exception $e) {
    293                 return new WP_Error('error', $e->getMessage());
    294             }
    295 
    296             return $this->client;
    297         }
    298 
    299         public function payment_fields() {
    300             if($this->payment_method === 'purchaseWithInstallment' || $this->payment_method === 'authorizeWithInstallment')
    301                 echo '<iframe style="width:100%;height:160px;border:none;min-width: 440px;" src="/?wc-api=best2pay_skvb_widget&amount=' . print_r((isset(WC()->cart->cart_contents_total)) ? WC()->cart->cart_contents_total : '', true) . '"></iframe>';
    302         }
    303 
    304         public function admin_options() {?>
    305             <h3><?php echo esc_html(__('Best2Pay', 'best2pay-payment'));?></h3>
    306             <p><?php echo sprintf(__('Payments with bank cards via the <a href="%s" target="_blank">Best2Pay</a> payment system.', 'best2pay-payment'), self::PLUGIN_URL);?></p>
    307             <table class="form-table">
    308                 <?php $this->generate_settings_html();?>
    309             </table>
    310         <?php }
    311 
    312         public function process_admin_options() {
    313             if(!empty($_POST[$this->remove_logo_field]) && !empty($this->logo)){
    314                 if(wp_delete_attachment($this->logo))
    315                     $this->update_option('logo');
    316             } else if (!empty($_FILES[$this->logo_field]['name'])) {
    317                 require_once(ABSPATH.'wp-admin/includes/image.php');
    318                 require_once(ABSPATH.'wp-admin/includes/file.php');
    319                 require_once(ABSPATH.'wp-admin/includes/media.php');
    320 
    321                 if(!file_is_valid_image($_FILES[$this->logo_field]['tmp_name']))
    322                     return false;
    323 
    324                 $attachment_id = media_handle_upload($this->logo_field, 0);
    325                 if (is_wp_error($attachment_id))
    326                     return $attachment_id->get_error_message();
    327 
    328                 if(!empty($this->logo))
    329                     wp_delete_attachment($this->logo);
    330 
    331                 $this->update_option('logo', $attachment_id);
    332             }
    333 
    334             $this->init_settings();
    335 
    336             $post_data = $this->get_post_data();
    337 
    338             foreach ($this->get_form_fields() as $key => $field) {
    339                 if(in_array($this->get_field_type($field), ['title', 'image'])) continue;
    340 
    341                 try {
    342                     $this->settings[$key] = $this->get_field_value($key, $field, $post_data);
    343                 } catch (Exception $e) {
    344                     $this->add_error($e->getMessage());
    345                 }
    346             }
    347 
    348             return update_option($this->get_option_key(), apply_filters('woocommerce_settings_api_sanitized_fields_' . $this->id, $this->settings));
    349         }
    350 
    351         public function generate_image_html($key, $data) {
    352             $field_key = $this->get_field_key($key);
    353             $defaults = [
    354                 'title' => '',
    355                 'disabled' => false,
    356                 'class' => '',
    357                 'css' => '',
    358                 'placeholder' => '',
    359                 'type' => 'file',
    360                 'desc_tip' => false,
    361                 'description' => '',
    362                 'custom_attributes' => [],
    363             ];
    364 
    365             $data = wp_parse_args($data, $defaults);
    366 
    367             ob_start();?>
    368             <tr valign="top">
    369                 <th scope="row" class="titledesc">
    370                     <label for="<?php echo esc_attr($field_key);?>"><?php echo wp_kses_post($data['title']);?> <?php echo $this->get_tooltip_html($data);?></label>
    371                 </th>
    372                 <td class="forminp">
    373                     <fieldset>
    374                         <legend class="screen-reader-text"><span><?php echo wp_kses_post($data['title']);?></span></legend>
    375                         <input class="input-text regular-input" type="file" name="<?php echo esc_attr($field_key);?>" id="<?php echo esc_attr($field_key);?>" accept="image/*">
    376                     </fieldset>
    377                     <?php if(!empty($this->logo)){
    378                         $logo_meta = wp_get_attachment_metadata($this->logo);?>
    379                         <img src="<?php echo wp_get_attachment_url($this->logo)?>" alt="" width="100" style="margin: 10px">
    380                         <div>(<?php echo esc_html($logo_meta['width'] . 'x' . $logo_meta['height']);?>)</div>
    381                         <br>
    382                         <label for="<?php echo esc_attr($this->remove_logo_field);?>">
    383                             <input class="" type="checkbox" name="<?php echo esc_attr($this->remove_logo_field);?>" id="<?php echo esc_attr($this->remove_logo_field);?>" style="" value="1"> <?php echo wp_kses_post( __('Remove logo', 'best2pay-payment'));?>
    384                         </label>
    385                     <?php } else { ?>
    386                         <img src="<?php echo plugins_url('assets/img/best2pay.png', plugin_basename(__FILE__));?>" alt="" width="100" style="margin: 10px">
    387                     <?php } ?>
    388                 </td>
    389             </tr>
    390             <?php return ob_get_clean();
    391         }
    392 
    393         function wc_order_item_add_complete_button($order) {
    394             if($order->get_payment_method() === $this->id && $order->get_meta('best2pay_order_state', true) === 'AUTHORIZED') {
    395                 wp_register_script('scripts-js', plugins_url('assets/js/scripts.js', plugin_basename(__FILE__)) , '', '', true);
    396                 wp_enqueue_script('scripts-js');
    397             ?>
    398                 <input type="hidden" id="nonce_best2pay_complete" value="<?php echo wp_create_nonce('best2pay_complete_action' . $order->get_id());?>">
    399                 <button type="button" id="button_best2pay_complete" class="button custom-items"><?php _e('Complete payment', 'best2pay-payment');?></button>
    400             <?php }
    401         }
    402 
    403         public function process_payment($order_id) {
    404             $wc_order = wc_get_order($order_id);
    405 
    406             if($this->notify_customer_enabled && $wc_order->get_status() !== $this->agreement_status && !get_post_meta($order_id, 'best2pay_order_moderated', true)) {
    407                 $wc_order->add_order_note(__('Order created successfully', 'best2pay-payment'));
    408                 $wc_order->update_status($this->agreement_status);
    409 
    410                 update_post_meta($wc_order->get_id(), 'best2pay_order_moderated', 'yes');
    411 
    412                 WC()->cart->empty_cart();
    413 
    414                 return [
    415                     'result' => 'success',
    416                     'redirect' => $this->get_return_url($wc_order),
    417                 ];
    418             }
    419 
    420             $register_order_id = get_post_meta($order_id, 'best2pay_order_id', true);
    421 
    422             if($register_order_id) {
    423                 $payment_url = $this->process_payment_payform((int)$register_order_id, $order_id);
    424             } else {
    425                 $pay_order_id = $this->process_payment_registration($wc_order);
    426                 $payment_url = $this->process_payment_payform($pay_order_id, $order_id);
    427             }
    428 
    429             return [
    430                 'result' => 'success',
    431                 'redirect' => $payment_url
    432             ];
    433         }
    434 
    435         public function wc_best2pay_order_payment_change($order_id, $status_from, $status_to, $order) {
    436             if($this->notify_customer_enabled && $order->payment_method === 'best2pay' && ($status_from === 'on-hold' && $status_to === 'pending'))
    437                 $this->process_payment_registration($order);
    438         }
    439 
    440         public function process_payment_registration($order): int {
    441             $this->calc_fiscal_position_shop_cart($order, $this->client->centifyAmount($order->get_total()));
    442 
    443             $register_data = [
    444                 'reference' => $order->get_id(),
    445                 'amount' => $this->client->centifyAmount($order->get_total()),
    446                 'currency' => $this->currency,
    447                 'email' => $order->get_billing_email(),
    448                 'description' => sprintf(__('Order #%s', 'best2pay-payment'), ltrim($order->get_order_number(), '#')),
    449                 'url' => $this->notify_url,
    450                 'mode' => 0,
    451                 'fiscal_positions' => $this->fiscal_positions
    452             ];
    453 
    454             if ($this->notify_customer_enabled)
    455                 $register_data['notify_customer'] = 1;
    456 
    457             try {
    458                 $response = $this->client->register($register_data);
    459                 if($response instanceof Error)
    460                     throw new Exception($response->description->getValue());
    461 
    462                 $b2p_order_id = (int)$response->id;
    463                 if (!$b2p_order_id)
    464                     throw new Exception(__('Failed to get Best2pay order ID', 'best2pay-payment'));
    465             } catch (Exception $e) {
    466                 wc_add_notice($e->getMessage(), 'error');
    467             }
    468 
    469             $order->update_status($this->{strtolower($response->getState()) . '_status'});
    470             update_post_meta($order->get_id(), 'best2pay_order_id', $b2p_order_id);
    471             update_post_meta($order->get_id(), 'best2pay_order_state', $response->getState());
    472             $order->add_order_note(__('Order registered successfully', 'best2pay-payment') . " (ID: $b2p_order_id)");
    473 
    474             return $b2p_order_id;
    475         }
    476 
    477         public function process_payment_payform($pay_order_id, $reference): string {
    478             $operation_params = ['id' => $pay_order_id];
    479             if (str_contains($this->payment_method, 'WithInstallment') && $this->shop_cart)
    480                 $operation_params['shop_cart'] = base64_encode(wp_json_encode($this->shop_cart));
    481             if (str_contains($this->payment_method, 'loan'))
    482                 $operation_params['reference'] = $reference;
    483 
    484             $url = call_user_func([$this->client, $this->payment_method], $operation_params);
    485 
    486             $parsed_url = parse_url($url);
    487             $this->api_operation = $parsed_url['path'];
    488             parse_str($parsed_url['query'], $this->query_params);
    489 
    490             return $url;
    491         }
    492 
    493         public function callback_notify() {
    494             $wc_order = [];
    495             $checkout_url = apply_filters('woocommerce_get_checkout_url', wc_get_checkout_url());
    496 
    497             try {
    498                 if ($isNotifyRequest = $this->isNotifyRequest()) {
    499                     $input = file_get_contents("php://input");
    500                     $ct_order_id = $this->client->handleResponse($input)->order_id->getValue();
    501                 } else {
    502                     if(isset($_REQUEST['error'])) {
    503                         $message = __('Failed to pay for the order', 'best2pay-payment') . ":\n" . sanitize_text_field($_REQUEST['error']);
    504 
    505                         wc_add_notice(nl2br($message), 'error');
    506                         wp_redirect($checkout_url);
    507                     }
    508 
    509                     $ct_order_id = (int) sanitize_text_field($_REQUEST['id']);
    510                     if(!$ct_order_id)
    511                         throw new Exception(__('Failed to get Best2pay order ID', 'best2pay-payment'));
    512 
    513                     $pc_ref_id = (int) sanitize_text_field($_REQUEST['reference']);
    514                     if(!$pc_ref_id)
    515                         throw new Exception(__('Undefined order ID', 'best2pay-payment'));
    516 
    517                     $pc_order_id = (int)get_post_meta($pc_ref_id, 'best2pay_order_id', true);
    518                     if($ct_order_id !== $pc_order_id)
    519                         throw new Exception(__('Request data is not valid', 'best2pay-payment'));
    520                 }
    521 
    522                 $ct_order = $this->client->order(['id' => $ct_order_id]);
    523                 if($ct_order instanceof Error)
    524                     throw new Exception($ct_order->description->getValue());
    525 
    526                 $wc_order = wc_get_order((int)$ct_order->reference);
    527                 if(!$wc_order)
    528                     throw new Exception(__('Failed to get order information', 'best2pay-payment'));
    529 
    530                 $wc_order->update_meta_data('best2pay_order_state', $ct_order->getState());
    531 
    532                 $paid = false;
    533 
    534                 if($ct_order->getState() !== get_post_meta($wc_order->get_id(), 'best2pay_order_state', true)) {
    535                     if($ct_order instanceof CreditOrder) {
    536                         $wc_order->update_status($ct_order->isPaid() ? $this->completed_status : $this->loan_status);
    537                         $wc_order->add_order_note($ct_order->isPaid() ? __('The loan agreement was successfully completed and signed', 'best2pay-payment') : __('The loan agreement was successfully completed, but not signed', 'best2pay-payment'));
    538 
    539                         $paid = true;
    540                     } else {
    541                         $wc_order->update_status($this->{strtolower($ct_order->getState()) . '_status'});
    542                         /* translators: %s: PC order state */
    543                         $wc_order->add_order_note(__('Payment successful', 'best2pay-payment') . ' ('.strtolower($ct_order->getState()).')');
    544                         $paid = $ct_order->isPaid();
    545                     }
    546 
    547                     $wc_order->save();
    548                 }
    549 
    550                 if ($isNotifyRequest) {
    551                     echo 'ok';
    552                 } else {
    553                     if($paid) {
    554                         WC()->cart->empty_cart();
    555                         wp_redirect($this->get_return_url($wc_order));
    556                     } else {
    557                         wc_add_notice(nl2br(__('Failed to pay incorrect card', 'best2pay-payment')), 'error');
    558                         wp_redirect($checkout_url);
    559                     }
    560                 }
    561             } catch (\throwable $e) {
    562                 if ($isNotifyRequest) {
    563                     echo 'ok';
    564                 } else {
    565                     $message = __('Failed to pay for the order', 'best2pay-payment') . ":\n" . $e->getMessage();
    566 
    567                     if($wc_order)
    568                         $wc_order->add_order_note(nl2br($message));
    569 
    570                     wc_add_notice(nl2br($message), 'error');
    571                     wp_redirect($checkout_url);
    572                 }
    573             }
    574 
    575             exit;
     49        );
     50    }
     51   
     52    /**
     53     * Add the Best2pay Payment gateway to the list of available gateways.
     54     *
     55     * @param array
     56     */
     57    public static function add_gateway( $gateways ) {
     58       
     59        $options = get_option( 'woocommerce_best2pay_settings', array() );
     60       
     61        if ( isset( $options['hide_for_non_admin_users'] ) ) {
     62            $hide_for_non_admin_users = $options['hide_for_non_admin_users'];
     63        } else {
     64            $hide_for_non_admin_users = 'no';
    57665        }
    57766       
    578         public function skvb_widget() {
    579             include_once __DIR__ . '/svkb_widget.php';
    580             exit;
     67        if ( ( 'yes' === $hide_for_non_admin_users && current_user_can( 'manage_options' ) ) || 'no' === $hide_for_non_admin_users ) {
     68            $gateways[] = 'WC_Best2pay_Gateway';
    58169        }
    582 
    583         public function process_complete() {
    584             try {
    585                 $order_id = (int) sanitize_text_field($_REQUEST['order_id']);
    586                 if(!$order_id)
    587                     throw new Exception(__('Undefined order ID', 'best2pay-payment'));
    588 
    589                 if (!wp_verify_nonce(sanitize_text_field(wp_unslash($_REQUEST['best2pay_nonce_value'])), 'best2pay_complete_action' . $order_id))
    590                     throw new Exception(__('Operation failed. Please refresh the page', 'best2pay-payment'));
    591 
    592                 $wc_order = wc_get_order($order_id);
    593                 if(!$wc_order)
    594                     throw new Exception(__('Failed to get order information', 'best2pay-payment'));
    595 
    596                 $pc_order_id = get_post_meta($wc_order->get_id(), 'best2pay_order_id', true);
    597                 if(!$pc_order_id)
    598                     throw new Exception(__('Failed to get Best2pay order ID', 'best2pay-payment'));
    599 
    600                 $ct_order = $this->client->order(['id' => $pc_order_id]);
    601                 if($ct_order instanceof Error)
    602                     throw new Exception($ct_order->description->getValue());
    603 
    604                 $complete_result = $ct_order->complete();
    605                 if(!$complete_result)
    606                     throw new Exception(__('Unable to debit funds', 'best2pay-payment'));
    607 
    608                 if($ct_order instanceof CreditOrder) {
    609                     $success_message = __('The loan agreement was successfully completed and signed', 'best2pay-payment');
    610                 } else {
    611                     $wc_order->update_status($this->completed_status);
    612                     $success_message = __('Funds for the order have been successfully debited', 'best2pay-payment');
    613                 }
    614 
    615                 $wc_order->update_meta_data('best2pay_order_state', 'COMPLETED');
    616                 $wc_order->add_order_note($success_message);
    617 
    618                 $wc_order->save();
    619 
    620                 echo wp_json_encode([
    621                     'success' => true,
    622                     'message' => nl2br($success_message)
    623                 ]);
    624             } catch (Exception $e) {
    625                 echo wp_json_encode([
    626                     'success' => false,
    627                     'message' => nl2br($e->getMessage())
    628                 ]);
    629 
    630                 return new WP_Error('error', $e->getMessage());
    631             }
    632 
    633             exit;
    634         }
    635 
    636         public function process_refund($order_id, $amount = null, $reason = '') {
    637             try {
    638                 $wc_order = wc_get_order($order_id);
    639                 if(!$wc_order)
    640                     throw new Exception(__('Failed to get order information', 'best2pay-payment'));
    641 
    642                 if (!$_REQUEST['security'])
    643                     throw new Exception(__('Operation failed. Please refresh the page', 'best2pay-payment'));
    644 
    645                 if($amount !== $wc_order->get_total())
    646                     return new WP_Error('error', __('Error, please enter the refund amount. Refunds must be made for the full amount of the order', 'best2pay-payment'));
    647 
    648                 $pc_order_id = get_post_meta($wc_order->get_id(), 'best2pay_order_id', true);
    649                 if(!$pc_order_id)
    650                     throw new Exception(__('Failed to get Best2pay order ID', 'best2pay-payment'));
    651 
    652                 $ct_order = $this->client->order(['id' => $pc_order_id]);
    653                 if($ct_order instanceof Error)
    654                     throw new Exception($ct_order->description->getValue());
    655 
    656                 $reverse_result = $ct_order->reverse();
    657                 if($reverse_result instanceof Error)
    658                     return new WP_Error('error', __('Unable to issue a refund on a credit order', 'best2pay-payment'));
    659             } catch (Exception $e) {
    660                 echo wp_json_encode([
    661                     'success' => false,
    662                     'message' => nl2br($e->getMessage())
    663                 ]);
    664 
    665                 return new WP_Error('error', $e->getMessage());
    666             }
    667 
    668             $wc_order->update_meta_data('best2pay_order_state', 'CANCELED');
    669             $comment = __('Payment canceled successfully', 'best2pay-payment');
    670 
    671             if($reason){
    672                 $comment .= PHP_EOL . esc_html($reason);
    673             }
    674 
    675             $wc_order->add_order_note($comment);
    676 
    677             $wc_order->save();
    678 
    679             return wp_json_encode([
    680                 'success' => true,
    681                 'message' => nl2br($comment)
    682             ]);
    683         }
    684 
    685         public function isNotifyRequest(): bool {
    686             try {
    687                 $input = file_get_contents("php://input");
    688                 if ($input && $this->client->handleResponse($input)) return true;
    689                 return false;
    690             } catch (\throwable $e) {
    691                 return false;
    692             }
    693         }
    694 
    695         private function calc_fiscal_position_shop_cart($order, $order_amount) {
    696             $fiscal_positions = [];
    697             $fiscal_amount = 0;
    698             $shop_cart = [];
    699 
    700             $basket_items = $order->get_items();
    701             $shipping_amount = $order->get_shipping_total();
    702 
    703             foreach ($basket_items as $b_key => $basket_item) {
    704                 $basket_item_data = $basket_item->get_data();
    705 
    706                 $fiscal_positions[$b_key]['quantity'] = $basket_item_data['quantity'];
    707                 $fiscal_amount += $basket_item_data['quantity'] * ($fiscal_positions[$b_key]['amount'] = $this->client->centifyAmount($basket_item->get_product()->get_price()));
    708                 $fiscal_positions[$b_key]['tax'] = (int)$this->tax;
    709                 $fiscal_positions[$b_key]['name'] = str_ireplace([';', '|'], '', $basket_item_data['name']);
    710 
    711                 $shop_cart[] = [
    712                     'name' => $basket_item_data['name'],
    713                     'goodCost' => (int)$basket_item->get_product()->get_price(),
    714                     'quantityGoods' => $basket_item_data['quantity']
    715                 ];
    716             }
    717 
    718             if ($shipping_amount) {
    719                 $fiscal_positions[] = [
    720                     'quantity' => 1,
    721                     'amount' => $this->client->centifyAmount($shipping_amount),
    722                     'tax' => (int)$this->tax,
    723                     'name' => 'Доставка'
    724                 ];
    725                 $fiscal_amount += $this->client->centifyAmount($shipping_amount);
    726                 $shop_cart[] = [
    727                     'name' => 'Доставка',
    728                     'goodCost' => (int)$shipping_amount,
    729                     'quantityGoods' => 1
    730                 ];
    731             }
    732 
    733             if ($fiscal_diff = abs($fiscal_amount - $order_amount)) {
    734                 $fiscal_positions[] = [1, $fiscal_diff, (int)$this->tax, 'Скидка', 14];
    735                 $shop_cart = [];
    736             }
    737 
    738             $this->fiscal_positions = $fiscal_positions;
    739             $this->shop_cart = $shop_cart;
    740         }
    741 
    742         public function get_currency($wc_currency): int {
    743             if (isset(CurrencyCode::cases()[$wc_currency])) {
    744                 return CurrencyCode::cases()[$wc_currency];
    745             } else throw new Exception('wrong currency');
     70        return $gateways;
     71    }
     72   
     73    /**
     74     * Plugin includes.
     75     */
     76    public static function includes() {
     77       
     78        // Make the WC_Best2pay_Gateway class available.
     79        if ( class_exists( 'WC_Payment_Gateway' ) ) {
     80            require_once 'includes/class-wc-gateway-best2pay.php';
    74681        }
    74782    }
     83   
     84    /**
     85     * Plugin url.
     86     *
     87     * @return string
     88     */
     89    public static function plugin_url() {
     90        return untrailingslashit( plugins_url( '/', __FILE__ ) );
     91    }
     92   
     93    /**
     94     * Plugin url.
     95     *
     96     * @return string
     97     */
     98    public static function plugin_abspath() {
     99        return trailingslashit( plugin_dir_path( __FILE__ ) );
     100    }
     101   
     102    /**
     103     * Registers WooCommerce Blocks integration.
     104     *
     105     */
     106    public static function woocommerce_gateway_best2pay_woocommerce_block_support() {
     107        if ( class_exists( 'Automattic\WooCommerce\Blocks\Payments\Integrations\AbstractPaymentMethodType' ) ) {
     108            require_once 'includes/blocks/class-wc-best2pay-payments-blocks.php';
     109            add_action(
     110                'woocommerce_blocks_payment_method_type_registration',
     111                function( Automattic\WooCommerce\Blocks\Payments\PaymentMethodRegistry $payment_method_registry ) {
     112                    $payment_method_registry->register( new WC_Gateway_Best2pay_Blocks_Support() );
     113                }
     114            );
     115        }
     116    }
     117}
    748118
    749     function add_best2pay_gateway($methods) {
    750         $methods[] = 'woocommerce_best2pay';
    751 
    752         return $methods;
    753     }
    754 
    755     add_filter('woocommerce_payment_gateways', 'add_best2pay_gateway');
    756 
    757     add_filter('plugin_action_links_' . plugin_basename( __FILE__ ),
    758         function($links) {
    759             if (!class_exists('woocommerce'))
    760                 return $links;
    761 
    762             array_unshift($links, sprintf('<a href="%1$s">%2$s</a>', admin_url('admin.php?page=wc-settings&tab=checkout&section=best2pay'), __('Settings', 'best2pay-payment')));
    763 
    764             return $links;
    765         }
    766     );
    767 }
     119WC_Best2pay_Payments::init();
  • best2pay-payment-method-visamastercard/trunk/languages/best2pay-payment-ru_RU.po

    r3213969 r3266993  
    33msgid ""
    44msgstr ""
    5 "Project-Id-Version: Best2Pay payment module 3.0.1\n"
     5"Project-Id-Version: Best2Pay payment module 3.2.14\n"
    66"Report-Msgid-Bugs-To: https://wordpress.org/support/plugin/best2pay-payment-method-visamastercard\n"
    77"Last-Translator: FULL NAME <EMAIL@ADDRESS>\n"
  • best2pay-payment-method-visamastercard/trunk/languages/best2pay-payment.pot

    r3213969 r3266993  
    33msgid ""
    44msgstr ""
    5 "Project-Id-Version: Best2Pay payment module 3.0.1\n"
     5"Project-Id-Version: Best2Pay payment module 3.2.14\n"
    66"Report-Msgid-Bugs-To: https://wordpress.org/support/plugin/best2pay-payment-method-visamastercard\n"
    77"Last-Translator: FULL NAME <EMAIL@ADDRESS>\n"
  • best2pay-payment-method-visamastercard/trunk/readme.txt

    r3213755 r3266993  
    55Tested up to: 6.6.1
    66Requires PHP: 8.1
    7 Stable tag: 3.0.1
     7Stable tag: 3.2.14
    88WC requires at least: 6.0
    99WC tested up to: 9.1.2
Note: See TracChangeset for help on using the changeset viewer.