UPS运费

时间:2012-12-13 08:16:11

标签: magento shipping

我想将运费与我的自定义运输模块集成,因此我需要从ups& amp;通过一些计算在我的模块上使用它。请帮我从ups到我的自定义模块获取费率。 感谢

2 个答案:

答案 0 :(得分:1)

Magento处理Mage_Usa_Model_Shipping_Carrier_Ups中的UPS API请求。不幸的是,该类没有任何公共方法来请求运费而不在请求中不传递报价对象。

如果您有报价对象,则可以实例化Mage_Usa_Model_Shipping_Carrier_Ups并通过调用collectRates()来请求费率。

如果没有引号对象,则必须扩展该类或编写自己的用于处理UPS API的类。

请在我的自定义类下面找到适用于Magento配置的

Module_Name_Helper_Data extends Mage_Core_Helper_Abstract
{

    public function getUpsRates($parcel, $destination)
    {    
        $xmlRequest = "";

        $shipToPostalCode  = $destination['postal_code'];
        $shipToCountryCode = $destination['dest_country_id'];
        $shipToRegionCode  = '';

        $weight = $parcel['weight'];
        $length = $parcel['length'];
        $height = $parcel['height'];
        $width  = $parcel['width'];

        $url = Mage::getStoreConfig('carriers/ups/gateway_xml_url');

        if (!$url) {
            $url = 'https://onlinetools.ups.com/ups.app/xml/Rate';
        }

        $userid         = Mage::getStoreConfig('carriers/ups/username');
        $userid_pass    = Mage::getStoreConfig('carriers/ups/password');
        $access_key     = Mage::getStoreConfig('carriers/ups/access_license_number');
        $shipper        = Mage::getStoreConfig('carriers/ups/shipper_number');

        $shipperCity          = Mage::getStoreConfig('shipping/origin/city');
        $shipperPostalCode    = Mage::getStoreConfig('shipping/origin/postcode');
        $shipperCountryCode   = Mage::getStoreConfig('shipping/origin/country_id');
        $shipperStateProvince = Mage::getStoreConfig('shipping/origin/region_id');

        $shipperStateProvince = Mage::getStoreConfig(Mage_Shipping_Model_Shipping::XML_PATH_STORE_REGION_ID, Mage::app()->getStore()->getStoreId());

        if (is_numeric($shipperStateProvince)) {
            $shipperStateProvince = Mage::getModel('directory/region')->load($shipperStateProvince)->getCode();
        }

        $xmlRequest =  <<<XMLRequest
      <?xml version="1.0"?>
        <AccessRequest xml:lang="en-US">
        <AccessLicenseNumber>$access_key</AccessLicenseNumber>
        <UserId>$userid</UserId>
        <Password>$userid_pass</Password>
      </AccessRequest>
      <?xml version="1.0"?>
        <RatingServiceSelectionRequest xml:lang="en-US">
          <Request>
            <TransactionReference>
              <CustomerContext>Rating and Service</CustomerContext>
              <XpciVersion>1.0</XpciVersion>
            </TransactionReference>
            <RequestAction>Rate</RequestAction>
            <RequestOption>Shop</RequestOption>
          </Request>
          <PickupType>
            <Code>03</Code>
            <Description>Customer Counter</Description>
          </PickupType>
          <Shipment>
            <Shipper>
              <ShipperNumber>{$shipper}</ShipperNumber>
              <Address>
                <City>{$shipperCity}</City>
                <PostalCode>{$shipperPostalCode}</PostalCode>
                <CountryCode>{$shipperCountryCode}</CountryCode>
                <StateProvinceCode>{$shipperStateProvince}</StateProvinceCode>
              </Address>
            </Shipper>
            <ShipTo>
              <Address>
                <PostalCode>{$shipToPostalCode}</PostalCode>
                <CountryCode>{$shipToCountryCode}</CountryCode>
                <ResidentialAddress>01</ResidentialAddress>
                <StateProvinceCode>{$shipToRegionCode}</StateProvinceCode>
                <ResidentialAddressIndicator>01</ResidentialAddressIndicator>
              </Address>
            </ShipTo>
            <ShipFrom>
              <Address>
                <PostalCode>{$shipperPostalCode}</PostalCode>
                <CountryCode>{$shipperCountryCode}</CountryCode>
                <StateProvinceCode>{$shipperStateProvince}</StateProvinceCode>
              </Address>
            </ShipFrom>
            <TaxInformationIndicator/>
            <Package>
              <PackagingType><Code>00</Code></PackagingType>
              <Dimensions>  
                <UnitOfMeasurement>  
                  <Code>IN</Code>  
                </UnitOfMeasurement>  
                <Length>{$length}</Length>  
                <Width>{$width}</Width>  
                <Height>{$height}</Height>  
              </Dimensions> 
              <PackageWeight>
                <UnitOfMeasurement><Code>LBS</Code></UnitOfMeasurement>
                <Weight>{$weight}</Weight>
              </PackageWeight>
            </Package>
            <RateInformation>
              <NegotiatedRatesIndicator/>
            </RateInformation>
          </Shipment>
        </RatingServiceSelectionRequest>
XMLRequest;

    $debugData = '';

    try {
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_HEADER, 0);
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $xmlRequest);
        curl_setopt($ch, CURLOPT_TIMEOUT, 30);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, Mage::getStoreConfig('carriers/ups/verify_peer'));
        $xmlResponse = curl_exec ($ch);
    }
    catch (Exception $e) {
        $xmlResponse = '';
    }

    return $this->_formatUpsRates($xmlResponse);
  }

