UPSRateRequest.php in Commerce UPS 8.3
File
src/UPSRateRequest.php
View source
<?php
namespace Drupal\commerce_ups;
use Drupal\commerce_price\Price;
use Drupal\commerce_shipping\Entity\ShipmentInterface;
use Drupal\commerce_shipping\Entity\ShippingMethodInterface;
use Drupal\commerce_shipping\ShippingRate;
use Drupal\commerce_shipping\ShippingService;
use Drupal\Core\Logger\LoggerChannelFactoryInterface;
use Drupal\Core\StringTranslation\TranslatableMarkup;
use Ups\Rate;
use Ups\Entity\RateInformation;
class UPSRateRequest extends UPSRequest implements UPSRateRequestInterface {
protected $configuration;
protected $upsShipment;
protected $logger;
public function __construct(UPSShipmentInterface $ups_shipment, LoggerChannelFactoryInterface $logger_factory) {
$this->upsShipment = $ups_shipment;
$this->logger = $logger_factory
->get(UPSRateRequestInterface::LOGGER_CHANNEL);
}
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());
if ($this
->getRateType()) {
$rate_information = new RateInformation();
$rate_information
->setNegotiatedRatesIndicator(TRUE);
$rate_information
->setRateChartIndicator(FALSE);
$shipment
->setRateInformation($rate_information);
}
$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();
if (!in_array($service_code, $this->configuration['services'])) {
continue;
}
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;
}
public function getRateType() {
return boolval($this->configuration['rate_options']['rate_type']);
}
}