Стоимость доставки не работает


Редактировать

После того, как я использовал приведенный ниже ответ, теперь я получаю плату за доставку в приложении.

Но сейчас мы столкнулись с небольшой проблемой:

В зависимости от расстояния мы установили цену доставки,

Shipping A : less than 100 kms = 50 $ , 
shipping B : 100 to 200 kms     100 $ 
shipping c : 200 and above kms-  150 $

Теперь мы получаем только "стоимость доставки c" [150$] за все расстояния. до того, как мы правильно получили все сборы за доставку A, B, C на сайте.....

Редактировать Конец

App/code/local/company/extension/Model/Carrier/Localdelivery.php

<?php
class Webkul_Mpperproductshipping_Model_Carrier_LocalDelivery extends Mage_Shipping_Model_Carrier_Abstract
{
    /* Use group alias */
    protected $_code = 'mpperproductshipping';
    public function collectRates(Mage_Shipping_Model_Rate_Request $request){
        //skip if not enabled
        if (!Mage::getStoreConfig('carriers/'.$this->_code.'/active')||Mage::getStoreConfig('carriers/mp_multi_shipping/active')){
           return false;
        }

        $result = Mage::getModel('shipping/rate_result');
        $session = Mage::getSingleton('checkout/session');
        $postcode=$session->getQuote()->getShippingAddress()->getPostcode();
        $countrycode=$session->getQuote()->getShippingAddress()->getCountry();
        $postcode=str_replace('-', '', $postcode);
        $shippingdetail=array();
        $shippostaldetail=array('countrycode'=>$countrycode,'postalcode'=>$postcode);
        /****/
        foreach($session->getQuote()->getAllVisibleItems() as $item) {
            $proid=$item->getProductId();
            $options=$item->getProductOptions();
            $mpassignproductId=$options['info_buyRequest']['mpassignproduct_id'];
            if(!$mpassignproductId) {
                foreach($item->getOptions() as $option) {
                    $temp=unserialize($option['value']);
                    if($temp['mpassignproduct_id']) {
                        $mpassignproductId=$temp['mpassignproduct_id'];
                    }
                }
            }
            if($mpassignproductId) {
                $mpassignModel = Mage::getModel('mpassignproduct/mpassignproduct')->load($mpassignproductId);
                $partner = $mpassignModel->getSellerId();
            } else {
                $collection=Mage::getModel('marketplace/product')
                    ->getCollection()->addFieldToFilter('mageproductid',array('eq'=>$proid));
                foreach($collection as $temp) {
                    $partner=$temp->getUserid();
                }
            }

            $product=Mage::getModel('catalog/product')->load($proid)->getWeight();
            $weight=$product*$item->getQty();
            if(count($shippingdetail)==0){
                array_push($shippingdetail,array('seller_id'=>$partner,'items_weight'=>$weight,'product_name'=>$item->getName(),'qty'=>$item->getQty(),'item_id'=>$item->getId()));
            }else{
                $shipinfoflag=true;
                $index=0;
                foreach($shippingdetail as $itemship){
                    if($itemship['seller_id']==$partner){
                        $itemship['items_weight']=$itemship['items_weight']+$weight;
                        $itemship['product_name']=$itemship['product_name'].",".$item->getName();
                        $itemship['item_id']=$itemship['item_id'].",".$item->getId();
                        $itemship['qty']=$itemship['qty']+$item->getQty();
                        $shippingdetail[$index]=$itemship;
                        $shipinfoflag=false;
                    }
                    $index++;
                }
                if($shipinfoflag==true){
                    array_push($shippingdetail,array('seller_id'=>$partner,'items_weight'=>$weight,'product_name'=>$item->getName(),'qty'=>$item->getQty(),'item_id'=>$item->getId()));
                }
            }
        }
        $shippingpricedetail=$this->getShippingPricedetail($shippingdetail,$shippostaldetail);

        if($shippingpricedetail['errormsg']!==""){
            Mage::getSingleton('core/session')->setShippingCustomError($shippingpricedetail['errormsg']);
            return $result;
        }
        /*store shipping in session*/
        $shippingAll=Mage::getSingleton('core/session')->getData('shippinginfo');
        $shippingAll[$this->_code]=$shippingpricedetail['shippinginfo'];
        Mage::getSingleton('core/session')->setData('shippinginfo',$shippingAll);

        $method = Mage::getModel('shipping/rate_result_method');
        $method->setCarrier($this->_code);
        $method->setCarrierTitle(Mage::getStoreConfig('carriers/'.$this->_code.'/title'));
        /* Use method name */
        $method->setMethod($this->_code);
        $method->setMethodTitle(Mage::getStoreConfig('carriers/'.$this->_code.'/name'));
        $method->setCost($shippingpricedetail['handlingfee']);
        $method->setPrice($shippingpricedetail['handlingfee']); 
        $result->append($method);
        return $result; 
    }