格式化回复

  protected function _formatUpsRates($xmlResponse)
  {
        $priceArr = array();

        $ups = new Mage_Usa_Model_Shipping_Carrier_Ups();
        $methods = $ups->getAllowedMethods();

        if (strlen(trim($xmlResponse)) > 0) {

            $xml = new Varien_Simplexml_Config();
            $xml->loadString($xmlResponse);

            $arr = $xml->getXpath("//RatingServiceSelectionResponse/Response/ResponseStatusCode/text()");

            $success = (int)$arr[0];

            if ($success === 1) {

                $arr               = $xml->getXpath("//RatingServiceSelectionResponse/RatedShipment");
                $allowedMethods    = explode(",", Mage::getStoreConfig('carriers/ups/allowed_methods'));
                $negotiatedArr     = $xml->getXpath("//RatingServiceSelectionResponse/RatedShipment/NegotiatedRates");
                $negotiatedActive  = (Mage::getStoreConfig('carriers/ups/negotiated_active') && !empty($negotiatedArr)) ? 1 : 0;
                $allowedCurrencies = Mage::getModel('directory/currency')->getConfigAllowCurrencies();

                foreach ($arr as $shipElement) {

                    $code = (string) $shipElement->Service->Code;

                    if (in_array($code, $allowedMethods)) {

                        if ($negotiatedActive) {
                            $cost = $shipElement->NegotiatedRates->NetSummaryCharges->GrandTotal->MonetaryValue;
                        } else {
                            $cost = $shipElement->TotalCharges->MonetaryValue;
                        }

                        //convert price with Origin country currency code to base currency code
                        $successConversion = true;
                        $responseCurrencyCode = (string) $shipElement->TotalCharges->CurrencyCode;

                        if ($responseCurrencyCode) {
                            if (in_array($responseCurrencyCode, $allowedCurrencies)) {
                                $cost = (float) $cost * $this->_getBaseCurrencyRate($responseCurrencyCode);
                            }
                        }

                        $priceArr[$code] = $cost;
                    }
                }
            }
        }

        $shippingMethods = array();

        foreach ($priceArr as $method => $price) {
            $shippingMethods[] = array(
              'code' => $method,
              'name' => $methods[$method],
              'price' => $price);
        }

        return $shippingMethods;
    }

获取货币汇率

  protected function _getBaseCurrencyRate($code, $responseCurrencyCode)
  {
      if (!$this->_baseCurrencyRate) {
          $this->_baseCurrencyRate = Mage::getModel('directory/currency')
              ->load($code)
              ->getAnyRate('USD');
      }

      return $this->_baseCurrencyRate;
  }

如果您希望重写费率,可以执行以下操作

class Module_Name_Model_Ship extends Mage_Shipping_Model_Carrier_Abstract implements Mage_Shipping_Model_Carrier_Interface
{
    public function collectRates(Mage_Shipping_Model_Rate_Request $request)
    {
        // your custom code
        // parent::collectRates($request);

    }

答案 1 :(得分:0)

查看UPS API以获取运费。