Сделайте сообщение об ошибке на странице оформления заказа Magento (этап Способ доставки) - PullRequest
3 голосов
/ 19 января 2012

Я разработал модуль метода доставки Magento, и он отлично работает.Я могу получить список доступных способов доставки из моего удаленного сервиса, но я хочу получить сообщение об ошибке, если что-то не так с подключением к srvice или т. Д. Код класса оператора collectRates приведен ниже.

public function collectRates(Mage_Shipping_Model_Rate_Request $request) {
if (!$this->getConfigFlag('active')) {
  return false;
}

require_once Mage::getBaseDir() . '/app/code/local/Citymail/CitymailDeliveryOption/lib/syvo_service_connect.php';

$citymail_service_url = $this->getConfigData('service_url') . '/syvo_service';

$connection = new syvo_service_connect($citymail_service_url);
if($connection->connect()) {

  $handling = Mage::getStoreConfig('carriers/'.$this->_code.'/handling');
  $rate_result = Mage::getModel('shipping/rate_result');

  $product_qty = 0;
  $products_data = array();

  $currency = Mage::app()->getStore()->getCurrentCurrencyCode();

  $quote = Mage::getSingleton('checkout/session')->getQuote();
  foreach($quote->getAllVisibleItems() as $cartItem) {
    $product_qty += $cartItem->getQty();
    $products_data[$cartItem->getId()] = array(
      'length_units' => 'cm',
      'length' => 0,
      'width' => 0,
      'height' => 0,
      'weight_units' => 'kg',
      'weight' => $cartItem->getProduct()->getWeight(),
      'shippable' => 'a',
      'sell_price' => $cartItem->getProduct()->getPrice(),
      'currency' => $currency,
    );
  }

  $shipping_address = Mage::getModel('checkout/cart')->getQuote()->getShippingAddress();
  $password = md5($this->getConfigData('service_password'));
  $params = array(
     'passw=' . $password,
     'login=' . $this->getConfigData('service_login'),
     'action=get_shipping_options',
     'product_qty=' . $product_qty,
     'products_data=' . json_encode($products_data),
     'country=' . $shipping_address->getCountryId(),
     'postal_code=' . $shipping_address->getPostcode(),
   );


  $response = $connection->send(implode('&', $params), 0, 30);
  $response_status_line = $connection->getResponseStatusLine();
  if((int)$response_status_line[1] == 403) {
    //Access denied message
  }
  else {
    $response_array = json_decode($response);

    $citymail_service_points_data = array();
    if($response_array->syvo_service_responce->type == 'success') {
      $options = array();        
      foreach($response_array->syvo_service_responce->data->syvo_shipping_methods as $key_method => $shipping_method) {

        $method_key = 'opt--' . $shipping_method->type . '--' . $shipping_method->distributor;

        if($shipping_method->type == 'DHL_SERVICE_POINT') {
          $citymail_service_points_data['service_points'][$shipping_method->id] = array(
            'dhl_service_point_postcode' => $shipping_method->postcode,
            'dhl_service_point_address' => $shipping_method->address,
          );
          $method_key .= '--' . $shipping_method->id;
        }

        $method = Mage::getModel("shipping/rate_result_method");
        $method->setCarrier($this->_code);
        $method->setCarrierTitle(Mage::getStoreConfig('carriers/' . $this->_code . '/title'));
        $method->setMethod($method_key);
        $method->setMethodTitle($shipping_method->text);
        $method->setCost($shipping_method->rate);
        $method->setPrice($shipping_method->rate + $handling);
        $rate_result->append($method);
      }

      $street = $shipping_address->getStreet();
      $citymail_temporary_order_data = array(
        'login' => $this->getConfigData('service_login'),
        'password' => $password,
        'country_id' => $shipping_address->getCountryId(),
        'company_name' => $shipping_address->getCompany(),
        'name' => trim($shipping_address->getFirstname() . ' ' . $shipping_address->getLastname()),
        'postal_code' => $shipping_address->getPostcode(),
        'phone_number' => $shipping_address->getTelephone(),
        'email' => $shipping_address->getEmail(),
        'street' => $street[0],
        'city' => $shipping_address->getCity(),
        'matrix_id' => $response_array->syvo_service_responce->data->matrix_id,
        'service_url' => $citymail_service_url,
      );


      $citymail_temporary_order_data = $citymail_service_points_data + $citymail_temporary_order_data;
      Mage::getSingleton('core/session')->setCitymailTemporaryOrderData($citymail_temporary_order_data);


    }
    else {
      //Some error handler

      $error = Mage::getModel("shipping/rate_result_error");
      $error->setCarrier('citymaildeliveryoption');
      $error->setErrorMessage('sasasas');
      $rate_result->append($error);


    }
  }

}
else {

}


return $rate_result;
}

Этот код должен возвращать сообщение об ошибке, если модуль не может получить список методов доставки:

$error = Mage::getModel("shipping/rate_result_error");
$error->setCarrier('citymaildeliveryoption');
$error->setErrorMessage('sasasas');
$rate_result->append($error);

Но ошибка не отображается.Я проверил существующие (основные) модули Magento, которые тоже используют обработчики ошибок (модули Ups, Usps), и обработчики ошибок этих модулей также не работают, сообщение об ошибке не отображается.

Не могли бы вы посоветовать решениеэта проблема.

Спасибо!

1 Ответ

2 голосов
/ 10 апреля 2012

Ваш код хороший.Вам просто нужно немного настроить, чтобы ваш оператор всегда отображал его методы.

Показано в Mage_Shipping_Model_Shipping-> collectCarrierRates () (строка 176), Magento проверяет наличие «showmethod» в конфигурации вашего оператора, если в результате получаетсяпо ошибке (и отменить его, если он оценивается в 0):

if ($carrier->getConfigData('showmethod') == 0 && $result->getError()) {
    return $this;
}

Так что вам просто нужно добавить это в свой config.xml:

<?xml version="1.0" encoding="UTF-8"?>
<config>
    <default>
        <carriers>
            <citymaildeliveryoption>
                <showmethod>1</showmethod>
            </citymaildeliveryoption>
        </carriers>
    </default>
</config>
...