Plugin Directory

Changeset 3306040


Ignore:
Timestamp:
06/03/2025 08:36:11 PM (10 months ago)
Author:
bpostshippingplugins
Message:

Change how the plugin get's shipping address data

Location:
bpost-shipping-platform/trunk/includes
Files:
4 edited

Legend:

Unmodified
Added
Removed
  • bpost-shipping-platform/trunk/includes/admin/class-Bpost-options-ui.php

    r3304764 r3306040  
    236236
    237237
    238         BpostWoo::log("== Check Token [" . $this->token . '] ');
     238        BpostWoo::log("== Check Token");
    239239        if(!$this->token && $this->public_key && $this->private_key) {
    240240
  • bpost-shipping-platform/trunk/includes/admin/class-Bpost-shipping.php

    r3298706 r3306040  
    2727//    public $HasPickup;
    2828
    29     private $rate_limiter;
    30 
    31 
    3229    private function __construct(){
    3330        $this->actions();
     
    3532
    3633        $this->is_dev = defined('BPOST_DEV');
    37         $this->rate_limiter = new Bpost_Rate_Limiter();
    3834    }
    3935
     
    171167    public function ajax_get_selected_carrier()
    172168    {
    173 
    174169        if (WC()->session->get('shipping_pickup_id') !== null) {
    175170            WC()->session->__unset('shipping_pickup_id');
    176171        }
    177 
    178172        if (WC()->session->get('shipping_pickup_label') !== null) {
    179173            WC()->session->__unset('shipping_pickup_label');
    180174        }
    181 
    182175        if (WC()->session->get('Bpost_pickup_extended') !== null) {
    183176            WC()->session->__unset('Bpost_pickup_extended');
     
    188181        }
    189182
     183        //Unset previous Bpost_selected_carrier
     184        if (WC()->session->get('Bpost_selected_carrier') !== null) {
     185            WC()->session->__unset('Bpost_selected_carrier');
     186        }
     187       
    190188        $frontendCarrier = isset($_GET['carrier']) ? sanitize_text_field(wp_unslash($_GET['carrier'])) : '';
    191189
     
    216214            foreach ($value->settings['rules'] as $rule){
    217215                if ($rule['meta']['title'] == $frontendCarrier){
     216               
    218217                    $weightOption = [
    219218                        'optionId'=> $value->id,
     
    235234
    236235        if ($weightPudoOptions['service_level'] == 301 || $weightPudoOptions['service_level'] == 307 || $weightPudoOptions['service_level'] == 'BPSML02' || $weightPudoOptions['service_level'] == 'BPSML04'){
     236            WC()->session->set('Bpost_selected_carrier', $number);
     237           
    237238            echo wp_json_encode(['status' => 1,'carrier_id' => $number,'pickupMandatory' => true]);die();
    238239        }
     
    246247
    247248            if($carrier && $HasPickup) {
    248                 // Display the select point button unless it's configured as impossible
    249                 $settings = $this->get_settings_from_shipping_method_id($flatRateOption['optionId']);
    250 
     249                WC()->session->set('Bpost_selected_carrier', $carrier->Id);
     250               
    251251                if($flatRateOption['pickupbehaviour'] != BpostOrder::$PICKUP_BEHAVIOUR_IMPOSSIBLE && ($flatRateOption['service_level'] == 301 || $flatRateOption['service_level'] == 307 || $flatRateOption['service_level'] == 'BPSML02' || $flatRateOption['service_level'] == 'BPSML04')) {
    252252                    echo wp_json_encode(['status' => 1,'carrier_id' => $carrier->Id,'pickupMandatory' => true]);die();
     
    318318        $client_id = $this->get_client_identifier();
    319319
    320         // Check rate limit
    321         if ($this->rate_limiter->is_limited($client_id, 'get_pickup_locations')) {
    322             wp_send_json_error([
    323                 'message' => 'Rate limit exceeded. Please try again later.',
    324                 'remaining_attempts' => $this->rate_limiter->get_remaining_attempts($client_id, 'get_pickup_locations')
    325             ]);
    326             return;
    327         }
    328320
    329321        // Start timing
     
    350342            $shipping_method_id = $carrier->Id;
    351343        }
    352 
    353         // Create a cache key based on address and coordinates
    354 //        $cache_key = 'bpost_pickup_points_' . md5(json_encode([
    355 //                'address' => $sanitized_address,
    356 //                'carrier_id' => $shipping_method_id,
    357 //                'lat' => isset($sanitized_address['Lat']) ? $sanitized_address['Lat'] : 0,
    358 //                'lng' => isset($sanitized_address['Lng']) ? $sanitized_address['Lng'] : 0
    359 //            ]));
    360 //
    361 //        // Try to get cached results
    362 //        $cached_results = get_transient($cache_key);
    363 //        if ($cached_results !== false) {
    364 //            // Calculate execution time
    365 //            $end_time = microtime(true);
    366 //            $execution_time = ($end_time - $start_time) * 1000;
    367 //
    368 //            // Add timing information to response
    369 //            $cached_results->execution_time = round($execution_time, 2);
    370 //            $cached_results->execution_time_unit = 'ms';
    371 //            $cached_results->from_cache = true;
    372 //
    373 //            wp_send_json($cached_results);
    374 //            return;
    375 //        }
    376344
    377345        $pickup_points = BpostWoo::get_pickup_locations($address, $shipping_method_id);
     
    463431                continue;
    464432            }
    465            
     433
    466434            // Sanitize setting name and value
    467435            $setting_name = sanitize_text_field($setting['name']);
    468436            $setting_value = sanitize_text_field($setting['value']);
    469            
     437
    470438            // Validate setting name (only allow alphanumeric and underscore)
    471439            if (!preg_match('/^[a-zA-Z0-9_]+$/', $setting_name)) {
    472440                continue;
    473441            }
    474            
     442
    475443            $settings[$setting_name] = $setting_value;
    476444        }
     
    484452        $setting_name = 'wbs_' . absint($instance_id) . '_Bpost';
    485453        update_option($setting_name, $settings);
    486        
     454
    487455        wp_send_json_success(array(
    488456            'message' => 'Settings saved successfully',
     
    512480        $upload_dir = wp_upload_dir();
    513481        $bpost_dir = $upload_dir['basedir'] . '/bpost-shipping';
    514        
     482
    515483        // Only delete files if directory exists
    516484        if (file_exists($bpost_dir)) {
     
    589557                    // Add carrier ID initialization to the main script
    590558                    wp_add_inline_script('bpost-pickup-script', "jQuery(function(){ Bpost.platform.setCarrier(" . esc_js($carrier->Id) . "); });");
    591                    
     559
    592560                    $Bpost_options .= "</td></tr>";
    593561                }
     
    776744    /**
    777745     * Get the upload directory path for Bpost shipping files
    778      * 
     746     *
    779747     * @return string The path to the Bpost shipping files directory
    780748     */
     
    782750        $upload_dir = wp_upload_dir();
    783751        $bpost_dir = $upload_dir['basedir'] . '/bpost-shipping';
    784        
     752
    785753        // Create directory if it doesn't exist
    786754        if (!file_exists($bpost_dir)) {
    787755            wp_mkdir_p($bpost_dir);
    788756        }
    789        
     757
    790758        // Ensure directory is writable
    791759        if (!is_writable($bpost_dir)) {
     
    793761            return false;
    794762        }
    795        
     763
    796764        return $bpost_dir;
    797765    }
     
    800768        $class_name = $this->get_class_name_for_carrier($carrier) . 'Free';
    801769        $file_name = 'class-Bpost-shipping' . $class_name . '.php';
    802        
     770
    803771        // Get the upload directory path
    804772        $upload_dir = $this->get_shipping_files_dir();
     
    807775            return;
    808776        }
    809        
     777
    810778        $file_path = $upload_dir . '/' . $file_name;
    811779
     
    820788        $class_name = $this->get_class_name_for_carrier($carrier);
    821789        $file_name = 'class-Bpost-shipping' . $class_name . '.php';
    822        
     790
    823791        // Get the upload directory path
    824792        $upload_dir = $this->get_shipping_files_dir();
     
    827795            return;
    828796        }
    829        
     797
    830798        $file_path = $upload_dir . '/' . $file_name;
    831799
     
    840808        $class_name = $this->get_class_name_for_carrier($carrier).'Weight';
    841809        $weighbasedFile = 'class-Bpost-shipping' . $class_name . '-weight.php';
    842        
     810
    843811        // Get the upload directory path
    844812        $upload_dir = $this->get_shipping_files_dir();
     
    847815            return;
    848816        }
    849        
     817
    850818        $file_path = $upload_dir . '/' . $weighbasedFile;
    851819
  • bpost-shipping-platform/trunk/includes/class-woo-Bpost.php

    r3304764 r3306040  
    1616include_once (BPOST_PLUGIN_PATH.'includes/plugins/class-Bpost-connector.php');
    1717include_once (BPOST_PLUGIN_PATH.'includes/plugins/class-Bpost-marketplace.php');
    18 include_once BPOST_PLUGIN_PATH.'/includes/core/class-Bpost-rate-limiter.php';
    1918
    2019/**
     
    230229     */
    231230    public function handle_update_settings() {
     231        $respdata = new stdClass();
    232232
    233233        // Check if POST request has data
     
    238238            $data = json_decode($raw_data);
    239239
    240         }
    241     }
    242 
    243 
    244     private function get_request_signature()
    245     {
    246         $hmac256 = hash_hmac('sha256', get_option('Bpost_private_key'), true);
    247         return base64_encode($hmac256);
    248     }
    249 
    250     /**
    251      * Actions to perform after all plugins are loaded.
    252      */
    253     public function plugins_loaded() {
    254         $this->check_marketplaces();
    255         $this->load_plugin_textdomain();
    256     }
    257 
    258     /**
    259      * Check if marketplace plugins are active and include necessary files.
    260      */
    261     public function check_marketplaces() {
    262         global $Bpost_dokan,$Bpost_wcfm;
    263 
    264         $active_plugins =  apply_filters('active_plugins', get_option( 'active_plugins' ));
    265         if ( in_array( 'dokan-lite/dokan.php', $active_plugins )) {
    266             require_once(BPOST_PLUGIN_PATH . 'includes/plugins/class-Bpost-dokan.php');
    267         }
    268 
    269         if (in_array('wc-multivendor-marketplace/wc-multivendor-marketplace.php', $active_plugins)) {
    270             require_once(BPOST_PLUGIN_PATH . 'includes/plugins/class-Bpost-wcfm.php');
    271         }
    272     }
    273 
    274     /**
    275      * Handle plugin upgrade and call necessary functions.
    276      *
    277      * @param WP_Upgrader $upgrader_object
    278      * @param array $options
    279      */
    280     public function upgrade_function( $upgrader_object, $options ) {
    281         global $Bpost;
    282 
    283         $current_plugin_path_name = plugin_basename( __FILE__ );
    284 
    285         if ($options['action'] == 'update' && $options['type'] == 'plugin' ){
    286             if(isset($options['plugins'])){
    287                 foreach($options['plugins'] as $each_plugin){
    288                     if ($each_plugin == $current_plugin_path_name){
    289                         self::Bpost_check_upgrade();
    290                     }
    291                 }
    292             }
    293         }
    294     }
    295 
    296     /**
    297      * Load plugin text domain for translations.
    298      */
    299     public function load_plugin_textdomain() {
    300         global $Bpost;
    301 
    302         load_plugin_textdomain( 'Bpost-for-woocommerce', false, basename( dirname( __FILE__ ) ) . '/languages/' );
    303     }
    304 
    305     /**
    306      * Automatically export orders when the specified WooCommerce order status is reached.
    307      *
    308      * @param int $order_id
    309      */
    310     public function auto_export($order_id) {
    311         global $wpdb;
    312 
    313         error_log("Auto export order_id: $order_id ");
    314 
    315         $query = $wpdb->prepare("SELECT status FROM {$wpdb->prefix}Bpost WHERE id = %d", $order_id);
    316 
    317         // phpcs:ignore
    318         $exported = $wpdb->get_results($query);
    319 
    320         self::log("Exported " . var_export($exported,true));
    321 
    322         if (!$exported || ($exported[0]->status != BpostOrder::$STATUS_EXPORTED_SUCCESSFULLY) ) {
    323             BpostWooOrder::export(array($order_id));
    324         } else if( self::$is_dev) {
    325             self::log("order $order_id was already exported status is $exported[0]->status:  ignore");
    326         }
    327     }
    328 
    329     /**
    330      * Append filters to WooCommerce.
    331      */
    332     public function filters() {
    333         add_filter('woocommerce_order_details_after_order_table_items', array($this,'print_pickup_label'));
    334 
    335         /**
    336          * Add spanish special zones like canary islands
    337          */
    338         add_filter( 'woocommerce_states', array($this, 'add_states') );
    339 
    340         add_filter( 'woocommerce_package_rates', array( $this, 'rates_filter'), 10, 2 );
    341     }
    342 
    343     /**
    344      * Validate shipping rate.
    345      *
    346      * @param WC_Shipping_Rate $r
    347      * @param array $package
    348      * @return bool
    349      */
    350     public function is_rate_valid( $r , $package ) {
    351         $options = get_option( 'woocommerce_' . $r->method_id . '_' . $r->instance_id . '_settings' );
    352 
    353 
    354         // Check if `excludeclasses` exists
    355         if( isset( $options['excludeclasses'] ) && $options['excludeclasses'] ) {
    356             BpostWoo::log( $r->label );
    357             $opt_exclude_classes = explode( ',', $options['excludeclasses'] );
    358             $contains_classes_to_exclude = false;
    359 
    360             // Check if the package contains products that have at least one of the selected classes
    361             foreach ( $package['contents'] as $key => $item ) {
    362                 foreach ( $opt_exclude_classes as $c2exclude ) {
    363                     $terms = get_the_terms( $item['product_id'], 'product_shipping_class' );
    364                     if ( $terms ) {
    365                         foreach( $terms as $term ) {
    366                             $contains_classes_to_exclude |=  $term->term_id == $c2exclude;
    367                         }
    368                     }
    369                 }
    370             }
    371 
    372             BpostWoo::log("contains class " . ( $contains_classes_to_exclude ? 1 : 0 ));
    373             if ( $contains_classes_to_exclude ) {
    374                 return false; // Exclude if it contains the class
    375             }
    376         }
    377         // Check if `min_amount` is set and valid
    378         if (isset($options['requires']) && $options['requires'] == 'min_amount' &&  isset( $options['min_amount'] ) && !empty( $options['min_amount'] ) ) {
    379 
    380             $min_amount =  $options['min_amount']; // Convert string "2,00" to float
    381             $cart_subtotal = WC()->cart->get_subtotal();
    382 
    383             BpostWoo::log("Min amount: " . $min_amount . ", Cart subtotal: " . $cart_subtotal);
    384 
    385             if ( (int) $cart_subtotal < (int)$min_amount ) {
    386 
    387                 BpostWoo::log("Cart subtotal is below the minimum amount, excluding shipping method.");
    388                 return false; // Exclude if cart subtotal is less than the minimum amount
    389             }
    390         }
    391         if( isset( $options['max_amount'] ) && !empty( $options['max_amount'] ) ){
    392             $max_amount =  $options['max_amount'];
    393             $cart_subtotal = WC()->cart->get_subtotal();
    394 
    395             BpostWoo::log("Max amount: " . $max_amount . ", Cart subtotal: " . $cart_subtotal);
    396 
    397             if ( (int) $cart_subtotal >= (int)$max_amount ) {
    398 
    399                 BpostWoo::log("Cart subtotal is below the minimum amount, excluding shipping method.");
    400                 return false; // Exclude if cart subtotal is less than the minimum amount
    401             }
    402         }
    403 
    404         return true; // Shipping method is valid
    405     }
    406 
    407     /**
    408      * Filter and return valid shipping rates.
    409      *
    410      * @param array $rates
    411      * @param array $package
    412      * @return array
    413      */
    414     public function rates_filter ( $rates, $package ) {
    415 
    416         $free_not_local = false;
    417         if ( get_option('Bpost_hide_not_free') ) {
    418             $free = array();
    419             foreach ( $rates as $id => $r) {
    420                 if ( $r->cost == 0 && $this->is_rate_valid( $r, $package ) ) {
    421                     $free_not_local |= ($r->method_id != 'local_pickup');
    422                     $free[$id] = $r;
    423                 }
    424             }
    425 
    426             if ( !empty( $free ) && $free_not_local) {
    427                 $rates = $free;
    428             }
    429         }
    430 
    431         $newrates = array();
    432         foreach ( $rates as $id => $r) {
    433             if( $this->is_rate_valid($r, $package) ) {
    434                 $newrates[$id] = $r ;
    435             }
    436         }
    437 
    438         return $newrates;
    439     }
    440 
    441     /**
    442      * Add custom states to WooCommerce.
    443      *
    444      * @param array $states
    445      * @return array
    446      */
    447     public function add_states ($states) {
    448         if( !get_option('Bpost_provinces',false)){
    449             return $states;
    450         }
    451 
    452         foreach ( BpostWoo::$provinces as $country => $values){
    453             foreach ($values as $code => $name) {
    454                 $states[$country][$code] = esc_html($name);
    455             }
    456         }
    457         return $states;
    458     }
    459 
    460     /**
    461      * Parse custom query variables.
    462      *
    463      * @param WP $wp
    464      */
    465     public function parse_request( $wp ='' ) {
    466         if( !empty( $wp->query_vars['Bpost_update'] ) ) {
    467             $this->api_update();
    468         }
    469 
    470         if( !empty( $wp->query_vars['Bpost_create_account'] ) ) {
    471             $this->create_account();
    472         }
    473 
    474 //        if( !empty($wp->query_vars['Bpost_request_account'] ) && Bpost_is_marketplace() ) {
    475 //            BpostMarketplace::instance()->request_account();
    476 //        }
    477     }
    478 
    479     /**
    480      * Handle API update requests.
    481      */
    482     public function api_update() {
    483         // Set the response type to JSON
    484         header("Content-Type:application/json");
    485 
    486         // Define the statuses
    487         $statuses = [
    488             0 => '',
    489             1 => 'wc-pending',
    490             2 => 'wc-processing',
    491             3 => 'wc-on-hold',
    492             4 => 'wc-completed',
    493             5 => 'wc-cancelled',
    494             6 => 'wc-refunded',
    495             7 => 'wc-failed',
    496         ];
    497 
    498 
    499         // Check if POST request has data
    500         if ($_SERVER['REQUEST_METHOD'] === 'POST' && (!empty($_POST) || file_get_contents("php://input"))) {
    501 
    502             // Assume that 'data' field in POST contains the raw JSON data
    503             $raw_data = isset($_POST['data']) ? sanitize_text_field(wp_unslash($_POST['data'])) : file_get_contents("php://input");
    504 
    505             error_log("APIUPDATE");
    506 
    507             // If no content is present, return an error message
    508             if (!trim($raw_data)) {
    509                 die(wp_json_encode((object)array("Error" => "No content")));
    510             }
    511 
    512             // Decode the JSON data
    513             $data = json_decode($raw_data);
    514 
    515 
    516             // Trigger the action with the decoded data
    517             do_action('Bpost_api_update', $data);
    518 
    519             // Get callback URL and API instance
    520             $url = self::get_callback_url();
    521             $api = self::get_api();
    522 
    523             // Validate the update request
    524             if (!$api->validate_update_request($data->Status, $data->TrackingId, $url, $data->Hash)) {
    525                 self::log("RESTAURE!! API_UPDATE INVALID SIGNATURE IGNORING ");
    526                 die(wp_json_encode((object)array("Error" => "Invalid Signature")));
    527             }
    528 
    529             // Handle the 'getshippingmethods' action
    530             if (isset($data->Action) && sanitize_text_field($data->Action) == 'getshippingmethods') {
    531                 echo wp_kses(BpostShipping::get_shipping_methods());
    532                 die();
    533             }
     240            // Define the statuses
     241            $statuses = [
     242                0 => '',
     243                1 => 'wc-pending',
     244                2 => 'wc-processing',
     245                3 => 'wc-on-hold',
     246                4 => 'wc-completed',
     247                5 => 'wc-cancelled',
     248                6 => 'wc-refunded',
     249                7 => 'wc-failed',
     250            ];
    534251
    535252            // Check action and hash match
     
    540257                update_option('Bpost_hide_not_free', 0);
    541258                update_option('Bpost_export_virtual_products', 1);
    542                 $respdata = new stdClass();
    543259
    544260                // Prepare response data
     
    557273                die(wp_json_encode($respdata));
    558274            }
    559 
    560 
     275        }
     276    }
     277
     278
     279    private function get_request_signature()
     280    {
     281        $hmac256 = hash_hmac('sha256', get_option('Bpost_private_key'), true);
     282        return base64_encode($hmac256);
     283    }
     284
     285    /**
     286     * Actions to perform after all plugins are loaded.
     287     */
     288    public function plugins_loaded() {
     289        $this->check_marketplaces();
     290        $this->load_plugin_textdomain();
     291    }
     292
     293    /**
     294     * Check if marketplace plugins are active and include necessary files.
     295     */
     296    public function check_marketplaces() {
     297        global $Bpost_dokan,$Bpost_wcfm;
     298
     299        $active_plugins =  apply_filters('active_plugins', get_option( 'active_plugins' ));
     300        if ( in_array( 'dokan-lite/dokan.php', $active_plugins )) {
     301            require_once(BPOST_PLUGIN_PATH . 'includes/plugins/class-Bpost-dokan.php');
     302        }
     303
     304        if (in_array('wc-multivendor-marketplace/wc-multivendor-marketplace.php', $active_plugins)) {
     305            require_once(BPOST_PLUGIN_PATH . 'includes/plugins/class-Bpost-wcfm.php');
     306        }
     307    }
     308
     309    /**
     310     * Handle plugin upgrade and call necessary functions.
     311     *
     312     * @param WP_Upgrader $upgrader_object
     313     * @param array $options
     314     */
     315    public function upgrade_function( $upgrader_object, $options ) {
     316        global $Bpost;
     317
     318        $current_plugin_path_name = plugin_basename( __FILE__ );
     319
     320        if ($options['action'] == 'update' && $options['type'] == 'plugin' ){
     321            if(isset($options['plugins'])){
     322                foreach($options['plugins'] as $each_plugin){
     323                    if ($each_plugin == $current_plugin_path_name){
     324                        self::Bpost_check_upgrade();
     325                    }
     326                }
     327            }
     328        }
     329    }
     330
     331    /**
     332     * Load plugin text domain for translations.
     333     */
     334    public function load_plugin_textdomain() {
     335        global $Bpost;
     336
     337        load_plugin_textdomain( 'Bpost-for-woocommerce', false, basename( dirname( __FILE__ ) ) . '/languages/' );
     338    }
     339
     340    /**
     341     * Automatically export orders when the specified WooCommerce order status is reached.
     342     *
     343     * @param int $order_id
     344     */
     345    public function auto_export($order_id) {
     346        global $wpdb;
     347
     348        error_log("Auto export order_id: $order_id ");
     349
     350        $query = $wpdb->prepare("SELECT status FROM {$wpdb->prefix}Bpost WHERE id = %d", $order_id);
     351
     352        // phpcs:ignore
     353        $exported = $wpdb->get_results($query);
     354
     355        self::log("Exported " . var_export($exported,true));
     356
     357        if (!$exported || ($exported[0]->status != BpostOrder::$STATUS_EXPORTED_SUCCESSFULLY) ) {
     358            BpostWooOrder::export(array($order_id));
     359        } else if( self::$is_dev) {
     360            self::log("order $order_id was already exported status is $exported[0]->status:  ignore");
     361        }
     362    }
     363
     364    /**
     365     * Append filters to WooCommerce.
     366     */
     367    public function filters() {
     368        add_filter('woocommerce_order_details_after_order_table_items', array($this,'print_pickup_label'));
     369
     370        /**
     371         * Add spanish special zones like canary islands
     372         */
     373        add_filter( 'woocommerce_states', array($this, 'add_states') );
     374
     375        add_filter( 'woocommerce_package_rates', array( $this, 'rates_filter'), 10, 2 );
     376    }
     377
     378    /**
     379     * Validate shipping rate.
     380     *
     381     * @param WC_Shipping_Rate $r
     382     * @param array $package
     383     * @return bool
     384     */
     385    public function is_rate_valid( $r , $package ) {
     386        $options = get_option( 'woocommerce_' . $r->method_id . '_' . $r->instance_id . '_settings' );
     387
     388
     389        // Check if `excludeclasses` exists
     390        if( isset( $options['excludeclasses'] ) && $options['excludeclasses'] ) {
     391            BpostWoo::log( $r->label );
     392            $opt_exclude_classes = explode( ',', $options['excludeclasses'] );
     393            $contains_classes_to_exclude = false;
     394
     395            // Check if the package contains products that have at least one of the selected classes
     396            foreach ( $package['contents'] as $key => $item ) {
     397                foreach ( $opt_exclude_classes as $c2exclude ) {
     398                    $terms = get_the_terms( $item['product_id'], 'product_shipping_class' );
     399                    if ( $terms ) {
     400                        foreach( $terms as $term ) {
     401                            $contains_classes_to_exclude |=  $term->term_id == $c2exclude;
     402                        }
     403                    }
     404                }
     405            }
     406
     407            BpostWoo::log("contains class " . ( $contains_classes_to_exclude ? 1 : 0 ));
     408            if ( $contains_classes_to_exclude ) {
     409                return false; // Exclude if it contains the class
     410            }
     411        }
     412        // Check if `min_amount` is set and valid
     413        if (isset($options['requires']) && $options['requires'] == 'min_amount' &&  isset( $options['min_amount'] ) && !empty( $options['min_amount'] ) ) {
     414
     415            $min_amount =  $options['min_amount']; // Convert string "2,00" to float
     416            $cart_subtotal = WC()->cart->get_subtotal();
     417
     418            BpostWoo::log("Min amount: " . $min_amount . ", Cart subtotal: " . $cart_subtotal);
     419
     420            if ( (int) $cart_subtotal < (int)$min_amount ) {
     421
     422                BpostWoo::log("Cart subtotal is below the minimum amount, excluding shipping method.");
     423                return false; // Exclude if cart subtotal is less than the minimum amount
     424            }
     425        }
     426        if( isset( $options['max_amount'] ) && !empty( $options['max_amount'] ) ){
     427            $max_amount =  $options['max_amount'];
     428            $cart_subtotal = WC()->cart->get_subtotal();
     429
     430            BpostWoo::log("Max amount: " . $max_amount . ", Cart subtotal: " . $cart_subtotal);
     431
     432            if ( (int) $cart_subtotal >= (int)$max_amount ) {
     433
     434                BpostWoo::log("Cart subtotal is below the minimum amount, excluding shipping method.");
     435                return false; // Exclude if cart subtotal is less than the minimum amount
     436            }
     437        }
     438
     439        return true; // Shipping method is valid
     440    }
     441
     442    /**
     443     * Filter and return valid shipping rates.
     444     *
     445     * @param array $rates
     446     * @param array $package
     447     * @return array
     448     */
     449    public function rates_filter ( $rates, $package ) {
     450
     451        $free_not_local = false;
     452        if ( get_option('Bpost_hide_not_free') ) {
     453            $free = array();
     454            foreach ( $rates as $id => $r) {
     455                if ( $r->cost == 0 && $this->is_rate_valid( $r, $package ) ) {
     456                    $free_not_local |= ($r->method_id != 'local_pickup');
     457                    $free[$id] = $r;
     458                }
     459            }
     460
     461            if ( !empty( $free ) && $free_not_local) {
     462                $rates = $free;
     463            }
     464        }
     465
     466        $newrates = array();
     467        foreach ( $rates as $id => $r) {
     468            if( $this->is_rate_valid($r, $package) ) {
     469                $newrates[$id] = $r ;
     470            }
     471        }
     472
     473        return $newrates;
     474    }
     475
     476    /**
     477     * Add custom states to WooCommerce.
     478     *
     479     * @param array $states
     480     * @return array
     481     */
     482    public function add_states ($states) {
     483        if( !get_option('Bpost_provinces',false)){
     484            return $states;
     485        }
     486
     487        foreach ( BpostWoo::$provinces as $country => $values){
     488            foreach ($values as $code => $name) {
     489                $states[$country][$code] = esc_html($name);
     490            }
     491        }
     492        return $states;
     493    }
     494
     495    /**
     496     * Parse custom query variables.
     497     *
     498     * @param WP $wp
     499     */
     500    public function parse_request( $wp ='' ) {
     501        if( !empty( $wp->query_vars['Bpost_update'] ) ) {
     502            $this->api_update();
     503        }
     504
     505        if( !empty( $wp->query_vars['Bpost_create_account'] ) ) {
     506            $this->create_account();
     507        }
     508
     509//        if( !empty($wp->query_vars['Bpost_request_account'] ) && Bpost_is_marketplace() ) {
     510//            BpostMarketplace::instance()->request_account();
     511//        }
     512    }
     513
     514    /**
     515     * Handle API update requests.
     516     */
     517    public function api_update() {
     518        // Set the response type to JSON
     519        header("Content-Type:application/json");
     520
     521        // Check if POST request has data
     522        if ($_SERVER['REQUEST_METHOD'] === 'POST' && (!empty($_POST) || file_get_contents("php://input"))) {
     523
     524            // Assume that 'data' field in POST contains the raw JSON data
     525            $raw_data = isset($_POST['data']) ? sanitize_text_field(wp_unslash($_POST['data'])) : file_get_contents("php://input");
     526
     527            error_log("APIUPDATE");
     528
     529            // If no content is present, return an error message
     530            if (!trim($raw_data)) {
     531                die(wp_json_encode((object)array("Error" => "No content")));
     532            }
     533
     534            // Decode the JSON data
     535            $data = json_decode($raw_data);
     536
     537
     538            // Trigger the action with the decoded data
     539            do_action('Bpost_api_update', $data);
     540
     541            // Get callback URL and API instance
     542            $url = self::get_callback_url();
     543            $api = self::get_api();
     544
     545            // Validate the update request
     546            if (!$api->validate_update_request($data->Status, $data->TrackingId, $url, $data->Hash)) {
     547                self::log("RESTAURE!! API_UPDATE INVALID SIGNATURE IGNORING ");
     548                die(wp_json_encode((object)array("Error" => "Invalid Signature")));
     549            }
     550
     551            // Handle the 'getshippingmethods' action
     552            if (isset($data->Action) && sanitize_text_field($data->Action) == 'getshippingmethods') {
     553                echo wp_kses(BpostShipping::get_shipping_methods());
     554                die();
     555            }
    561556
    562557            // Handle the order update
     
    649644            wp_register_script('Bpost_script' , BPOST_PLUGIN_URL.'assets/js/Bpost.js', array ( 'jquery' ),'2.2',['in_footer' => true] );
    650645            wp_enqueue_script( 'Bpost_script');
    651            
    652             // Localize the script with new data
    653             wp_localize_script('Bpost_script', 'bpost_ajax', array(
    654                 'ajax_url' => admin_url('admin-ajax.php'),
    655                 'nonce' => wp_create_nonce('bpost-ajax-nonce')
    656             ));
    657            
    658646            wp_register_style( 'Bpost_style', BPOST_PLUGIN_URL.'assets/css/Bpost.css',[],'1.0.0' );
    659647            wp_register_style( 'checkout_style', BPOST_PLUGIN_URL.'assets/css/checkout.css',[],'1.0.0' );
     
    663651            wp_register_script('Bpost_connect' , BPOST_PLUGIN_URL.'assets/js/connect.js' ,[],'1.0.0',['in_footer' => true]);
    664652            wp_enqueue_script( 'Bpost_connect');
    665            
    666             // Localize the connect script as well
    667             wp_localize_script('Bpost_connect', 'bpost_connect_ajax', array(
    668                 'ajax_url' => admin_url('admin-ajax.php'),
    669                 'nonce' => wp_create_nonce('bpost-connect-nonce')
    670             ));
     653
    671654        }
    672655
     
    11321115        }
    11331116
    1134         if (!get_option(BpostWoo::$OPTION_BPOST_CACHE_KEY) && get_option(BpostShippingPlatform::$OPTION_BPOST_PUBLIC_KEY)) {
    1135             update_option(BpostWoo::$OPTION_BPOST_CACHE_KEY, sanitize_text_field(get_option(BpostShippingPlatform::$OPTION_BPOST_PUBLIC_KEY)));
    1136             update_option(BpostWoo::$OPTION_CALLBACK_URL, esc_url(BpostShippingPlatform::get_callback_url()));
     1117        if (!get_option(BpostWoo::$OPTION_BPOST_CACHE_KEY) && get_option(BpostWoo::$OPTION_BPOST_PUBLIC_KEY)) {
     1118            update_option(BpostWoo::$OPTION_BPOST_CACHE_KEY, sanitize_text_field(get_option(BpostWoo::$OPTION_BPOST_PUBLIC_KEY)));
     1119            update_option(BpostWoo::$OPTION_CALLBACK_URL, esc_url(BpostWoo::get_callback_url()));
    11371120        }
    11381121
  • bpost-shipping-platform/trunk/includes/core/class-Bpost-api-v3.php

    r3304764 r3306040  
    335335     */
    336336    public function get_pickup_locations($address, $carrier_id){
    337         if(!$carrier_id){
     337        if(!WC()->session->get('Bpost_selected_carrier')){
    338338            return array(
    339339                'Error' => array(
    340340                    'Id' => 1111,
    341                     'Info' => "Invalid carrier of id $carrier_id"
     341                    'Info' => "Invalid carrier of id " . WC()->session->get('Bpost_selected_carrier')
    342342                )
    343343            );
    344344        }
    345345
    346         if(is_numeric($address['Streetname2'])){
    347             $address['HouseNumber'] = $address['Streetname2'];
    348             $address['Streetname2'] ='';
    349         }
    350         $dataToSend = [
    351             "City" => $address['City'],
    352             "Country" => WC()->customer->get_shipping_country(),
    353             "PostalCode" => $address['PostalCode'],
    354             "Streetname1" => $address['Streetname1'],
    355             "Lat" => $address['Lat'],
    356             "Long" => $address['Long']
    357         ];
     346
     347        // If session Bpost_selected_carrier exists, use WC()->customer for address fields
     348        if (isset(WC()->session) && WC()->session->get('Bpost_selected_carrier')) {
     349            $dataToSend = [
     350                "City" => WC()->customer->get_shipping_city(),
     351                "Country" => WC()->customer->get_shipping_country(),
     352                "PostalCode" => WC()->customer->get_shipping_postcode(),
     353                "Streetname1" => WC()->customer->get_shipping_address_1(),
     354                "Lat" => isset($address['Lat']) ? $address['Lat'] : '',
     355                "Long" => isset($address['Long']) ? $address['Long'] : ''
     356            ];
     357        }
    358358
    359359        $lang = $this->get_ISO2_from_localisation(get_locale());
     
    361361        $data = array(
    362362            'Address' =>  $dataToSend,
    363             'CarrierId' => $carrier_id,
     363            'CarrierId' => WC()->session->get('Bpost_selected_carrier'),
    364364            'Language' => $lang === "nl" ? "nl" : "fr"
    365365        );
    366366
    367367        $this->log("get_pickup_locations Address " . var_export($address, true ) . "; 
    368             Carrier :" . $carrier_id );
     368            Carrier :" . WC()->session->get('Bpost_selected_carrier') );
    369369        $curl =  $this->send_to_api('POST','/pickuppoints', $data);
    370370        return $curl->response;
Note: See TracChangeset for help on using the changeset viewer.