You are here

function commerce_ups_service_rate_order in Commerce UPS 7

Same name and namespace in other branches
  1. 7.2 commerce_ups.module \commerce_ups_service_rate_order()

Shipping service callback: returns a base price array for a shipping service calculated for the given order.

1 string reference to 'commerce_ups_service_rate_order'
commerce_ups_commerce_shipping_service_info in ./commerce_ups.module
Implements hook_commerce_shipping_service_info().

File

./commerce_ups.module, line 73

Code

function commerce_ups_service_rate_order($shipping_service, $order) {

  // First attempt to recover cached shipping rates for the current order.
  $rates = commerce_shipping_rates_cache_get('ups', $order, variable_get('commerce_ups_rates_timeout', 0));

  // If no rates were recovered from the cache or the cached rates are over one minute old...
  if (!$rates) {
    $rates = array();

    // Build the rate request for the current order. This returns XML.
    $rate_request_xml = commerce_ups_build_rate_request($order);

    // If we got a valid rate request object back...
    if ($rate_request_xml) {

      // Submit the API request to UPS.
      $response = commerce_ups_api_request($rate_request_xml, t('Requesting shipping rates for Order @order_number', array(
        '@order_number' => $order->order_number,
      )));
      if (!empty($response)) {

        // Parse the response to cache all requested rates for the current order.
        foreach ($response->RatedShipment as $rate) {

          // Extract the service name and price information from the rate object.
          $service_name = commerce_ups_commerce_shipping_service_name((string) $rate->Service->Code);
          $decimal = (string) $rate->TotalCharges->MonetaryValue;
          $currency_code = (string) $rate->TotalCharges->CurrencyCode;

          // Add an item to the rates array for the current service.
          $rates[$service_name] = array(
            'amount' => commerce_currency_decimal_to_amount($decimal, $currency_code),
            'currency_code' => $currency_code,
            'data' => array(),
          );
        }

        // Cache the calculated rates for subsequent requests.
        commerce_shipping_rates_cache_set('ups', $order, $rates);
      }
    }
  }

  // Return the rate for the requested service or FALSE if not found.
  return isset($rates[$shipping_service['name']]) ? $rates[$shipping_service['name']] : FALSE;
}