I am having a problem calculating delivery variants in WooCommerce. On the checkout page, I have a field in which the address is entered and using jQuery and a special api service, the city code is calculated. Next, a request is sent to my web service, which displays delivery options for the selected city.
Most often this happens without interruptions, but sometimes delivery options are not calculated for the same city. I traced what was happening in the calculate_shipping function of my shipping method, and it turns out that sometimes it gets called 2 times for reasons I don't understand. That is, they are called simultaneously and the first time a Null response is received for delivery options, and the next request produces the required options.
But WooCommerce only picks up the first Null response and displays a message that no options are available. If I refresh the page, the options are displayed correctly. I also noticed that the first time calculate_shipping is called for the city code that was before that, that is, before the address was changed.How to determine and fix the reason why calculate_shipping is called 2 times in some cases? Below is the code for my calculate_shipping method.
public function calculate_shipping( $package = array() ) {
$to_postcode = !empty($package['destination']['postcode']) ? $package['destination']['postcode'] : '000000';
$dimensions = $this->set_package($package);
$delivery_fias_code = $package['destination']['fias_code'];
$delivery_params = [
'aoguid' => $delivery_fias_code,
'postalcode' => empty($delivery_fias_code) ? $to_postcode : '000000',
'weight' => $dimensions['weight'],
'width' => $dimensions['width'],
'length' => $dimensions['length'],
'height' => $dimensions['height'],
'declared' => $package['cart_subtotal'],
'topay' => 0,
'showmode' => 0,
'owner_id' => 55688//get_option('wcopt_login')
];
$deliveryVariants = null;
$deliveryVariants = $this->get_delivery_variants($delivery_params);
if ($deliveryVariants)
$deliveryVariants = json_decode($deliveryVariants, 1);
if ($deliveryVariants != null) {
foreach ($deliveryVariants as $deliveryVariant) {
$this->add_rate(
array(
'id' => $deliveryVariant['Tariff_id'],
'label' => !($deliveryVariant['MinDays'] == $deliveryVariant['MaxDays']) ? $deliveryVariant['TariffName'] . ' (от ' . $deliveryVariant['MinDays'] . ' до ' . $deliveryVariant['MaxDays'] . ' дней)' : $deliveryVariant['TariffName'] . ' (' . $deliveryVariant['MinDays'] . ' дней)',
'cost' => $deliveryVariant['Cost'] + $deliveryVariant['Insurance'],
'package' => $package,
'meta_data' => array(
'tariff_id' => $deliveryVariant['Tariff_id'],
'DeliveryMode' => $deliveryVariant['DeliveryMode']
),
)
);
}
}
}