     public function getShippingPricedetail($shippingdetail,$shippostaldetail) {
        $shippinginfo=array();
        $handling=0;
        $session = Mage::getSingleton('checkout/session');
        $customerAddress = $session->getQuote()->getShippingAddress();
        foreach($shippingdetail as $shipdetail) {
            $seller = Mage::getModel("customer/customer")->load($shipdetail['seller_id']);
            $sellerAddress = $seller->getPrimaryShippingAddress();
            $distance = $this->getDistanse($sellerAddress->getPostcode(),$customerAddress->getPostcode());
            $price = 0;
            $itemsarray=explode(',',$shipdetail['item_id']);
            foreach($session->getQuote()->getAllItems() as $item) {
                $proid=$item->getProductId();
                $options=$item->getProductOptions();
                $mpassignproductId=$options['info_buyRequest']['mpassignproduct_id'];
                if(!$mpassignproductId) {
                    foreach($item->getOptions() as $option) {
                        $temp=unserialize($option['value']);
                        if($temp['mpassignproduct_id']) {
                            $mpassignproductId=$temp['mpassignproduct_id'];
                        }
                    }
                }
                $mpshippingcharge = 0;
                $localDistance = Mage::getStoreConfig('marketplace/mpperproductshipping/local_shipping_distance');
                $regionalDistance = Mage::getStoreConfig('marketplace/mpperproductshipping/regional_shipping_distance');
                $stateDistance = Mage::getStoreConfig('marketplace/mpperproductshipping/state_shipping_distance');
                if(in_array($item->getId(),$itemsarray)) {
                    if($mpassignproductId) {
                        if($distance < $localDistance) {
                            $mpshippingcharge=Mage::getModel('mpassignproduct/mpassignproduct')->load($mpassignproductId)->getLocalShippingCharge();
                        } elseif($distance > $localDistance && $distance < $regionalDistance) {
                            $mpshippingcharge=Mage::getModel('mpassignproduct/mpassignproduct')->load($mpassignproductId)->getRegionalShippingCharge();
                        } elseif($distance > $regionalDistance) {
                            $mpshippingcharge=Mage::getModel('mpassignproduct/mpassignproduct')->load($mpassignproductId)->getStateShippingCharge();
                        }
                    } else {
                        if($distance < $localDistance) {
                            $mpshippingcharge=Mage::getModel('catalog/product')->load($item->getProductId())->getMpLocalShippingCharge();
                        } elseif($distance > $localDistance && $distance < $regionalDistance) {
                            $mpshippingcharge=Mage::getModel('catalog/product')->load($item->getProductId())->getMpRegionalShippingCharge();
                        } elseif($distance > $regionalDistance) {
                            $mpshippingcharge=Mage::getModel('catalog/product')->load($item->getProductId())->getMpStateShippingCharge();
                        }   
                    }
                    if(floatval($mpshippingcharge)==0){
                        $price=$price+floatval($this->getConfigData('defalt_ship_amount'));
                    }else{
                        $price=$price+$mpshippingcharge;
                    }
                }
            }

            $handling = $handling+$price;
            $submethod = array(array('method'=>Mage::getStoreConfig('carriers/'.$this->_code.'/title'),'cost'=>$price,'error'=>0));
            array_push($shippinginfo,array('seller_id'=>$shipdetail['seller_id'],'methodcode'=>$this->_code,'shipping_ammount'=>$price,'product_name'=>$shipdetail['product_name'],'submethod'=>$submethod,'item_ids'=>$shipdetail['item_id']));
        }
        $msg="";
        return array('handlingfee'=>$handling,'shippinginfo'=>$shippinginfo,'errormsg'=>$msg);
    }

    private function getDistanse($origin,$destination) {
        $url = "http://maps.googleapis.com/maps/api/distancematrix/json?origins=".$origin.",india&destinations=".$destination.",india&mode=driving&language=en-EN&sensor=false";
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_PROXYPORT, 3128);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
        $response = curl_exec($ch);
        curl_close($ch);
        $response_all = json_decode($response);
        $distance = $response_all->rows[0]->elements[0]->distance->value / 1000;
        return $distance;
    }
}

У нас есть торговая площадка с несколькими поставщиками/продавцами сайт. мы делаем приложение для Android для сайта....

Мы используем индивидуальный способ доставки на нашем сайте.

