You are here

public function UPSRateRequest::getRates in Commerce UPS 8.3

Fetch rates from the UPS API.

Parameters

\Drupal\commerce_shipping\Entity\ShipmentInterface $commerce_shipment: The commerce shipment.

\Drupal\commerce_shipping\Entity\ShippingMethodInterface $shipping_method: The shipping method.

Return value

array An array of ShippingRate objects.

Throws

\Exception Exception when required properties are missing.

Overrides UPSRateRequestInterface::getRates

File

src/UPSRateRequest.php, line 70

Class

UPSRateRequest
Class UPSRateRequest.

Namespace

Drupal\commerce_ups

Code

public function getRates(ShipmentInterface $commerce_shipment, ShippingMethodInterface $shipping_method) {
  $rates = [];
  try {
    $auth = $this
      ->getAuth();
  } catch (\Exception $e) {
    $this->logger
      ->error(new TranslatableMarkup('Unable to fetch authentication config for UPS. Please check your shipping method configuration.'));
    return [];
  }
  $request = new Rate($auth['access_key'], $auth['user_id'], $auth['password'], $this
    ->useIntegrationMode());
  try {
    $shipment = $this->upsShipment
      ->getShipment($commerce_shipment, $shipping_method
      ->getPlugin());

    // Enable negotiated rates, if enabled.
    if ($this
      ->getRateType()) {
      $rate_information = new RateInformation();
      $rate_information
        ->setNegotiatedRatesIndicator(TRUE);
      $rate_information
        ->setRateChartIndicator(FALSE);
      $shipment
        ->setRateInformation($rate_information);
    }

    // Shop Rates.
    $ups_rates = $request
      ->shopRates($shipment);
  } catch (\Exception $e) {
    $this->logger
      ->error($e
      ->getMessage());
    $ups_rates = [];
  }
  if (!empty($ups_rates->RatedShipment)) {
    foreach ($ups_rates->RatedShipment as $ups_rate) {
      $service_code = $ups_rate->Service
        ->getCode();

      // Only add the rate if this service is enabled.
      if (!in_array($service_code, $this->configuration['services'])) {
        continue;
      }

      // Use negotiated rates if they were returned.
      if ($this
        ->getRateType() && !empty($ups_rate->NegotiatedRates->NetSummaryCharges->GrandTotal->MonetaryValue)) {
        $cost = $ups_rate->NegotiatedRates->NetSummaryCharges->GrandTotal->MonetaryValue;
        $currency = $ups_rate->NegotiatedRates->NetSummaryCharges->GrandTotal->CurrencyCode;
      }
      else {
        $cost = $ups_rate->TotalCharges->MonetaryValue;
        $currency = $ups_rate->TotalCharges->CurrencyCode;
      }
      $price = new Price((string) $cost, $currency);
      $service_name = $ups_rate->Service
        ->getName();
      $rates[] = new ShippingRate([
        'shipping_method_id' => $shipping_method
          ->id(),
        'service' => new ShippingService($service_code, $service_name),
        'amount' => $price,
      ]);
    }
  }
  return $rates;
}