💦 FULL SET: Changeset/ - HD Photos!

Changeset 3033150


Ignore:
Timestamp:
02/08/2024 12:10:12 PM (23 months ago)
Author:
redmonkey73
Message:

Update to version 2.8 from GitHub

Location:
bonus-plus-wp
Files:
4 added
8 deleted
33 edited
1 copied

Legend:

Unmodified
Added
Removed
  • bonus-plus-wp/assets/banner-1544x500.png

    • Property svn:mime-type changed from application/octet-stream to image/png
  • bonus-plus-wp/assets/banner-772x250.png

    • Property svn:mime-type changed from application/octet-stream to image/png
  • bonus-plus-wp/assets/icon-128x128.png

    • Property svn:mime-type changed from application/octet-stream to image/png
  • bonus-plus-wp/assets/icon-256x256.png

    • Property svn:mime-type changed from application/octet-stream to image/png
  • bonus-plus-wp/assets/icon.svg

    • Property svn:mime-type set to image/svg+xml
  • bonus-plus-wp/assets/screenshot-1.jpg

    • Property svn:mime-type changed from application/octet-stream to image/jpeg
  • bonus-plus-wp/assets/screenshot-2.jpg

    • Property svn:mime-type changed from application/octet-stream to image/jpeg
  • bonus-plus-wp/assets/screenshot-3.jpg

    • Property svn:mime-type changed from application/octet-stream to image/jpeg
  • bonus-plus-wp/assets/screenshot-4.jpg

    • Property svn:mime-type changed from application/octet-stream to image/jpeg
  • bonus-plus-wp/assets/screenshot-5.png

    • Property svn:mime-type changed from application/octet-stream to image/png
  • bonus-plus-wp/assets/scrrnshots-6.png

    • Property svn:mime-type changed from application/octet-stream to image/png
  • bonus-plus-wp/tags/2.8/bonus-plus-wp.php

    r3011611 r3033150  
    88 * Developer: redmonkey73
    99 * Developer URI: https://github.com/evgrezanov/
    10  * Text Domain: wp-bonus-plus
     10 * Text Domain: bonus-plus-wp
    1111 * Domain Path: /languages
    1212 * License: GPLv2 or later
     
    1515 * WP requires at least: 6.0
    1616 * Tested up to: 6.4.2
    17  * Version: 2.7
     17 * Version: 2.8
    1818 */
    1919namespace BPWP;
     
    2828    public static function init()
    2929    {
    30         define('BPWP_PLUGIN_VERSION', '2.7');
     30        define('BPWP_PLUGIN_VERSION', '2.8');
    3131
    3232        require_once __DIR__ . '/functions.php';
     
    7171        if (in_array('woocommerce/woocommerce.php', apply_filters('active_plugins', get_option('active_plugins')))) {
    7272            require_once __DIR__ . '/inc/WooAccount.php';
     73            require_once __DIR__ . '/inc/ApiHelper.php';
    7374        }
    7475        require_once __DIR__ . '/inc/MenuSettings.php';
     
    7677        require_once __DIR__ . '/inc/ClientProfile.php';
    7778        require_once __DIR__ . '/inc/WooProductCatExport.php';
    78         require_once __DIR__ . '/inc/ApiHelper.php';
    7979        require_once __DIR__ . '/inc/CustomerBalance.php';
     80        require_once __DIR__ . '/inc/RestApiEndpoints.php';
    8081    }   
    8182
  • bonus-plus-wp/tags/2.8/functions.php

    r2975143 r3033150  
    5454            'body'        => $params,
    5555        );
     56        $args['headers']['Content-Length'] = strlen( $args['body'] ?: '' ); // Добавим Content-Length. Важно, если body пустой
    5657    }
    5758
     
    139140}
    140141
     142/**
     143 * Get the error message for a given code.
     144 *
     145 * @param int $code The error code.
     146 * @return string|false The error message, or false if not found.
     147 */
    141148function bpwp_api_get_error_msg($code)
    142149{
  • bonus-plus-wp/tags/2.8/inc/ApiHelper.php

    r3004945 r3033150  
    1818        add_action('woocommerce_before_cart_totals', [__CLASS__, 'bpwp_cart_checkout_bonusplus_price']);
    1919        add_action('woocommerce_checkout_before_order_review', [__CLASS__, 'bpwp_cart_checkout_bonusplus_price']);
    20         add_action('woocommerce_short_description', [__CLASS__, 'bpwp_single_product_bonusplus_price'], 10, 1);
     20        add_action('woocommerce_product_meta_end', [__CLASS__, 'bpwp_single_product_bonusplus_price'], 10);
    2121        add_action('woocommerce_cart_calculate_fees', [__CLASS__, 'add_custom_fee_on_checkout']);
    22        
     22
    2323    }
    2424
     
    3737       
    3838            WC()->cart->add_fee($fee_name, $fee_amount, $taxable, $tax_class);
    39 
    4039        }
    4140    }
     
    119118                'quantity'  => $quantity
    120119            );
     120            do_action('logger', $items);
     121           
    121122        }
    122123
     
    150151            $retailcalc = bpwp_api_request(
    151152                'retail/calc',
    152                 json_encode($params),
     153                wp_json_encode($params),
    153154                'PUT',
    154155            );
    155156           
    156             $response_code = wp_remote_retrieve_response_code($retailcalc);
     157            //$response_code = wp_remote_retrieve_response_code($retailcalc);
    157158
    158159            return $retailcalc;
     
    171172       
    172173        $output = '';
    173        
     174        // TODO добавить проверку на nonce if (isset($_GET['testrequest']) && isset($_GET['nonce']) && wp_verify_nonce($_GET['nonce'], 'nonce_action_name')) {}
    174175        if (isset($_GET['testrequest'])) {
    175176           
     
    235236
    236237            $output .= '<div class="bonus-plus-price">';
    237             $output .= '<p>Ваш бонусный баланс '. $available_bonuses .'.</p><p>Сумма бонусов, которые будут начислены '. $bonuses .'.</p><p> На эту покупку будет списано '. $maxDebitBonuses .' бон.</p>';
     238            $output .= '<p>Ваш бонусный баланс '. $available_bonuses .'.</p><p>Сумма бонусов, которые будут начислены '. $bonuses .'.</p><p> На эту покупку будет списано '. $maxDebitBonuses .' бонусов</p>';
    238239            $output .= '</div>';
    239240           
     
    243244    }
    244245
     246    /**
     247     * Renders retail items calculation based on the provided data.
     248     *
     249     * @param array $data The data for the retail items calculation.
     250     */
    245251    public static function bpwp_render_retailitems_calc($data)
    246252    {
     
    274280
    275281    /**
    276      *
    277      */
    278     public static function bpwp_single_product_bonusplus_price($post_excerpt){
     282     *  Выводит доступные бонусы на странице товара
     283     */
     284    public static function bpwp_single_product_bonusplus_price(){
     285       
     286        if (!is_product()) {
     287            return;
     288        }
     289       
    279290        $content = '';
    280        
    281         if (is_product()) {
    282             $price_data = self::bpwp_get_calc_bonusplus_price();
    283             $content = $post_excerpt . self::bpwp_render_retailitems_calc($price_data);
    284         }
    285 
     291        $price_data = self::bpwp_get_calc_bonusplus_price();
     292        $content = self::bpwp_render_retailitems_calc($price_data);
     293           
    286294        return $content;
    287295    }
     
    301309    }
    302310
     311    /**
     312     * Get the maximum debit bonuses from the provided data array.
     313     *
     314     * @param array $data The input data array
     315     */
    303316    public function bpwp_get_max_debit_bonuses($data) {
    304317        if (is_array($data) && isset($data['request']) && isset($data['request']['discount'])) {
     
    309322}
    310323
     324
     325
    311326BPWPApiHelper::init();
  • bonus-plus-wp/tags/2.8/inc/ClientProfile.php

    r3004945 r3033150  
    1616        add_action('wp_login', [__CLASS__, 'bpwp_customer_login'], 10, 2);
    1717        add_filter('bpwp_replace_customer_card_desc', [__CLASS__, 'bpwp_replace_customer_card_desc'], 10, 2);
     18        //add_action('woocommerce_customer_save_address', [__CLASS__, 'bpwp_remove_user_meta_on_address_change'], 10, 2);
    1819    }
    1920
     
    138139            // Проверим заполнены ли у порльзователя дата рождения и телефон
    139140            $user_id = get_current_user_id();
    140             $billing_birth_date = get_user_meta( $user_id, 'billing_birth_date', true );
    141141            $billing_phone = get_user_meta(get_current_user_id(), 'billing_phone', true);
    142142            $bonus_plus = get_user_meta(get_current_user_id(), 'bonus-plus', true);
    143143           
    144             if ( empty( $billing_birth_date ) || empty($billing_phone) ) {
     144            if (empty($billing_phone) ) {
    145145                $data['title']  =   __('ОШИБКА!', 'bonus-plus-wp');
    146146                $data['url']    =   get_option('bpwp_uri_customers_lk_billing_address');
    147                 $data['desc']   =   'Добавьте дату рождения и/или номер телефона в личном кабинете';
     147                $data['desc']   =   'Добавьте номер телефона в личном кабинете';
    148148                $data['class']  =   'card3';
    149149                // или данные из Бонус+ пустые
     
    239239        }
    240240    }
     241   
     242    /**
     243     * Обновление метаданных Бонус+ при сохранении адреса из личного кабинета пользователя
     244     *
     245     *  @param int    $user_id      User ID being saved.
     246     *  @param string $address_type Type of address; 'billing' or 'shipping'.
     247     *
     248     * @return void
     249     *
     250     */
     251    public static function bpwp_remove_user_meta_on_address_change( $user_id, $load_address ){
     252        if ( ! is_user_logged_in() ) return;
     253
     254        if ( $load_address !== 'billing') return;
     255        // TODO: Если есть мета и тел bonus-plus['phone] и billing_phone не совпадают, то чистим мета
     256        $user = get_user_by_id($user_id);
     257
     258        //self::bpwp_customer_login($user->user_login, $user);
     259    }
    241260}
    242261BPWPProfile::init();
  • bonus-plus-wp/tags/2.8/inc/CustomerBalance.php

    r3004945 r3033150  
    1717        // Заказ выполнен, запрос с начислением бонусов. Комментарий в заказ - "бонусы начисены"
    1818        add_action('woocommerce_order_status_completed', [__CLASS__, 'bpwp_customer_balance_bonusplus']);
    19        
    2019    }
    2120
     
    2726        $user_id = $order->get_user_id();
    2827               
    29         // TODO Получить бонусы для списания и добавить в мета заказа
     28        // Получить бонусы для списания и добавить в мета заказа
    3029        $data = BPWPApiHelper::bpwp_get_calc_bonusplus_price();
    3130
     
    3433        }
    3534
    36         // Запрос Резервируем бонусы
    37         /*
    38         https://bonusplus.pro/api/Help/Api/PATCH-customer-phoneNumber-balance-reserve
    39         */
    40 
    41         // Резервируем бонусы, передаем положительное число
    42 
     35       
    4336        $order_data = array(
    4437            'billing_phone' => bpwp_api_get_customer_phone($user_id),
     
    4740        );
    4841       
     42        /* Запрос Резервируем бонусы, передаем положительное число
     43        https://bonusplus.pro/api/Help/Api/PATCH-customer-phoneNumber-balance-reserve
     44        */
    4945        $balance_reserve = self::bpwp_balance_reserve($order_data);
    5046
    51        
    52         $info = bpwp_api_get_customer_data();
    53        
    54         if ($info && is_array($info)) {
    55             $info['availableBonuses'] = $info['availableBonuses'] - $bonus_debit;
    56            
    57             update_user_meta($user_id, 'bonus-plus', $info);
    58         }
    59        
    60        
    61         //TODO В инфо заказа фильтр, начислено бонусов
    62 
    63         /*
    64         bonus-plus [
    65             'availableBonuses' => 404.0
    66         ]
    67         */
    68         // Обновление данных заказа
    69         // if ($balance_reserve['code'] == 200){
    70         //     update_order_meta($order_id, 'bonus_debit', $bonus_debit);
    71            
    72         //     //update_user_meta($order_id, 'bonus_debit', $balance_reserve['request']['customer']);
    73         // }
    74 
    75         add_post_meta( $order_id, '_bonus_debit', $bonus_debit );
    76 
    77         //if ($deduction == 'true') { // TODO Если пользователь подтвердил списание бонусов
    78            
    79             // Добавим Скидку
    80             $item_id = wc_add_order_item( $order_id, array(
    81                 'order_item_name' => 'Списание бонусов',
    82                 'order_item_type' => 'fee'
    83                 ) );
    84                
    85                 wc_add_order_item_meta( $item_id, '_line_total', wc_format_decimal( -$bonus_debit) );
    86            
    87             $order->calculate_totals();
    88             $order_id = $order->save();
    89 
    90         //} End if
    91 
     47        if ($balance_reserve['code'] == 204) {
     48       
     49            $info = bpwp_api_get_customer_data();
     50           
     51            if ($info && is_array($info)) {
     52                $info['availableBonuses'] = $info['availableBonuses'] - $bonus_debit;
     53               
     54                update_user_meta($user_id, 'bonus-plus', $info);
     55            }
     56
     57            add_post_meta( $order_id, '_bonus_debit', $bonus_debit, true);
     58       
     59        } else {
     60            do_action(
     61                'bpwp_logger',
     62                $type = __CLASS__,
     63                $title = __('Ошибка при резервировании бонусов', 'bonus-plus-wp'),
     64                $desc = sprintf(__('У заказа ИД %s, бонусы не зарезервированы!', 'bonus-plus-wp'), $order_id),
     65            );
     66        }
    9267    }
    9368
     
    10681            $balance_reserve = bpwp_api_request(
    10782                '/customer/'. $order_data['billing_phone'] .'/balance/reserve',
    108                 json_encode($params),
     83                wp_json_encode($params),
    10984                'PATCH',
    11085            );
    111            
     86
    11287            return $balance_reserve;
    113         }
    114 
    115     }
    116    
     88
     89        }
     90    }
    11791
    11892    /**
     
    135109            // Освобождаем из резерва, передаем отрицательное число
    136110            $balance_reserve = self::bpwp_balance_reserve($order_data);
    137         }
    138        
    139         //Проведение продажи в БонусПлюс
    140         $retail = self::bpwp_get_order_bonuses($order_id);
    141 
    142         // Обновление данных пользователя
    143         if ($retail['code'] == 200){
    144 
    145             update_user_meta($user_id, 'bonus-plus', $retail['request']['customer']);
     111           
     112            if ($balance_reserve['code'] == 204) {
     113               
     114                //Проведение продажи в БонусПлюс
     115                $retail = self::bpwp_get_order_bonuses($order_id);
     116   
     117                // Обновление данных пользователя
     118                if ($retail['code'] == 200){
     119                    update_user_meta($user_id, 'bonus-plus', $retail['request']['customer']);
     120                } else {
     121                    do_action(
     122                    'bpwp_logger',
     123                    $type = __CLASS__,
     124                    $title = __('Проведение продажи в БонусПлюс', 'bonus-plus-wp'),
     125                    $desc = sprintf(__('Заказа ИД %s, код ошибки %s', 'bonus-plus-wp'), $order_id,),
     126                    );
     127                }
     128
     129            } else {
     130                do_action(
     131                    'bpwp_logger',
     132                    $type = __CLASS__,
     133                    $title = __('Ошибка при списании бонусов', 'bonus-plus-wp'),
     134                    $desc = sprintf(__('У заказа ИД %s, бонусы не зарезервированы!', 'bonus-plus-wp'), $order_id),
     135                );
     136            }
    146137        }
    147138    }
     
    181172        // Отправим запрос "Проведение продажи в БонусПлюс"
    182173        if (!empty($billingPhone) && !empty($store) && count($items) >= 1){
    183             $retail = bpwp_api_request(
    184                 'retail',
    185                 json_encode($params),
    186                 'POST',
    187             );
    188            
     174        $retail = bpwp_api_request(
     175            'retail',
     176            wp_json_encode($params),
     177            'POST',
     178        );
    189179            return $retail;
    190180        }
    191 
    192181    }
    193182
  • bonus-plus-wp/tags/2.8/inc/Logger.php

    r2577633 r3033150  
    6060
    6161      if (is_array($description)) {
    62         $description = json_encode($description, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE);
     62        $description = wp_json_encode($description, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE);
    6363      } else {
    6464        $description = wc_print_r($description, true);
     
    9292    if (!empty($description)) {
    9393      if (is_array($description)) {
    94         $description = json_encode($description, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE);
     94        $description = wp_json_encode($description, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE);
    9595      } else {
    9696        $description = wc_print_r($description, true);
  • bonus-plus-wp/tags/2.8/inc/MenuSettings.php

    r3004945 r3033150  
    483483
    484484            printf('<a href="%s">Вернуться...</a>', remove_query_arg('a', self::$url));
    485            
     485            // TODO Processing form data without nonce verification.
     486            // if ( isset( $_GET['a'] ) && isset( $_GET['nonce'] ) && wp_verify_nonce( $_GET['nonce'], 'your_action_nonce' ) ) {
     487            //do_action( 'bpwp_tool_actions_' . $_GET['a'] );
     488            //}
    486489            do_action('bpwp_tool_actions_' . $_GET['a']);
    487490
  • bonus-plus-wp/tags/2.8/inc/WooAccount.php

    r3004945 r3033150  
    3434        add_action('wp_enqueue_scripts', [__CLASS__, 'bpwp_qrcode_scripts']);
    3535        add_filter('bpwp_debug_phone_verify', '__return_true');
    36         add_filter('woocommerce_billing_fields', [__CLASS__, 'bpwp_add_birth_date_billing_field'], 20, 1);
    37         if (wp_doing_ajax()) {
    38             add_action('wp_ajax_nopriv_bpwp_cv', [__CLASS__, 'bpwp_client_verify_phone_callback']);
    39             add_action('wp_ajax_bpwp_cv', [__CLASS__, 'bpwp_client_verify_phone_callback']);
    40         }
     36
    4137    }
    4238
     
    110106            if (empty($is_debug)) {
    111107                printf('<h2>%s</h2>', 'Информация по карте лояльности');
     108
     109                echo '<div id="loader" class="center-body"><div class="loader-ball-8"></div></div>';
    112110
    113111                //do_action('bpwp_after_bonus_card_info_title');
     
    185183        $customerData = bpwp_api_get_customer_data();
    186184        $cardNumber = !empty($customerData['discountCardNumber']) ? $customerData['discountCardNumber'] : '';
    187         //$clientInfo = [];
    188         $apiKey = '';
    189         $sendSmsUri = '';
    190         $sendOtpUri = '';
    191         $registrationUri = '';
    192 
    193         if (!empty($phone = get_user_meta(get_current_user_id(), 'billing_phone', true))) {
    194             $apiKey = base64_encode(esc_attr(get_option('bpwp_api_key')));
    195             $sendSmsUri = sprintf('https://bonusplus.pro/api/customer/%s/sendCode/', $phone);
    196             $sendOtpUri = sprintf('https://bonusplus.pro/api/customer/%s/checkCode/', $phone);
    197             $registrationUri = 'https://bonusplus.pro/api/customer/';
    198             //$clientInfo = self::bpwp_get_client_registration_data(get_current_user_id());
    199         }
     185        $phone = get_user_meta(get_current_user_id(), 'billing_phone', true);
    200186
    201187        wp_enqueue_script(
     
    208194
    209195        wp_enqueue_script(
    210             'accountjs',
    211             plugins_url('/assets/account.js', __DIR__),
     196            'customerjs',
     197            plugins_url('/assets/customer.js', __DIR__),
    212198            ['qrcodejs', 'jquery'],
    213199            BPWP_PLUGIN_VERSION,
     
    215201        );
    216202
     203        wp_enqueue_script( 'wp-api' );
     204
    217205        wp_localize_script(
    218             'accountjs',
     206            'customerjs',
    219207            'accountBonusPlusData',
    220208            array(
    221                 'auth'              => esc_attr($apiKey),
    222                 'sendSmsUri'        => $sendSmsUri,
    223                 'sendOtpUri'        => $sendOtpUri,
    224                 'registrationUri'   => esc_attr($registrationUri),
    225                 'redirect'          => site_url() . '/my-account/',
    226                 'ajax_url'          => admin_url('admin-ajax.php'),
    227                 'cardNumber'        => esc_attr($cardNumber),
    228                 'debug'             => apply_filters('bpwp_debug_phone_verify', false),
    229                 'clientInfo'        => json_encode(self::bpwp_get_client_registration_data(get_current_user_id())),
     209                'phone'      => esc_attr($phone),
     210                'cardNumber' => esc_attr($cardNumber),
     211                'redirect'   => site_url() . '/my-account/bonus-plus/',
     212                'debug'      => apply_filters('bpwp_debug_phone_verify', false),
    230213            )
    231214        );
     
    240223        $phone = !empty(get_user_meta(get_current_user_id(), 'billing_phone', true)) ? get_user_meta(get_current_user_id(), 'billing_phone', true) : '';
    241224
    242         $birthDate = !empty(get_user_meta(get_current_user_id(), 'billing_birth_date', true)) ? get_user_meta(get_current_user_id(), 'billing_birth_date', true) : '';
    243 
    244225        $verifiedUser = !empty(get_user_meta(get_current_user_id(), 'bpwp_verified_user', true)) ? get_user_meta(get_current_user_id(), 'bpwp_verified_user', true) : '';
    245226
     
    248229        if (empty($phone)) {
    249230
    250             $msg .= sprintf('<h3>%s</h3>', __('Пожалуйста заполнить платежный адрес и телефон', 'bonus-plus-wp'));
    251         } else if (empty($birthDate)) {
    252 
    253             $msg .= sprintf('<h3>%s</h3>', __('Пожалуйста заполните дату рождения в платежном адресе', 'bonus-plus-wp'));
     231            $msg .= sprintf('<h3>%s</h3>', __('Пожалуйста, заполните платежный адрес и телефон', 'bonus-plus-wp'));
     232            $msg .= sprintf('<a href="%s">%s</a>', '/my-account/edit-address/billing/', __('Перейти к заполнению данных', 'bonus-plus-wp'));
    254233        } else if (empty($verifiedUser)) {
    255234
     
    277256            <div hidden id="bpmsg" class="msg" style="display:none;"></div>
    278257
    279             <div id="qrcode" style="display:none;"></div>
    280 
    281             <div id='bpwp-registration' style="display:none;">
    282                 <p><?= __('Вы еще не зарегистрированы в программе лояльности', 'bonus-plus-wp') ?>
     258            <!-- <div id="qrcode" style="display:none;"></div> -->
     259
     260            <div id='bpwp-registration'>
     261                <p><?php echo __('Вы еще не зарегистрированы в программе лояльности', 'bonus-plus-wp') ?></p>
     262            </div>
     263
     264            <div id='bpwp-verify-start' style="display:none;">
     265                <p><?php echo __('Подтвердите номер телефона', 'bonus-plus-wp') ?>
     266                    <strong><?php echo $phone ?></strong>
    283267                </p>
    284                 <button id="bpwpRegistration"><?= __('Создать учетную запись', 'bonus-plus-wp') ?></button>
     268                <button id="bpwpSendSms"><?php echo __('Отправить SMS c кодом подтверждения', 'bonus-plus-wp') ?></button>
    285269            </div>
    286270
    287             <div id='bpwp-verify-start' style="display:none;">
    288                 <p><?= __('Подтвердите номер телефона', 'bonus-plus-wp') ?>
    289                     <strong><?= $phone ?></strong>
    290                 </p>
    291                 <button id="bpwpSendSms"><?= __('Отправить SMS c кодом подтверждения', 'bonus-plus-wp') ?></button>
    292             </div>
    293 
    294271            <div id='bpwp-verify-end' style="display:none;">
    295                 <p><?= __('Введите код высланый в SMS, на номер телефона:', 'bonus-plus-wp') ?>
    296                     <strong><?= $phone ?></strong>
     272                <p><?php echo __('Введите код высланый в SMS, на номер телефона:', 'bonus-plus-wp') ?>
     273                    <strong><?php echo $phone ?></strong>
    297274                </p>
    298275                <input id="bpwpOtpInput" type="number" maxLength="1" size="6" min="0" max="999999" pattern="[0-9]{6}" />
    299                 <button id="bpwpSendOtp"><?= __('Подтвердить номер телефона', 'bonus-plus-wp') ?></button>
     276                <button id="bpwpSendOtp"><?php echo __('Подтвердить номер телефона', 'bonus-plus-wp') ?></button>
    300277            </div>
    301278        </div>
    302279<?php
    303     }
    304 
    305     /**
    306      *  Добавим обязательное поле "Дата рождения" в платежный адрес
    307      */
    308     public static function bpwp_add_birth_date_billing_field($billing_fields)
    309     {
    310         $billing_fields['billing_birth_date'] = array(
    311             'type'        => 'date',
    312             'label'       => __('Дата рождения', 'bonus-plus-wp'),
    313             'class'       => array('form-row-wide'),
    314             'priority'    => 25,
    315             'required'    => true,
    316             'clear'       => true,
    317         );
    318 
    319         return $billing_fields;
    320     }
    321 
    322     /**
    323      * AJAX Callback
    324      * Always Echos and Exits
    325      */
    326     public static function bpwp_client_verify_phone_callback()
    327     {
    328         // Ensure we have the data we need to continue
    329         if (!is_user_logged_in()) {
    330             // If we don't - return custom error message and exit
    331             header('HTTP/1.1 400 Empty POST Values');
    332             wp_send_json('Could Not Verify POST Values.');
    333             wp_die();
    334         }
    335         $user_id = get_current_user_id();
    336 
    337         // if user already register, make verify phone request
    338         $phone = bpwp_api_get_customer_phone($user_id);
    339 
    340         if (!empty($phone)) {
    341             $res = bpwp_api_request(
    342                 'customer',
    343                 array(
    344                     'phone' => $phone
    345                 ),
    346                 'GET'
    347             );
    348             if (!empty($res['request'])) {
    349                 $response = $res['request']['response'];
    350                 update_user_meta($user_id, 'bonus-plus', $res['request']);
    351                 $result = $res['request'];
    352                 // todo
    353                 // ... parse response data and return cardnumber
    354                 wp_send_json($res);
    355                 wp_die();
    356             }
    357         }
    358280    }
    359281
     
    379301        $billingEmail = !empty($customer['billing_email']) ? $customer['billing_email'] : '-';
    380302        $billingPhone = !empty($customer['billing_phone']) ? $customer['billing_phone'] : '-';
    381         // ДД.ММ.ГГГГ
    382         if (isset($customer['billing_birth_date'])) {
    383             $originalBDate = $customer['billing_birth_date'][0];
    384             $newBDate = date("d.m.Y", strtotime($originalBDate));
    385         } else {
    386             $newBDate = '';
    387         }
    388303
    389304        $registrationData = array();
    390305
    391         if ($firstName && $lastName && $newBDate && $billingEmail && $billingPhone) {
     306        if ($firstName && $lastName && $billingEmail && $billingPhone) {
    392307            /*
    393308            $registrationData['phone']      = $billingPhone;
     
    405320                'ln'         => $lastName[0],
    406321                'desc'       => __('Регистрация на сайте', 'bonus-plus-wp'),
    407                 'birthDay'   => $newBDate,
    408322            );
    409323            //$registrationData['address']   = $billingPostcode . $billingCountry . $billingState . $billingCity . $address1 . $address2;
     
    412326        return $registrationData;
    413327    }
     328
    414329}
     330
    415331BPWPMyAccount::init();
  • bonus-plus-wp/tags/2.8/inc/WooProductCatExport.php

    r3011611 r3033150  
    314314            $export = bpwp_api_request(
    315315                'product/import',
    316                 json_encode($params),
     316                wp_json_encode($params),
    317317                'POST',
    318318            );
     
    383383        ?>
    384384        <div class="wrap">
    385             <div id="message" class="<?= esc_attr($class) ?>">
     385            <div id="message" class="<?php echo esc_attr($class) ?>">
    386386                <?php
    387387                    foreach ($strings as $string) {
     
    404404        //Get all terms associated with post in woocommerce's taxonomy 'product_cat'
    405405        $terms = get_the_terms($productId, 'product_cat');
    406 
    407         //Get an array of their IDs
    408         $term_ids = wp_list_pluck($terms, 'term_id');
    409 
    410         //Get array of parents - 0 is not a parent
    411         $parents = array_filter(wp_list_pluck($terms, 'parent'));
    412 
    413         //Get array of IDs of terms which are not parents.
    414         $term_ids_not_parents = array_diff($term_ids,  $parents);
    415 
    416         //Get corresponding term objects.
    417         $terms_not_parents = array_intersect_key($terms,  $term_ids_not_parents);
    418 
    419         return $terms_not_parents;
     406       
     407        // Check if terms exist and is not a WP_Error
     408        if (is_array($terms) && !is_wp_error($terms)) {
     409
     410            //Get an array of their IDs
     411            $term_ids = wp_list_pluck($terms, 'term_id');
     412
     413            //Get array of parents - 0 is not a parent
     414            $parents = array_filter(wp_list_pluck($terms, 'parent'));
     415
     416            //Get array of IDs of terms which are not parents.
     417            $term_ids_not_parents = array_diff($term_ids,  $parents);
     418
     419            //Get corresponding term objects.
     420            $terms_not_parents = array_intersect_key($terms,  $term_ids_not_parents);
     421
     422            return $terms_not_parents;
     423        }
     424
     425        // Return an empty array if there are no terms or an error occurred
     426        return array();
    420427    }
    421428}
  • bonus-plus-wp/tags/2.8/readme.txt

    r3011611 r3033150  
    55Requires at least: 4.0
    66Tested up to: 6.4.2
    7 Stable tag: 2.7
     7Stable tag: 2.8
    88Requires PHP: 8.1
    99License: GPLv2 or later
     
    4646= Automatic installation =
    4747
    48 Automatic installation is the easiest option -- WordPress will handles the file transfer, and you won’t need to leave your web browser. To do an automatic install of WP-bonus-plus, log in to your WordPress dashboard, navigate to the Plugins menu, and click “Add New.”
     48Automatic installation is the easiest option -- WordPress will handles the file transfer, and you won’t need to leave your web browser. To do an automatic install of bonus-plus-wp, log in to your WordPress dashboard, navigate to the Plugins menu, and click “Add New.”
    4949
    50 In the search field type “wp-bonus-plus,” then click “Search Plugins.” Once you’ve found us,  you can view details about it such as the point release, rating, and description. Most importantly of course, you can install it by! Click “Install Now,” and WordPress will take it from there.
     50In the search field type “bonus-plus-wp,” then click “Search Plugins.” Once you’ve found us,  you can view details about it such as the point release, rating, and description. Most importantly of course, you can install it by! Click “Install Now,” and WordPress will take it from there.
    5151
    5252= Manual installation =
    5353
    54 Manual installation method requires downloading the wp-bonus-plus plugin and uploading it to your web server via your favorite FTP application. The WordPress codex contains [instructions on how to do this here](https://wordpress.org/support/article/managing-plugins/#manual-plugin-installation).
     54Manual installation method requires downloading the bonus-plus-wp plugin and uploading it to your web server via your favorite FTP application. The WordPress codex contains [instructions on how to do this here](https://wordpress.org/support/article/managing-plugins/#manual-plugin-installation).
    5555
    5656
     
    9292
    9393== Changelog ==
     94
     95= 2.8 =
     96- убрали поле "дата рождения" из личного кабинета https://github.com/evgrezanov/bonus-plus-wp/issues/58
     97- добавлена обработка ошибок при экспорте товаров и категорий https://github.com/evgrezanov/bonus-plus-wp/issues/56
     98- рефакторинг процесса авторизации и регистрации в программе лояльности https://github.com/evgrezanov/bonus-plus-wp/issues/47
     99- исправлена функция списания и резервирования бонусов https://github.com/evgrezanov/bonus-plus-wp/issues/40
     100- исправлена проблема с безопастностью при генерации QR кода в личном кабинете исправить проблему с безопастностью https://github.com/evgrezanov/bonus-plus-wp/issues/21
    94101
    95102= 2.7 =
  • bonus-plus-wp/tags/2.8/templates/client-account.php

    r2627044 r3033150  
    1010
    1111    <div id='bpwp-registration' style="display:none;">
    12         <p><?= __('Вы еще не зарегистрированы в программе лояльности', 'bonus-plus-wp') ?>
     12        <p><?php echo __('Вы еще не зарегистрированы в программе лояльности', 'bonus-plus-wp') ?>
    1313        </p>
    14         <button id="bpwpRegistration"><?= __('Продолжить регистрацию', 'bonus-plus-wp') ?></button>
     14        <button id="bpwpRegistration"><?php echo __('Продолжить регистрацию', 'bonus-plus-wp') ?></button>
    1515    </div>
    1616
    1717    <div id='bpwp-verify-start' style="display:none;">
    18         <p><?= __('Для завершения регистрации в Бонус+, подтвердите номер телефона, после отправки СМС', 'bonus-plus-wp') ?>
    19             <strong><?= $phone ?></strong>
     18        <p><?php echo __('Для завершения регистрации в Бонус+, подтвердите номер телефона, после отправки СМС', 'bonus-plus-wp') ?>
     19        <strong><?php echo $phone; ?></strong>
    2020        </p>
    21         <button id="bpwpSendSms"><?= __('Отправить SMS c кодом подтверждения', 'bonus-plus-wp') ?></button>
     21        <button id="bpwpSendSms"><?php echo __('Отправить SMS c кодом подтверждения', 'bonus-plus-wp'); ?></button>
    2222    </div>
    2323
    2424    <div id='bpwp-verify-end' style="display:none;">
    25         <p><?= __('Введите код высланый в SMS, на номер телефона:', 'bonus-plus-wp') ?>
    26             <strong><?= $phone ?></strong>
     25        <p><?php echo __('Введите код высланый в SMS, на номер телефона:', 'bonus-plus-wp'); ?></p>
     26        <strong><?php echo $phone; ?></strong>
    2727        </p>
    2828        <input id="bpwpOtpInput" type="number" maxLength="1" size="6" min="0" max="999999" pattern="[0-9]{6}" />
    29         <button id="bpwpSendOtp"><?= __('Подтвердить', 'bonus-plus-wp') ?></button>
     29        <button id="bpwpSendOtp"><?php echo __('Подтвердить', 'bonus-plus-wp'); ?></button>
    3030    </div>
    3131</div>
  • bonus-plus-wp/trunk/bonus-plus-wp.php

    r3011611 r3033150  
    88 * Developer: redmonkey73
    99 * Developer URI: https://github.com/evgrezanov/
    10  * Text Domain: wp-bonus-plus
     10 * Text Domain: bonus-plus-wp
    1111 * Domain Path: /languages
    1212 * License: GPLv2 or later
     
    1515 * WP requires at least: 6.0
    1616 * Tested up to: 6.4.2
    17  * Version: 2.7
     17 * Version: 2.8
    1818 */
    1919namespace BPWP;
     
    2828    public static function init()
    2929    {
    30         define('BPWP_PLUGIN_VERSION', '2.7');
     30        define('BPWP_PLUGIN_VERSION', '2.8');
    3131
    3232        require_once __DIR__ . '/functions.php';
     
    7171        if (in_array('woocommerce/woocommerce.php', apply_filters('active_plugins', get_option('active_plugins')))) {
    7272            require_once __DIR__ . '/inc/WooAccount.php';
     73            require_once __DIR__ . '/inc/ApiHelper.php';
    7374        }
    7475        require_once __DIR__ . '/inc/MenuSettings.php';
     
    7677        require_once __DIR__ . '/inc/ClientProfile.php';
    7778        require_once __DIR__ . '/inc/WooProductCatExport.php';
    78         require_once __DIR__ . '/inc/ApiHelper.php';
    7979        require_once __DIR__ . '/inc/CustomerBalance.php';
     80        require_once __DIR__ . '/inc/RestApiEndpoints.php';
    8081    }   
    8182
  • bonus-plus-wp/trunk/functions.php

    r2975143 r3033150  
    5454            'body'        => $params,
    5555        );
     56        $args['headers']['Content-Length'] = strlen( $args['body'] ?: '' ); // Добавим Content-Length. Важно, если body пустой
    5657    }
    5758
     
    139140}
    140141
     142/**
     143 * Get the error message for a given code.
     144 *
     145 * @param int $code The error code.
     146 * @return string|false The error message, or false if not found.
     147 */
    141148function bpwp_api_get_error_msg($code)
    142149{
  • bonus-plus-wp/trunk/inc/ApiHelper.php

    r3004945 r3033150  
    1818        add_action('woocommerce_before_cart_totals', [__CLASS__, 'bpwp_cart_checkout_bonusplus_price']);
    1919        add_action('woocommerce_checkout_before_order_review', [__CLASS__, 'bpwp_cart_checkout_bonusplus_price']);
    20         add_action('woocommerce_short_description', [__CLASS__, 'bpwp_single_product_bonusplus_price'], 10, 1);
     20        add_action('woocommerce_product_meta_end', [__CLASS__, 'bpwp_single_product_bonusplus_price'], 10);
    2121        add_action('woocommerce_cart_calculate_fees', [__CLASS__, 'add_custom_fee_on_checkout']);
    22        
     22
    2323    }
    2424
     
    3737       
    3838            WC()->cart->add_fee($fee_name, $fee_amount, $taxable, $tax_class);
    39 
    4039        }
    4140    }
     
    119118                'quantity'  => $quantity
    120119            );
     120            do_action('logger', $items);
     121           
    121122        }
    122123
     
    150151            $retailcalc = bpwp_api_request(
    151152                'retail/calc',
    152                 json_encode($params),
     153                wp_json_encode($params),
    153154                'PUT',
    154155            );
    155156           
    156             $response_code = wp_remote_retrieve_response_code($retailcalc);
     157            //$response_code = wp_remote_retrieve_response_code($retailcalc);
    157158
    158159            return $retailcalc;
     
    171172       
    172173        $output = '';
    173        
     174        // TODO добавить проверку на nonce if (isset($_GET['testrequest']) && isset($_GET['nonce']) && wp_verify_nonce($_GET['nonce'], 'nonce_action_name')) {}
    174175        if (isset($_GET['testrequest'])) {
    175176           
     
    235236
    236237            $output .= '<div class="bonus-plus-price">';
    237             $output .= '<p>Ваш бонусный баланс '. $available_bonuses .'.</p><p>Сумма бонусов, которые будут начислены '. $bonuses .'.</p><p> На эту покупку будет списано '. $maxDebitBonuses .' бон.</p>';
     238            $output .= '<p>Ваш бонусный баланс '. $available_bonuses .'.</p><p>Сумма бонусов, которые будут начислены '. $bonuses .'.</p><p> На эту покупку будет списано '. $maxDebitBonuses .' бонусов</p>';
    238239            $output .= '</div>';
    239240           
     
    243244    }
    244245
     246    /**
     247     * Renders retail items calculation based on the provided data.
     248     *
     249     * @param array $data The data for the retail items calculation.
     250     */
    245251    public static function bpwp_render_retailitems_calc($data)
    246252    {
     
    274280
    275281    /**
    276      *
    277      */
    278     public static function bpwp_single_product_bonusplus_price($post_excerpt){
     282     *  Выводит доступные бонусы на странице товара
     283     */
     284    public static function bpwp_single_product_bonusplus_price(){
     285       
     286        if (!is_product()) {
     287            return;
     288        }
     289       
    279290        $content = '';
    280        
    281         if (is_product()) {
    282             $price_data = self::bpwp_get_calc_bonusplus_price();
    283             $content = $post_excerpt . self::bpwp_render_retailitems_calc($price_data);
    284         }
    285 
     291        $price_data = self::bpwp_get_calc_bonusplus_price();
     292        $content = self::bpwp_render_retailitems_calc($price_data);
     293           
    286294        return $content;
    287295    }
     
    301309    }
    302310
     311    /**
     312     * Get the maximum debit bonuses from the provided data array.
     313     *
     314     * @param array $data The input data array
     315     */
    303316    public function bpwp_get_max_debit_bonuses($data) {
    304317        if (is_array($data) && isset($data['request']) && isset($data['request']['discount'])) {
     
    309322}
    310323
     324
     325
    311326BPWPApiHelper::init();
  • bonus-plus-wp/trunk/inc/ClientProfile.php

    r3004945 r3033150  
    1616        add_action('wp_login', [__CLASS__, 'bpwp_customer_login'], 10, 2);
    1717        add_filter('bpwp_replace_customer_card_desc', [__CLASS__, 'bpwp_replace_customer_card_desc'], 10, 2);
     18        //add_action('woocommerce_customer_save_address', [__CLASS__, 'bpwp_remove_user_meta_on_address_change'], 10, 2);
    1819    }
    1920
     
    138139            // Проверим заполнены ли у порльзователя дата рождения и телефон
    139140            $user_id = get_current_user_id();
    140             $billing_birth_date = get_user_meta( $user_id, 'billing_birth_date', true );
    141141            $billing_phone = get_user_meta(get_current_user_id(), 'billing_phone', true);
    142142            $bonus_plus = get_user_meta(get_current_user_id(), 'bonus-plus', true);
    143143           
    144             if ( empty( $billing_birth_date ) || empty($billing_phone) ) {
     144            if (empty($billing_phone) ) {
    145145                $data['title']  =   __('ОШИБКА!', 'bonus-plus-wp');
    146146                $data['url']    =   get_option('bpwp_uri_customers_lk_billing_address');
    147                 $data['desc']   =   'Добавьте дату рождения и/или номер телефона в личном кабинете';
     147                $data['desc']   =   'Добавьте номер телефона в личном кабинете';
    148148                $data['class']  =   'card3';
    149149                // или данные из Бонус+ пустые
     
    239239        }
    240240    }
     241   
     242    /**
     243     * Обновление метаданных Бонус+ при сохранении адреса из личного кабинета пользователя
     244     *
     245     *  @param int    $user_id      User ID being saved.
     246     *  @param string $address_type Type of address; 'billing' or 'shipping'.
     247     *
     248     * @return void
     249     *
     250     */
     251    public static function bpwp_remove_user_meta_on_address_change( $user_id, $load_address ){
     252        if ( ! is_user_logged_in() ) return;
     253
     254        if ( $load_address !== 'billing') return;
     255        // TODO: Если есть мета и тел bonus-plus['phone] и billing_phone не совпадают, то чистим мета
     256        $user = get_user_by_id($user_id);
     257
     258        //self::bpwp_customer_login($user->user_login, $user);
     259    }
    241260}
    242261BPWPProfile::init();
  • bonus-plus-wp/trunk/inc/CustomerBalance.php

    r3004945 r3033150  
    1717        // Заказ выполнен, запрос с начислением бонусов. Комментарий в заказ - "бонусы начисены"
    1818        add_action('woocommerce_order_status_completed', [__CLASS__, 'bpwp_customer_balance_bonusplus']);
    19        
    2019    }
    2120
     
    2726        $user_id = $order->get_user_id();
    2827               
    29         // TODO Получить бонусы для списания и добавить в мета заказа
     28        // Получить бонусы для списания и добавить в мета заказа
    3029        $data = BPWPApiHelper::bpwp_get_calc_bonusplus_price();
    3130
     
    3433        }
    3534
    36         // Запрос Резервируем бонусы
    37         /*
    38         https://bonusplus.pro/api/Help/Api/PATCH-customer-phoneNumber-balance-reserve
    39         */
    40 
    41         // Резервируем бонусы, передаем положительное число
    42 
     35       
    4336        $order_data = array(
    4437            'billing_phone' => bpwp_api_get_customer_phone($user_id),
     
    4740        );
    4841       
     42        /* Запрос Резервируем бонусы, передаем положительное число
     43        https://bonusplus.pro/api/Help/Api/PATCH-customer-phoneNumber-balance-reserve
     44        */
    4945        $balance_reserve = self::bpwp_balance_reserve($order_data);
    5046
    51        
    52         $info = bpwp_api_get_customer_data();
    53        
    54         if ($info && is_array($info)) {
    55             $info['availableBonuses'] = $info['availableBonuses'] - $bonus_debit;
    56            
    57             update_user_meta($user_id, 'bonus-plus', $info);
    58         }
    59        
    60        
    61         //TODO В инфо заказа фильтр, начислено бонусов
    62 
    63         /*
    64         bonus-plus [
    65             'availableBonuses' => 404.0
    66         ]
    67         */
    68         // Обновление данных заказа
    69         // if ($balance_reserve['code'] == 200){
    70         //     update_order_meta($order_id, 'bonus_debit', $bonus_debit);
    71            
    72         //     //update_user_meta($order_id, 'bonus_debit', $balance_reserve['request']['customer']);
    73         // }
    74 
    75         add_post_meta( $order_id, '_bonus_debit', $bonus_debit );
    76 
    77         //if ($deduction == 'true') { // TODO Если пользователь подтвердил списание бонусов
    78            
    79             // Добавим Скидку
    80             $item_id = wc_add_order_item( $order_id, array(
    81                 'order_item_name' => 'Списание бонусов',
    82                 'order_item_type' => 'fee'
    83                 ) );
    84                
    85                 wc_add_order_item_meta( $item_id, '_line_total', wc_format_decimal( -$bonus_debit) );
    86            
    87             $order->calculate_totals();
    88             $order_id = $order->save();
    89 
    90         //} End if
    91 
     47        if ($balance_reserve['code'] == 204) {
     48       
     49            $info = bpwp_api_get_customer_data();
     50           
     51            if ($info && is_array($info)) {
     52                $info['availableBonuses'] = $info['availableBonuses'] - $bonus_debit;
     53               
     54                update_user_meta($user_id, 'bonus-plus', $info);
     55            }
     56
     57            add_post_meta( $order_id, '_bonus_debit', $bonus_debit, true);
     58       
     59        } else {
     60            do_action(
     61                'bpwp_logger',
     62                $type = __CLASS__,
     63                $title = __('Ошибка при резервировании бонусов', 'bonus-plus-wp'),
     64                $desc = sprintf(__('У заказа ИД %s, бонусы не зарезервированы!', 'bonus-plus-wp'), $order_id),
     65            );
     66        }
    9267    }
    9368
     
    10681            $balance_reserve = bpwp_api_request(
    10782                '/customer/'. $order_data['billing_phone'] .'/balance/reserve',
    108                 json_encode($params),
     83                wp_json_encode($params),
    10984                'PATCH',
    11085            );
    111            
     86
    11287            return $balance_reserve;
    113         }
    114 
    115     }
    116    
     88
     89        }
     90    }
    11791
    11892    /**
     
    135109            // Освобождаем из резерва, передаем отрицательное число
    136110            $balance_reserve = self::bpwp_balance_reserve($order_data);
    137         }
    138        
    139         //Проведение продажи в БонусПлюс
    140         $retail = self::bpwp_get_order_bonuses($order_id);
    141 
    142         // Обновление данных пользователя
    143         if ($retail['code'] == 200){
    144 
    145             update_user_meta($user_id, 'bonus-plus', $retail['request']['customer']);
     111           
     112            if ($balance_reserve['code'] == 204) {
     113               
     114                //Проведение продажи в БонусПлюс
     115                $retail = self::bpwp_get_order_bonuses($order_id);
     116   
     117                // Обновление данных пользователя
     118                if ($retail['code'] == 200){
     119                    update_user_meta($user_id, 'bonus-plus', $retail['request']['customer']);
     120                } else {
     121                    do_action(
     122                    'bpwp_logger',
     123                    $type = __CLASS__,
     124                    $title = __('Проведение продажи в БонусПлюс', 'bonus-plus-wp'),
     125                    $desc = sprintf(__('Заказа ИД %s, код ошибки %s', 'bonus-plus-wp'), $order_id,),
     126                    );
     127                }
     128
     129            } else {
     130                do_action(
     131                    'bpwp_logger',
     132                    $type = __CLASS__,
     133                    $title = __('Ошибка при списании бонусов', 'bonus-plus-wp'),
     134                    $desc = sprintf(__('У заказа ИД %s, бонусы не зарезервированы!', 'bonus-plus-wp'), $order_id),
     135                );
     136            }
    146137        }
    147138    }
     
    181172        // Отправим запрос "Проведение продажи в БонусПлюс"
    182173        if (!empty($billingPhone) && !empty($store) && count($items) >= 1){
    183             $retail = bpwp_api_request(
    184                 'retail',
    185                 json_encode($params),
    186                 'POST',
    187             );
    188            
     174        $retail = bpwp_api_request(
     175            'retail',
     176            wp_json_encode($params),
     177            'POST',
     178        );
    189179            return $retail;
    190180        }
    191 
    192181    }
    193182
  • bonus-plus-wp/trunk/inc/Logger.php

    r2577633 r3033150  
    6060
    6161      if (is_array($description)) {
    62         $description = json_encode($description, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE);
     62        $description = wp_json_encode($description, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE);
    6363      } else {
    6464        $description = wc_print_r($description, true);
     
    9292    if (!empty($description)) {
    9393      if (is_array($description)) {
    94         $description = json_encode($description, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE);
     94        $description = wp_json_encode($description, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE);
    9595      } else {
    9696        $description = wc_print_r($description, true);
  • bonus-plus-wp/trunk/inc/MenuSettings.php

    r3004945 r3033150  
    483483
    484484            printf('<a href="%s">Вернуться...</a>', remove_query_arg('a', self::$url));
    485            
     485            // TODO Processing form data without nonce verification.
     486            // if ( isset( $_GET['a'] ) && isset( $_GET['nonce'] ) && wp_verify_nonce( $_GET['nonce'], 'your_action_nonce' ) ) {
     487            //do_action( 'bpwp_tool_actions_' . $_GET['a'] );
     488            //}
    486489            do_action('bpwp_tool_actions_' . $_GET['a']);
    487490
  • bonus-plus-wp/trunk/inc/WooAccount.php

    r3004945 r3033150  
    3434        add_action('wp_enqueue_scripts', [__CLASS__, 'bpwp_qrcode_scripts']);
    3535        add_filter('bpwp_debug_phone_verify', '__return_true');
    36         add_filter('woocommerce_billing_fields', [__CLASS__, 'bpwp_add_birth_date_billing_field'], 20, 1);
    37         if (wp_doing_ajax()) {
    38             add_action('wp_ajax_nopriv_bpwp_cv', [__CLASS__, 'bpwp_client_verify_phone_callback']);
    39             add_action('wp_ajax_bpwp_cv', [__CLASS__, 'bpwp_client_verify_phone_callback']);
    40         }
     36
    4137    }
    4238
     
    110106            if (empty($is_debug)) {
    111107                printf('<h2>%s</h2>', 'Информация по карте лояльности');
     108
     109                echo '<div id="loader" class="center-body"><div class="loader-ball-8"></div></div>';
    112110
    113111                //do_action('bpwp_after_bonus_card_info_title');
     
    185183        $customerData = bpwp_api_get_customer_data();
    186184        $cardNumber = !empty($customerData['discountCardNumber']) ? $customerData['discountCardNumber'] : '';
    187         //$clientInfo = [];
    188         $apiKey = '';
    189         $sendSmsUri = '';
    190         $sendOtpUri = '';
    191         $registrationUri = '';
    192 
    193         if (!empty($phone = get_user_meta(get_current_user_id(), 'billing_phone', true))) {
    194             $apiKey = base64_encode(esc_attr(get_option('bpwp_api_key')));
    195             $sendSmsUri = sprintf('https://bonusplus.pro/api/customer/%s/sendCode/', $phone);
    196             $sendOtpUri = sprintf('https://bonusplus.pro/api/customer/%s/checkCode/', $phone);
    197             $registrationUri = 'https://bonusplus.pro/api/customer/';
    198             //$clientInfo = self::bpwp_get_client_registration_data(get_current_user_id());
    199         }
     185        $phone = get_user_meta(get_current_user_id(), 'billing_phone', true);
    200186
    201187        wp_enqueue_script(
     
    208194
    209195        wp_enqueue_script(
    210             'accountjs',
    211             plugins_url('/assets/account.js', __DIR__),
     196            'customerjs',
     197            plugins_url('/assets/customer.js', __DIR__),
    212198            ['qrcodejs', 'jquery'],
    213199            BPWP_PLUGIN_VERSION,
     
    215201        );
    216202
     203        wp_enqueue_script( 'wp-api' );
     204
    217205        wp_localize_script(
    218             'accountjs',
     206            'customerjs',
    219207            'accountBonusPlusData',
    220208            array(
    221                 'auth'              => esc_attr($apiKey),
    222                 'sendSmsUri'        => $sendSmsUri,
    223                 'sendOtpUri'        => $sendOtpUri,
    224                 'registrationUri'   => esc_attr($registrationUri),
    225                 'redirect'          => site_url() . '/my-account/',
    226                 'ajax_url'          => admin_url('admin-ajax.php'),
    227                 'cardNumber'        => esc_attr($cardNumber),
    228                 'debug'             => apply_filters('bpwp_debug_phone_verify', false),
    229                 'clientInfo'        => json_encode(self::bpwp_get_client_registration_data(get_current_user_id())),
     209                'phone'      => esc_attr($phone),
     210                'cardNumber' => esc_attr($cardNumber),
     211                'redirect'   => site_url() . '/my-account/bonus-plus/',
     212                'debug'      => apply_filters('bpwp_debug_phone_verify', false),
    230213            )
    231214        );
     
    240223        $phone = !empty(get_user_meta(get_current_user_id(), 'billing_phone', true)) ? get_user_meta(get_current_user_id(), 'billing_phone', true) : '';
    241224
    242         $birthDate = !empty(get_user_meta(get_current_user_id(), 'billing_birth_date', true)) ? get_user_meta(get_current_user_id(), 'billing_birth_date', true) : '';
    243 
    244225        $verifiedUser = !empty(get_user_meta(get_current_user_id(), 'bpwp_verified_user', true)) ? get_user_meta(get_current_user_id(), 'bpwp_verified_user', true) : '';
    245226
     
    248229        if (empty($phone)) {
    249230
    250             $msg .= sprintf('<h3>%s</h3>', __('Пожалуйста заполнить платежный адрес и телефон', 'bonus-plus-wp'));
    251         } else if (empty($birthDate)) {
    252 
    253             $msg .= sprintf('<h3>%s</h3>', __('Пожалуйста заполните дату рождения в платежном адресе', 'bonus-plus-wp'));
     231            $msg .= sprintf('<h3>%s</h3>', __('Пожалуйста, заполните платежный адрес и телефон', 'bonus-plus-wp'));
     232            $msg .= sprintf('<a href="%s">%s</a>', '/my-account/edit-address/billing/', __('Перейти к заполнению данных', 'bonus-plus-wp'));
    254233        } else if (empty($verifiedUser)) {
    255234
     
    277256            <div hidden id="bpmsg" class="msg" style="display:none;"></div>
    278257
    279             <div id="qrcode" style="display:none;"></div>
    280 
    281             <div id='bpwp-registration' style="display:none;">
    282                 <p><?= __('Вы еще не зарегистрированы в программе лояльности', 'bonus-plus-wp') ?>
     258            <!-- <div id="qrcode" style="display:none;"></div> -->
     259
     260            <div id='bpwp-registration'>
     261                <p><?php echo __('Вы еще не зарегистрированы в программе лояльности', 'bonus-plus-wp') ?></p>
     262            </div>
     263
     264            <div id='bpwp-verify-start' style="display:none;">
     265                <p><?php echo __('Подтвердите номер телефона', 'bonus-plus-wp') ?>
     266                    <strong><?php echo $phone ?></strong>
    283267                </p>
    284                 <button id="bpwpRegistration"><?= __('Создать учетную запись', 'bonus-plus-wp') ?></button>
     268                <button id="bpwpSendSms"><?php echo __('Отправить SMS c кодом подтверждения', 'bonus-plus-wp') ?></button>
    285269            </div>
    286270
    287             <div id='bpwp-verify-start' style="display:none;">
    288                 <p><?= __('Подтвердите номер телефона', 'bonus-plus-wp') ?>
    289                     <strong><?= $phone ?></strong>
    290                 </p>
    291                 <button id="bpwpSendSms"><?= __('Отправить SMS c кодом подтверждения', 'bonus-plus-wp') ?></button>
    292             </div>
    293 
    294271            <div id='bpwp-verify-end' style="display:none;">
    295                 <p><?= __('Введите код высланый в SMS, на номер телефона:', 'bonus-plus-wp') ?>
    296                     <strong><?= $phone ?></strong>
     272                <p><?php echo __('Введите код высланый в SMS, на номер телефона:', 'bonus-plus-wp') ?>
     273                    <strong><?php echo $phone ?></strong>
    297274                </p>
    298275                <input id="bpwpOtpInput" type="number" maxLength="1" size="6" min="0" max="999999" pattern="[0-9]{6}" />
    299                 <button id="bpwpSendOtp"><?= __('Подтвердить номер телефона', 'bonus-plus-wp') ?></button>
     276                <button id="bpwpSendOtp"><?php echo __('Подтвердить номер телефона', 'bonus-plus-wp') ?></button>
    300277            </div>
    301278        </div>
    302279<?php
    303     }
    304 
    305     /**
    306      *  Добавим обязательное поле "Дата рождения" в платежный адрес
    307      */
    308     public static function bpwp_add_birth_date_billing_field($billing_fields)
    309     {
    310         $billing_fields['billing_birth_date'] = array(
    311             'type'        => 'date',
    312             'label'       => __('Дата рождения', 'bonus-plus-wp'),
    313             'class'       => array('form-row-wide'),
    314             'priority'    => 25,
    315             'required'    => true,
    316             'clear'       => true,
    317         );
    318 
    319         return $billing_fields;
    320     }
    321 
    322     /**
    323      * AJAX Callback
    324      * Always Echos and Exits
    325      */
    326     public static function bpwp_client_verify_phone_callback()
    327     {
    328         // Ensure we have the data we need to continue
    329         if (!is_user_logged_in()) {
    330             // If we don't - return custom error message and exit
    331             header('HTTP/1.1 400 Empty POST Values');
    332             wp_send_json('Could Not Verify POST Values.');
    333             wp_die();
    334         }
    335         $user_id = get_current_user_id();
    336 
    337         // if user already register, make verify phone request
    338         $phone = bpwp_api_get_customer_phone($user_id);
    339 
    340         if (!empty($phone)) {
    341             $res = bpwp_api_request(
    342                 'customer',
    343                 array(
    344                     'phone' => $phone
    345                 ),
    346                 'GET'
    347             );
    348             if (!empty($res['request'])) {
    349                 $response = $res['request']['response'];
    350                 update_user_meta($user_id, 'bonus-plus', $res['request']);
    351                 $result = $res['request'];
    352                 // todo
    353                 // ... parse response data and return cardnumber
    354                 wp_send_json($res);
    355                 wp_die();
    356             }
    357         }
    358280    }
    359281
     
    379301        $billingEmail = !empty($customer['billing_email']) ? $customer['billing_email'] : '-';
    380302        $billingPhone = !empty($customer['billing_phone']) ? $customer['billing_phone'] : '-';
    381         // ДД.ММ.ГГГГ
    382         if (isset($customer['billing_birth_date'])) {
    383             $originalBDate = $customer['billing_birth_date'][0];
    384             $newBDate = date("d.m.Y", strtotime($originalBDate));
    385         } else {
    386             $newBDate = '';
    387         }
    388303
    389304        $registrationData = array();
    390305
    391         if ($firstName && $lastName && $newBDate && $billingEmail && $billingPhone) {
     306        if ($firstName && $lastName && $billingEmail && $billingPhone) {
    392307            /*
    393308            $registrationData['phone']      = $billingPhone;
     
    405320                'ln'         => $lastName[0],
    406321                'desc'       => __('Регистрация на сайте', 'bonus-plus-wp'),
    407                 'birthDay'   => $newBDate,
    408322            );
    409323            //$registrationData['address']   = $billingPostcode . $billingCountry . $billingState . $billingCity . $address1 . $address2;
     
    412326        return $registrationData;
    413327    }
     328
    414329}
     330
    415331BPWPMyAccount::init();
  • bonus-plus-wp/trunk/inc/WooProductCatExport.php

    r3011611 r3033150  
    314314            $export = bpwp_api_request(
    315315                'product/import',
    316                 json_encode($params),
     316                wp_json_encode($params),
    317317                'POST',
    318318            );
     
    383383        ?>
    384384        <div class="wrap">
    385             <div id="message" class="<?= esc_attr($class) ?>">
     385            <div id="message" class="<?php echo esc_attr($class) ?>">
    386386                <?php
    387387                    foreach ($strings as $string) {
     
    404404        //Get all terms associated with post in woocommerce's taxonomy 'product_cat'
    405405        $terms = get_the_terms($productId, 'product_cat');
    406 
    407         //Get an array of their IDs
    408         $term_ids = wp_list_pluck($terms, 'term_id');
    409 
    410         //Get array of parents - 0 is not a parent
    411         $parents = array_filter(wp_list_pluck($terms, 'parent'));
    412 
    413         //Get array of IDs of terms which are not parents.
    414         $term_ids_not_parents = array_diff($term_ids,  $parents);
    415 
    416         //Get corresponding term objects.
    417         $terms_not_parents = array_intersect_key($terms,  $term_ids_not_parents);
    418 
    419         return $terms_not_parents;
     406       
     407        // Check if terms exist and is not a WP_Error
     408        if (is_array($terms) && !is_wp_error($terms)) {
     409
     410            //Get an array of their IDs
     411            $term_ids = wp_list_pluck($terms, 'term_id');
     412
     413            //Get array of parents - 0 is not a parent
     414            $parents = array_filter(wp_list_pluck($terms, 'parent'));
     415
     416            //Get array of IDs of terms which are not parents.
     417            $term_ids_not_parents = array_diff($term_ids,  $parents);
     418
     419            //Get corresponding term objects.
     420            $terms_not_parents = array_intersect_key($terms,  $term_ids_not_parents);
     421
     422            return $terms_not_parents;
     423        }
     424
     425        // Return an empty array if there are no terms or an error occurred
     426        return array();
    420427    }
    421428}
  • bonus-plus-wp/trunk/readme.txt

    r3011611 r3033150  
    55Requires at least: 4.0
    66Tested up to: 6.4.2
    7 Stable tag: 2.7
     7Stable tag: 2.8
    88Requires PHP: 8.1
    99License: GPLv2 or later
     
    4646= Automatic installation =
    4747
    48 Automatic installation is the easiest option -- WordPress will handles the file transfer, and you won’t need to leave your web browser. To do an automatic install of WP-bonus-plus, log in to your WordPress dashboard, navigate to the Plugins menu, and click “Add New.”
     48Automatic installation is the easiest option -- WordPress will handles the file transfer, and you won’t need to leave your web browser. To do an automatic install of bonus-plus-wp, log in to your WordPress dashboard, navigate to the Plugins menu, and click “Add New.”
    4949
    50 In the search field type “wp-bonus-plus,” then click “Search Plugins.” Once you’ve found us,  you can view details about it such as the point release, rating, and description. Most importantly of course, you can install it by! Click “Install Now,” and WordPress will take it from there.
     50In the search field type “bonus-plus-wp,” then click “Search Plugins.” Once you’ve found us,  you can view details about it such as the point release, rating, and description. Most importantly of course, you can install it by! Click “Install Now,” and WordPress will take it from there.
    5151
    5252= Manual installation =
    5353
    54 Manual installation method requires downloading the wp-bonus-plus plugin and uploading it to your web server via your favorite FTP application. The WordPress codex contains [instructions on how to do this here](https://wordpress.org/support/article/managing-plugins/#manual-plugin-installation).
     54Manual installation method requires downloading the bonus-plus-wp plugin and uploading it to your web server via your favorite FTP application. The WordPress codex contains [instructions on how to do this here](https://wordpress.org/support/article/managing-plugins/#manual-plugin-installation).
    5555
    5656
     
    9292
    9393== Changelog ==
     94
     95= 2.8 =
     96- убрали поле "дата рождения" из личного кабинета https://github.com/evgrezanov/bonus-plus-wp/issues/58
     97- добавлена обработка ошибок при экспорте товаров и категорий https://github.com/evgrezanov/bonus-plus-wp/issues/56
     98- рефакторинг процесса авторизации и регистрации в программе лояльности https://github.com/evgrezanov/bonus-plus-wp/issues/47
     99- исправлена функция списания и резервирования бонусов https://github.com/evgrezanov/bonus-plus-wp/issues/40
     100- исправлена проблема с безопастностью при генерации QR кода в личном кабинете исправить проблему с безопастностью https://github.com/evgrezanov/bonus-plus-wp/issues/21
    94101
    95102= 2.7 =
  • bonus-plus-wp/trunk/templates/client-account.php

    r2627044 r3033150  
    1010
    1111    <div id='bpwp-registration' style="display:none;">
    12         <p><?= __('Вы еще не зарегистрированы в программе лояльности', 'bonus-plus-wp') ?>
     12        <p><?php echo __('Вы еще не зарегистрированы в программе лояльности', 'bonus-plus-wp') ?>
    1313        </p>
    14         <button id="bpwpRegistration"><?= __('Продолжить регистрацию', 'bonus-plus-wp') ?></button>
     14        <button id="bpwpRegistration"><?php echo __('Продолжить регистрацию', 'bonus-plus-wp') ?></button>
    1515    </div>
    1616
    1717    <div id='bpwp-verify-start' style="display:none;">
    18         <p><?= __('Для завершения регистрации в Бонус+, подтвердите номер телефона, после отправки СМС', 'bonus-plus-wp') ?>
    19             <strong><?= $phone ?></strong>
     18        <p><?php echo __('Для завершения регистрации в Бонус+, подтвердите номер телефона, после отправки СМС', 'bonus-plus-wp') ?>
     19        <strong><?php echo $phone; ?></strong>
    2020        </p>
    21         <button id="bpwpSendSms"><?= __('Отправить SMS c кодом подтверждения', 'bonus-plus-wp') ?></button>
     21        <button id="bpwpSendSms"><?php echo __('Отправить SMS c кодом подтверждения', 'bonus-plus-wp'); ?></button>
    2222    </div>
    2323
    2424    <div id='bpwp-verify-end' style="display:none;">
    25         <p><?= __('Введите код высланый в SMS, на номер телефона:', 'bonus-plus-wp') ?>
    26             <strong><?= $phone ?></strong>
     25        <p><?php echo __('Введите код высланый в SMS, на номер телефона:', 'bonus-plus-wp'); ?></p>
     26        <strong><?php echo $phone; ?></strong>
    2727        </p>
    2828        <input id="bpwpOtpInput" type="number" maxLength="1" size="6" min="0" max="999999" pattern="[0-9]{6}" />
    29         <button id="bpwpSendOtp"><?= __('Подтвердить', 'bonus-plus-wp') ?></button>
     29        <button id="bpwpSendOtp"><?php echo __('Подтвердить', 'bonus-plus-wp'); ?></button>
    3030    </div>
    3131</div>
Note: See TracChangeset for help on using the changeset viewer.