Этот способ доставки основан на "продавец" и "Покупатель" почтовый индекс код. мы сохраняем почтовый индекс продавца в бэкэнде. мы устанавливаем стоимость доставки в зависимости от расстояния в бэкэнде. Как только покупатель введет почтовый индекс в адрес доставки, он рассчитает стоимость доставки между продавцом и покупателем в зависимости от расстояния.

Это отлично работает на сайте.

Но в приложении для Android мы вызываем этот API, чтобы получить способы доставки: Список покупок()

Мы получаем способ доставки, но мы получаем стоимость доставки как ноль.

Выше я опубликовал код расширения, отвечающий за оплату доставки....

Author: Baby in Magento, 2015-12-21

1 answers

Проблема может быть связана с неправильным использованием данных котировок. Не создавайте экземпляр модели checkout/session в методе collectRates(), потому что он может начать новый сеанс при вызове метода API. Соберите данные адреса доставки клиента из объекта $request (экземпляр Mage_Shipping_Model_Rate_Request). Попробуйте эти методы вместо ваших:

  • $session->getQuote()->getShippingAddress()->getPostcode()
    заменить на
    $request->getDestPostcode()

  • $session->getQuote()->getShippingAddress()->getCountry()
    заменить на
    $request->getDestCountryId() или $request->getDestCountry()

  • $session->getQuote()->getAllVisibleItems()
    заменить на
    $request->getAllItems()

Проверьте, как он используется в Mage_Usa_Model_Shipping_Carrier_Dhl::collectRates().

РЕДАКТИРОВАТЬ

public function collectRates(Mage_Shipping_Model_Rate_Request $request){
        //skip if not enabled
        if (!Mage::getStoreConfig('carriers/'.$this->_code.'/active')||Mage::getStoreConfig('carriers/mp_multi_shipping/active')){
           return false;
        }

        $result = Mage::getModel('shipping/rate_result');

        /* Edited by martin_mageworx */
        $postcode=$request->getDestPostcode();
        $countrycode=$request->getDestCountry();
        $items=$request->getAllItems();
        /* End Editing by martin_mageworx */

        $postcode=str_replace('-', '', $postcode);
        $shippingdetail=array();
        $shippostaldetail=array('countrycode'=>$countrycode,'postalcode'=>$postcode,'items'=>$items);
        /****/
        foreach($items as $item) {
            $proid=$item->getProductId();
            $options=$item->getProductOptions();
            $mpassignproductId=$options['info_buyRequest']['mpassignproduct_id'];
            if(!$mpassignproductId) {
                foreach($item->getOptions() as $option) {
                    $temp=unserialize($option['value']);
                    if($temp['mpassignproduct_id']) {
                        $mpassignproductId=$temp['mpassignproduct_id'];
                    }
                }
            }
            if($mpassignproductId) {
                $mpassignModel = Mage::getModel('mpassignproduct/mpassignproduct')->load($mpassignproductId);
                $partner = $mpassignModel->getSellerId();
            } else {
                $collection=Mage::getModel('marketplace/product')
                    ->getCollection()->addFieldToFilter('mageproductid',array('eq'=>$proid));
                foreach($collection as $temp) {
                    $partner=$temp->getUserid();
                }
            }

            $product=Mage::getModel('catalog/product')->load($proid)->getWeight();
            $weight=$product*$item->getQty();
            if(count($shippingdetail)==0){
                array_push($shippingdetail,array('seller_id'=>$partner,'items_weight'=>$weight,'product_name'=>$item->getName(),'qty'=>$item->getQty(),'item_id'=>$item->getId()));
            }else{
                $shipinfoflag=true;
                $index=0;
                foreach($shippingdetail as $itemship){
                    if($itemship['seller_id']==$partner){
                        $itemship['items_weight']=$itemship['items_weight']+$weight;
                        $itemship['product_name']=$itemship['product_name'].",".$item->getName();
                        $itemship['item_id']=$itemship['item_id'].",".$item->getId();
                        $itemship['qty']=$itemship['qty']+$item->getQty();
                        $shippingdetail[$index]=$itemship;
                        $shipinfoflag=false;
                    }
                    $index++;
                }
                if($shipinfoflag==true){
                    array_push($shippingdetail,array('seller_id'=>$partner,'items_weight'=>$weight,'product_name'=>$item->getName(),'qty'=>$item->getQty(),'item_id'=>$item->getId()));
                }
            }
        }
        $shippingpricedetail=$this->getShippingPricedetail($shippingdetail,$shippostaldetail);

        if($shippingpricedetail['errormsg']!==""){
            Mage::getSingleton('core/session')->setShippingCustomError($shippingpricedetail['errormsg']);
            return $result;
        }
        /*store shipping in session*/
        $shippingAll=Mage::getSingleton('core/session')->getData('shippinginfo');
        $shippingAll[$this->_code]=$shippingpricedetail['shippinginfo'];
        Mage::getSingleton('core/session')->setData('shippinginfo',$shippingAll);

        $method = Mage::getModel('shipping/rate_result_method');
        $method->setCarrier($this->_code);
        $method->setCarrierTitle(Mage::getStoreConfig('carriers/'.$this->_code.'/title'));
        /* Use method name */
        $method->setMethod($this->_code);
        $method->setMethodTitle(Mage::getStoreConfig('carriers/'.$this->_code.'/name'));
        $method->setCost($shippingpricedetail['handlingfee']);
        $method->setPrice($shippingpricedetail['handlingfee']); 
        $result->append($method);
        return $result; 
    }

