如何在Magento的添加购物车操作中设置送货地址并收取运费?

时间:2012-04-04 20:06:02

标签: php magento magento-1.5

我有一些产品只能卖给特定地区。所以我添加了一个javascript弹出窗口,询问用户的邮政编码,我点击了一个网络服务,确认我可以将这个项目卖给他们。

此外,在购物车页面上,我要求提供运输邮政编码,以便我可以计算正确的运费。

我想如果我已经要求用户提供他们的拉链,我会自动将其设置为添加到购物车,并使用适当的运费/方法显示它们。

我认为我可以简单地扩展购物车控制器的addAction来设置拉链并收取费率,但拉链似乎没有保存,我也无法收取费率。

这是我正在使用的功能:

public function addAction()
{
    $cart   = $this->_getCart();
    $params = $this->getRequest()->getParams();
    try {
        if (isset($params['qty'])) {
            $filter = new Zend_Filter_LocalizedToNormalized(
                array('locale' => Mage::app()->getLocale()->getLocaleCode())
            );
            $params['qty'] = $filter->filter($params['qty']);
        }

        $product = $this->_initProduct();
        $related = $this->getRequest()->getParam('related_product');

        /**
         * Check product availability
         */
        if (!$product) {
            $this->_goBack();
            return;
        }


        $cart->addProduct($product, $params);
        if (!empty($related)) {
            $cart->addProductsByIds(explode(',', $related));
        }

        if((isset($params['territory_value_submitted']) && !empty($params['territory_value_submitted']))) {
            $shipping_address = $cart->getQuote()->getShippingAddress();
            $billing_address = $cart->getQuote()->getBillingAddress();

            Mage::log('Current Zip: '.$shipping_address->getPostcode());
            Mage::log('New Zip: '.$params['territory_value_submitted']);

            if($shipping_address->getPostcode() != $params['territory_value_submitted']) {
                $region = '';
                // use web service to lookup coresponding state for this zip code
                $state_lookup_response = file_get_contents(WEB_SERVICE_URL.'?zip='.$params['territory_value_submitted'].'&field=state');
                if($state_lookup_response != '') {
                    $region = $state_lookup_response;
                }

                $shipping_address
                    ->setCountryId('')
                    ->setCity('')
                    ->setPostcode($params['territory_value_submitted'])
                    ->setRegion($region)
                    ->setRegionId('')
                    ->setCollectShippingRates(true)
                    ->save();

                Mage::log('Set Zip: '.$shipping_address->getPostalcode());

                $current_bill_zip = $billing_address->getPostcode();
                if(empty($current_bill_zip)) {
                    $billing_address
                        ->setCountryId('')
                        ->setCity('')
                        ->setPostcode($params['territory_value_submitted'])
                        ->setRegion($region)
                        ->setRegionId('')
                        ->save();
                }

                $ship_method = $shipping_address->getShippingMethod();
                if(empty($ship_method)) {
                    $shipping_address->collectShippingRates();

                    $rates = $shipping_address->getAllShippingRates();
                    Mage::log('Available Rate Count: '.count($rates));

                    //if a free shipping method exists, choose that as the default
                    if($this->_getQuote()->getShippingAddress()->getShippingRateByCode('productmatrix_Free_Shipping') !== false) {
                        $this->_getQuote()->getShippingAddress()->setShippingMethod('productmatrix_Free_Shipping');
                    }
                    //if a standard shipping method exists, choose that as the default
                    elseif($this->_getQuote()->getShippingAddress()->getShippingRateByCode('productmatrix_Standard_Delivery') !== false) {
                        $this->_getQuote()->getShippingAddress()->setShippingMethod('productmatrix_Standard_Delivery');
                    }
                    $shipping_address->save();
                }
                $cart->getQuote()->save();
            }
        }
        $cart->save();

        $this->_getSession()->setCartWasUpdated(true);

        /**
         * @todo remove wishlist observer processAddToCart
         */
        Mage::dispatchEvent('checkout_cart_add_product_complete',
            array('product' => $product, 'request' => $this->getRequest(), 'response' => $this->getResponse())
        );


        if (!$this->_getSession()->getNoCartRedirect(true)) {
            if (!$cart->getQuote()->getHasError()){
                $message = $this->__('%s was added to your shopping cart.', Mage::helper('core')->htmlEscape($product->getName()));
                $this->_getSession()->addSuccess($message);
            }
            $this->_goBack();
        }
    } catch (Mage_Core_Exception $e) {
        if ($this->_getSession()->getUseNotice(true)) {
            $this->_getSession()->addNotice($e->getMessage());
        } else {
            $messages = array_unique(explode("\n", $e->getMessage()));
            foreach ($messages as $message) {
                $this->_getSession()->addError($message);
            }
        }

        $url = $this->_getSession()->getRedirectUrl(true);
        if ($url) {
            $this->getResponse()->setRedirect($url);
        } else {
            $this->_redirectReferer(Mage::helper('checkout/cart')->getCartUrl());
        }
    } catch (Exception $e) {
        $this->_getSession()->addException($e, $this->__('Cannot add the item to shopping cart.'));
        Mage::logException($e);
        $this->_goBack();
    }
}

更奇怪的是,当我在同一会话中多次执行该过程时,记录的内容会发生变化。

以下是将同一产品添加到购物车3次的日志,始终使用10001的邮政编码:

2012-04-04T19:58:20+00:00 DEBUG (7): Current Zip:
2012-04-04T19:58:20+00:00 DEBUG (7): New Zip: 10001
2012-04-04T19:58:20+00:00 DEBUG (7): Set Zip:
2012-04-04T19:58:20+00:00 DEBUG (7): Available Rate Count: 0
2012-04-04T19:58:36+00:00 DEBUG (7): Current Zip:
2012-04-04T19:58:36+00:00 DEBUG (7): New Zip: 10001
2012-04-04T19:58:36+00:00 DEBUG (7): Set Zip:
2012-04-04T19:58:36+00:00 DEBUG (7): Available Rate Count: 0
2012-04-04T19:59:00+00:00 DEBUG (7): Current Zip: 10001
2012-04-04T19:59:00+00:00 DEBUG (7): New Zip: 10001

请注意,第二个添加中的Set Zip为空,但Current Zip不适用于第三个添加。并且第3次添加不会尝试收取运费,因为新的zip与当前的zip相同。

是否有人知道是什么阻止数据被正确加载或保存?

1 个答案:

答案 0 :(得分:0)

解决方案是添加我在CartController::indexAction函数中找到的函数调用。

$cart->init();会将购物车状态设置为CHECKOUT_STATE_BEGIN并清除所有相关地址。因此需要在获取地址对象之前调用它。

如:

if((isset($params['territory_value_submitted']) && !empty($params['territory_value_submitted']))) {
        $cart->init();

        $shipping_address = $cart->getQuote()->getShippingAddress();
        $billing_address = $cart->getQuote()->getBillingAddress();

现在,购物车页面上的$cart->init()不会清除对地址所做的更改。

此外,如果没有为送货地址设置CountryId,则无法选择正确的送货方式。由于我只在美国境内发货,因此我的所有运输规则仅限于美国,未找到匹配规则。

通过更改

解决了这个问题
$shipping_address
    ->setCountryId('')

$shipping_address
    ->setCountryId('US')