public function getShippingPricedetail($shippingdetail,$shippostaldetail) {
        $shippinginfo=array();
        $handling=0;
        $session = Mage::getSingleton('checkout/session');
        $customerAddress = $session->getQuote()->getShippingAddress();

        /* Edited by martin_mageworx */
        $customerPostCode = $shippostaldetail['postalcode'];
        $items = $shippostaldetail['items'];
        /* End Editing by martin_mageworx */

        foreach($shippingdetail as $shipdetail) {
            $seller = Mage::getModel("customer/customer")->load($shipdetail['seller_id']);
            $sellerAddress = $seller->getPrimaryShippingAddress();
            $distance = $this->getDistanse($sellerAddress->getPostcode(),$customerPostCode);
            $price = 0;
            $itemsarray=explode(',',$shipdetail['item_id']);
            foreach($items as $item) {
                $proid=$item->getProductId();
                $options=$item->getProductOptions();
                $mpassignproductId=$options['info_buyRequest']['mpassignproduct_id'];
                if(!$mpassignproductId) {
                    foreach($item->getOptions() as $option) {
                        $temp=unserialize($option['value']);
                        if($temp['mpassignproduct_id']) {
                            $mpassignproductId=$temp['mpassignproduct_id'];
                        }
                    }
                }
                $mpshippingcharge = 0;
                $localDistance = Mage::getStoreConfig('marketplace/mpperproductshipping/local_shipping_distance');
                $regionalDistance = Mage::getStoreConfig('marketplace/mpperproductshipping/regional_shipping_distance');
                $stateDistance = Mage::getStoreConfig('marketplace/mpperproductshipping/state_shipping_distance');
                if(in_array($item->getId(),$itemsarray)) {
                    if($mpassignproductId) {
                        if($distance < $localDistance) {
                            $mpshippingcharge=Mage::getModel('mpassignproduct/mpassignproduct')->load($mpassignproductId)->getLocalShippingCharge();
                        } elseif($distance > $localDistance && $distance < $regionalDistance) {
                            $mpshippingcharge=Mage::getModel('mpassignproduct/mpassignproduct')->load($mpassignproductId)->getRegionalShippingCharge();
                        } elseif($distance > $regionalDistance) {
                            $mpshippingcharge=Mage::getModel('mpassignproduct/mpassignproduct')->load($mpassignproductId)->getStateShippingCharge();
                        }
                    } else {
                        if($distance < $localDistance) {
                            $mpshippingcharge=Mage::getModel('catalog/product')->load($item->getProductId())->getMpLocalShippingCharge();
                        } elseif($distance > $localDistance && $distance < $regionalDistance) {
                            $mpshippingcharge=Mage::getModel('catalog/product')->load($item->getProductId())->getMpRegionalShippingCharge();
                        } elseif($distance > $regionalDistance) {
                            $mpshippingcharge=Mage::getModel('catalog/product')->load($item->getProductId())->getMpStateShippingCharge();
                        }   
                    }
                    if(floatval($mpshippingcharge)==0){
                        $price=$price+floatval($this->getConfigData('defalt_ship_amount'));
                    }else{
                        $price=$price+$mpshippingcharge;
                    }
                }
            }

            $handling = $handling+$price;
            $submethod = array(array('method'=>Mage::getStoreConfig('carriers/'.$this->_code.'/title'),'cost'=>$price,'error'=>0));
            array_push($shippinginfo,array('seller_id'=>$shipdetail['seller_id'],'methodcode'=>$this->_code,'shipping_ammount'=>$price,'product_name'=>$shipdetail['product_name'],'submethod'=>$submethod,'item_ids'=>$shipdetail['item_id']));
        }
        $msg="";
        return array('handlingfee'=>$handling,'shippinginfo'=>$shippinginfo,'errormsg'=>$msg);
    }
 5
Author: martin_mageworx, 2016-01-15 07:18:50