public function getRate($PostalCode, $dest_zip, $dest_country_code, $service, $weight, $length = 0, $width = 0, $height = 0) { $setting = new Cart66Setting(); $home_country = explode('~', Cart66Setting::getValue('home_country')); $countryCode = array_shift($home_country); $pickupCode = Cart66Setting::getValue('fedex_pickup_code') ? Cart66Setting::getValue('fedex_pickup_code') : "REGULAR_PICKUP"; $residential = Cart66Setting::getValue('fedex_only_ship_commercial') ? "0" : "1"; $locationType = Cart66Setting::getValue('fedex_location_type') == 'commercial' ? "0" : "1"; if ($this->credentials != 1) { print 'Please set your credentials with the setCredentials function'; die; } $path_to_wsdl = CART66_PATH . "/pro/models/RateService_v14.wsdl"; ini_set("soap.wsdl_cache_enabled", "0"); $client = new SoapClient($path_to_wsdl, array('trace' => 1)); // Refer to http://us3.php.net/manual/en/ref.soap.php for more information $request['WebAuthenticationDetail'] = array('UserCredential' => array('Key' => $this->developerKey, 'Password' => $this->password)); $request['ClientDetail'] = array('AccountNumber' => $this->accountNumber, 'MeterNumber' => $this->meterNumber); $request['TransactionDetail'] = array('CustomerTransactionId' => ' *** Rate Available Services Request v14 using PHP ***'); $request['Version'] = array('ServiceId' => 'crs', 'Major' => '14', 'Intermediate' => '0', 'Minor' => '0'); $request['ReturnTransitAndCommit'] = true; $request['RequestedShipment']['DropoffType'] = $pickupCode; // valid values REGULAR_PICKUP, REQUEST_COURIER, ... $request['RequestedShipment']['ShipTimestamp'] = date('c'); // Service Type and Packaging Type are not passed in the request $request['RequestedShipment']['Shipper'] = array('Address' => array('PostalCode' => $this->fromZip, 'CountryCode' => $countryCode, 'Residential' => $locationType)); $request['RequestedShipment']['Recipient'] = array('Address' => array('PostalCode' => $dest_zip, 'CountryCode' => $dest_country_code, 'Residential' => $residential)); $request['RequestedShipment']['ShippingChargesPayment'] = array('PaymentType' => 'SENDER', 'Payor' => array('ResponsibleParty' => array('AccountNumber' => $this->accountNumber, 'Contact' => null, 'Address' => array('CountryCode' => $countryCode)))); $request['RequestedShipment']['RateRequestTypes'] = 'ACCOUNT'; $request['RequestedShipment']['RateRequestTypes'] = 'LIST'; $request['RequestedShipment']['PackageCount'] = $this->getPackageCount(); $request['RequestedShipment']['RequestedPackageLineItems'] = $this->getRequestedPackageLineItems($weight); try { $client->__setLocation('https://gateway.fedex.com:443/web-services'); $response = $client->getRates($request); if ($response->HighestSeverity != 'FAILURE' && $response->HighestSeverity != 'ERROR') { $rate = array(); if (is_array($response->RateReplyDetails)) { foreach ($response->RateReplyDetails as $rateReply) { $serviceType = $rateReply->ServiceType; $amount = $rateReply->RatedShipmentDetails[0]->ShipmentRateDetail->TotalNetCharge->Amount; $rate[] = array('name' => $serviceType, 'rate' => $amount); } } else { $serviceType = $response->RateReplyDetails->ServiceType; $amount = $response->RateReplyDetails->RatedShipmentDetails[0]->ShipmentRateDetail->TotalNetCharge->Amount; $rate[] = array('name' => $serviceType, 'rate' => $amount); } } else { $rate = false; Cart66Common::log('[' . basename(__FILE__) . ' - line ' . __LINE__ . "] Error: " . print_r($response->Notifications, true)); } } catch (SoapFault $exception) { $this->printFault($exception, $client); Cart66Common::log('[' . basename(__FILE__) . ' - line ' . __LINE__ . "] FedEx Error|| Code: " . $exception->faultcode . " Message: " . $exception->faultstring); Cart66Common::log('[' . basename(__FILE__) . ' - line ' . __LINE__ . "] Client Details: " . print_r($client, true)); $rate = false; } return $rate; }
protected function _getQuotes() { $r = $this->_request; $request = array('WebAuthenticationDetail' => array('UserCredential' => array('Key' => $r->key, 'Password' => $r->password)), 'ClientDetail' => array('AccountNumber' => $r->accountNumber, 'MeterNumber' => $r->meterNumber), 'Version' => array('ServiceId' => 'crs', 'Major' => '10', 'Intermediate' => '0', 'Minor' => '0'), 'RequestedShipment' => array('DropoffType' => $r->dropoffType, 'ShipTimestamp' => date('c'), 'PackagingType' => $r->packaging, 'TotalInsuredValue' => array('Ammount' => $r->value, 'Currency' => $r->currencyCode), 'Shipper' => array('Address' => array('PostalCode' => $r->originPostalCode, 'CountryCode' => $r->originCountryCode)), 'Recipient' => array('Address' => array('PostalCode' => $r->destPostalCode, 'CountryCode' => $r->destCountryCode, 'Residential' => (bool) $this->_config->residenceDelivery)), 'ShippingChargesPayment' => array('PaymentType' => 'SENDER', 'Payor' => array('AccountNumber' => $r->accountNumber, 'CountryCode' => $r->originCountryCode)), 'RateRequestTypes' => 'LIST', 'PackageCount' => '1', 'PackageDetail' => 'INDIVIDUAL_PACKAGES', 'RequestedPackageLineItems' => array(array('GroupPackageCount' => 1, 'Weight' => array('Value' => $r->weight, 'Units' => 'LB'))))); $pathToWsdl = Axis::config('system/path') . "/app/code/Axis/ShippingFedex/etc/RateService_v10.wsdl"; $client = new SoapClient($pathToWsdl); // production : https://gateway.fedex.com:443/GatewayDC // test : https://wsbeta.fedex.com:443/web-services $client->__setLocation($this->_config->gateway); $response = $client->getRates($request); return $this->_parseResponse($response); }
function quote($data, $config) { if ($config["test_mode"] == 'true') { $wsdl = PATH_THIRD . "brilliant_retail/core/shipping/assets/fedex/wsdl/RateService_v13_test.wsdl"; } else { $wsdl = PATH_THIRD . "brilliant_retail/core/shipping/assets/fedex/wsdl/RateService_v13.wsdl"; } $client = new SoapClient($wsdl, array('trace' => 1)); // Refer to http://us3.php.net/manual/en/ref.soap.php for more information // Need at least 1 for the weight if ($data["weight"] < 1) { $data["weight"] = 1; } $request['WebAuthenticationDetail'] = array('UserCredential' => array('Key' => $config["fedex_key"], 'Password' => $config["fedex_password"])); $request['ClientDetail'] = array('AccountNumber' => $config["fedex_account"], 'MeterNumber' => $config["fedex_meter"]); $request['TransactionDetail'] = array('CustomerTransactionId' => ' *** Rate Request v13 using BrilliantRetail ***'); $request['Version'] = array('ServiceId' => 'crs', 'Major' => '13', 'Intermediate' => '0', 'Minor' => '0'); $request['ReturnTransitAndCommit'] = true; $request['RequestedShipment']['DropoffType'] = 'REGULAR_PICKUP'; $request['RequestedShipment']['ShipTimestamp'] = date('c'); $request['RequestedShipment']['PackagingType'] = 'YOUR_PACKAGING'; $request['RequestedShipment']['TotalInsuredValue'] = array('Ammount' => $data["total"], 'Currency' => 'USD'); // Shipper Info $request['RequestedShipment']['Shipper'] = array('Contact' => array('PersonName' => '', 'CompanyName' => '', 'PhoneNumber' => ''), 'Address' => array('StreetLines' => array(''), 'City' => '', 'StateOrProvinceCode' => $config["from_state"], 'PostalCode' => $config["from_zip"], 'CountryCode' => $config["from_country"])); // Recipient Info $request['RequestedShipment']['Recipient'] = array('Contact' => array('PersonName' => '', 'CompanyName' => '', 'PhoneNumber' => ''), 'Address' => array('StreetLines' => array(), 'City' => '', 'StateOrProvinceCode' => substr($data["to_state"], 0, 2), 'PostalCode' => $data["to_zip"], 'CountryCode' => $data["to_country"], 'Residential' => true)); $request['RequestedShipment']['RateRequestTypes'] = 'LIST'; $request['RequestedShipment']['PackageCount'] = '1'; $request['RequestedShipment']['RequestedPackageLineItems'] = $packageLineItem = array('SequenceNumber' => 1, 'GroupPackageCount' => 1, 'Weight' => array('Value' => $data["weight"], 'Units' => strtoupper($config["weight_unit"])), 'Dimensions' => array('Length' => (int) $config["size_length"], 'Width' => (int) $config["size_width"], 'Height' => (int) $config["size_height"], 'Units' => 'IN')); $code = unserialize($config["code"]); $this->rates = array(); foreach ($code as $c) { $request['RequestedShipment']['ServiceType'] = $c; try { if (setEndpoint('changeEndpoint')) { $newLocation = $client->__setLocation(setEndpoint('endpoint')); } $response = $client->getRates($request); if ($response->HighestSeverity != 'FAILURE' && $response->HighestSeverity != 'ERROR') { $rateReply = $response->RateReplyDetails; $this->rates[$c] = array('code' => $c, 'rate' => number_format($rateReply->RatedShipmentDetails[0]->ShipmentRateDetail->TotalNetCharge->Amount, 2), 'label' => ucwords(strtolower(str_replace("_", " ", $rateReply->ServiceType)))); } } catch (SoapFault $exception) { printFault($exception, $client); } } if (count($this->rates) > 1) { usort($this->rates, array($this, '_rate_sort')); } return $this->rates; }
/** * Send transaction * * @return void */ public function send() { $this->request['RequestedShipment']['RequestedPackageLineItems'] = ['SequenceNumber' => 1, 'GroupPackageCount' => 1, 'Weight' => $this->weight]; if (null !== $this->dimensions['Length'] && null !== $this->dimensions['Width'] && null !== $this->dimensions['Height']) { $this->request['RequestedShipment']['RequestedPackageLineItems']['Dimensions'] = $this->dimensions; } $this->response = $this->client->getRates($this->request); $this->responseCode = (int) $this->response->Notifications->Code; $this->responseMessage = (string) $this->response->Notifications->Message; if ($this->responseCode == 0) { foreach ($this->response->RateReplyDetails as $rate) { $this->rates[self::$services[(string) $rate->ServiceType]] = number_format((string) $rate->RatedShipmentDetails[0]->ShipmentRateDetail->TotalNetCharge->Amount, 2); } $this->rates = array_reverse($this->rates, true); } }
function getRates(array $from, array $to, array $packages) { if (!class_exists('SoapClient')) { return array(); } $wsdl = dirname(__FILE__) . '/FedEx_v8.wsdl'; $args = array(); $request = $this->getRequest($from, $to, $packages); try { $client = new SoapClient($wsdl, $args); $response = $client->getRates($request); $options = $response->RateReplyDetails; $out = $this->extractRates($options); return $out; } catch (SoapFault $e) { return array(); } }
/** * Request shipping rates * * @return void */ public function send() { $this->requestHeader['Version'] = ['ServiceId' => 'crs', 'Major' => '18', 'Intermediate' => '0', 'Minor' => '0']; $request['RequestedShipment'] = ['RateRequestTypes' => 'ACCOUNT', 'RateRequestTypes' => 'LIST', 'PackageCount' => count($this->packages), 'Shipper' => $this->shipFrom, 'Recipient' => $this->shipTo, 'RequestedPackageLineItems' => []]; foreach ($this->packages as $package) { $request['RequestedShipment']['RequestedPackageLineItems'][] = $package->rateRequest(); } $request = array_merge($this->requestHeader, $request); $this->client = new \SoapClient($this->wsdl['rates'], ['trace' => 1]); $this->response = $this->client->getRates($request); $this->responseCode = (int) $this->response->Notifications->Code; $this->responseMessage = (string) $this->response->Notifications->Message; $this->ratesExtended = []; if ($this->responseCode == 0) { foreach ($this->response->RateReplyDetails as $rate) { $serviceType = (string) $rate->ServiceType; $total = number_format((string) $rate->RatedShipmentDetails[0]->ShipmentRateDetail->TotalNetCharge->Amount, 2); $this->ratesExtended[$serviceType] = (object) ['shipper' => 'fedex', 'total' => $total, 'PackagingType' => (string) $rate->PackagingType, 'SignatureOption' => (string) $rate->SignatureOption, 'ActualRateType' => (string) $rate->ActualRateType, 'serviceType' => $serviceType, 'title' => self::$services[$serviceType]]; $this->rates[self::$services[$serviceType]] = $total; } $this->rates = array_reverse($this->rates, true); } }
/** sends a SOAP request to a FedEx server. see what happens */ function send_fedex_query($request) { if ($this->debug) { $log = "\n\n==\n" . get_class($this) . "::send_fedex_query()\n" . date('r'); $log .= "\nIP: " . $_SERVER['REMOTE_ADDR']; error_log($log, 3, $this->debug_log); } $wsdl = dirname(__FILE__) . '/' . $this->_path_to_wsdl; if ($this->test_mode) { // testing version wsql hacked in, has a one-line difference $wsdl = preg_replace('/\\.wsdl$/', '-testing.wsdl', $wsdl); } $client = new SoapClient($wsdl, array('trace' => $this->debug)); // http://us3.php.net/manual/en/ref.soap.php $quotes = array(); try { $response = $client->getRates($request); } catch (SoapFault $e) { if ($this->debug) { $log = "\n\n==== EXCEPTION CAUGHT : SoapFault Exception ====\n"; $log .= "====REQUEST====: \n" . $client->__getLastRequestHeaders() . "\n"; $log .= $client->__getLastRequest() . "\n\n"; $log .= "====RESPONSE===: \n" . $client->__getLastResponseHeaders() . "\n"; $log .= $client->__getLastResponse() . "\n\n"; error_log($log, 3, $this->debug_log); } return $this->raiseError($e->getMessage()); } if ($this->debug) { $log = "\n====REQUEST==== \n" . $client->__getLastRequest() . "\n\n"; error_log($log, 3, $this->debug_log); error_log("\nHighestSeverity: {$response->HighestSeverity}\n", 3, $this->debug_log); $log = "====RESPONSE===: \n" . serialize($response) . "\n\n"; error_log($log, 3, $this->debug_log); } if ($response->HighestSeverity == 'SUCCESS') { foreach ($response->RateReplyDetails as $rateReply) { if (!is_object($rateReply) || !isset($rateReply->ServiceType)) { continue; } $service = $rateReply->ServiceType; foreach ($rateReply->RatedShipmentDetails as $detail) { $last_rate = null; if (isset($detail->ShipmentRateDetail)) { $rate = $detail->ShipmentRateDetail->TotalNetFedExCharge->Amount; /* fedex returns multiple rate detail objects for each method, but they are always identical (maybe) */ if (!empty($last_rate) and $rate != $last_rate) { $msg = "got different rates for the same shipping method {$service}"; trigger_error($msg, E_USER_WARNING); if ($this->debug) { error_log("{$msg}\n", 3, $this->debug_log); } } $last_rate = $rate; } } $quotes[$service] = $rate; } if (empty($quotes)) { $err = "No ship methods are available for this destination at this time. Please try again."; if ($this->debug) { error_log("ERROR: {$err}\n", 3, $this->debug_log); } return $this->raiseError($err); } return $quotes; } else { if (is_object($response->Notifications)) { if ($response->Notifications->Code == 556) { $err = "The Address or Postal/ZIP code was not valid."; } else { $err = $response->Notifications->Severity . ': ' . $response->Notifications->Message . ' '; } } elseif (is_array($response->Notifications)) { foreach ($response->Notifications as $notification) { $err .= $notification->Message . ' '; } } if ($this->debug) { error_log("Notification: {$err}\n", 3, $this->debug_log); } return $this->raiseError($err); } }
function quote($pShipHash = array()) { /* FedEx integration starts */ global $gBitCustomer, $order; require_once dirname(__FILE__) . '/fedex-common.php5'; ini_set("soap.wsdl_cache_enabled", "0"); $shippingWeight = !empty($pShipHash['shipping_weight']) && $pShipHash['shipping_weight'] > 1 ? $pShipHash['shipping_weight'] : 1; $shippingNumBoxes = !empty($pShipHash['shipping_num_boxes']) ? $pShipHash['shipping_num_boxes'] : 1; $client = new SoapClient(dirname(__FILE__) . "/RateService_v10.wsdl", array('trace' => 1)); $this->types = array(); if (MODULE_SHIPPING_FEDEX_WEB_SERVICES_INTERNATIONAL_PRIORITY == 'true') { $this->types['INTERNATIONAL_PRIORITY'] = array('code' => 'FEDEX_INTERNATIONAL_PRIORITY', 'icon' => '', 'handling_fee' => MODULE_SHIPPING_FEDEX_WEB_SERVICES_INT_EXPRESS_HANDLING_FEE); $this->types['EUROPE_FIRST_INTERNATIONAL_PRIORITY'] = array('code' => 'FEDEX_EUROPE_FIRST_INTERNATIONAL_PRIORITY', 'icon' => '', 'handling_fee' => MODULE_SHIPPING_FEDEX_WEB_SERVICES_INT_EXPRESS_HANDLING_FEE); } if (MODULE_SHIPPING_FEDEX_WEB_SERVICES_INTERNATIONAL_ECONOMY == 'true') { $this->types['INTERNATIONAL_ECONOMY'] = array('code' => 'FEDEX_INTERNATIONAL_ECONOMY', 'icon' => '', 'handling_fee' => MODULE_SHIPPING_FEDEX_WEB_SERVICES_INT_EXPRESS_HANDLING_FEE); } if (MODULE_SHIPPING_FEDEX_WEB_SERVICES_STANDARD_OVERNIGHT == 'true') { $this->types['STANDARD_OVERNIGHT'] = array('code' => 'FEDEX_STANDARD_OVERNIGHT', 'icon' => '', 'handling_fee' => MODULE_SHIPPING_FEDEX_WEB_SERVICES_EXPRESS_HANDLING_FEE); } if (MODULE_SHIPPING_FEDEX_WEB_SERVICES_FIRST_OVERNIGHT == 'true') { $this->types['FIRST_OVERNIGHT'] = array('code' => 'FEDEX_FIRST_OVERNIGHT', 'icon' => '', 'handling_fee' => MODULE_SHIPPING_FEDEX_WEB_SERVICES_EXPRESS_HANDLING_FEE); } if (MODULE_SHIPPING_FEDEX_WEB_SERVICES_PRIORITY_OVERNIGHT == 'true') { $this->types['PRIORITY_OVERNIGHT'] = array('code' => 'FEDEX_PRIORITY_OVERNIGHT', 'icon' => '', 'handling_fee' => MODULE_SHIPPING_FEDEX_WEB_SERVICES_EXPRESS_HANDLING_FEE); } if (MODULE_SHIPPING_FEDEX_WEB_SERVICES_2DAY == 'true') { $this->types['FEDEX_2_DAY'] = array('code' => 'FEDEX_2_DAY', 'icon' => '', 'handling_fee' => MODULE_SHIPPING_FEDEX_WEB_SERVICES_EXPRESS_HANDLING_FEE); } // because FEDEX_GROUND also is returned for Canadian Addresses, we need to check if the country matches the store country and whether international ground is enabled if (MODULE_SHIPPING_FEDEX_WEB_SERVICES_GROUND == 'true' && $order->delivery['country']['countries_id'] == STORE_COUNTRY || MODULE_SHIPPING_FEDEX_WEB_SERVICES_GROUND == 'true' && $order->delivery['country']['countries_id'] != STORE_COUNTRY && MODULE_SHIPPING_FEDEX_WEB_SERVICES_INTERNATIONAL_GROUND == 'true') { $this->types['FEDEX_GROUND'] = array('code' => 'FEDEX_GROUND', 'icon' => '', 'handling_fee' => $order->delivery['country']['countries_id'] == STORE_COUNTRY ? MODULE_SHIPPING_FEDEX_WEB_SERVICES_HANDLING_FEE : MODULE_SHIPPING_FEDEX_WEB_SERVICES_INT_HANDLING_FEE); $this->types['GROUND_HOME_DELIVERY'] = array('code' => 'FEDEX_GROUND_HOME_DELIVERY', 'icon' => '', 'handling_fee' => $order->delivery['country']['countries_id'] == STORE_COUNTRY ? MODULE_SHIPPING_FEDEX_WEB_SERVICES_HANDLING_FEE : MODULE_SHIPPING_FEDEX_WEB_SERVICES_INT_HANDLING_FEE); } if (MODULE_SHIPPING_FEDEX_WEB_SERVICES_INTERNATIONAL_GROUND == 'true') { $this->types['INTERNATIONAL_GROUND'] = array('code' => 'FEDEX_INTERNATIONAL_GROUND', 'icon' => '', 'handling_fee' => MODULE_SHIPPING_FEDEX_WEB_SERVICES_INT_HANDLING_FEE); } if (MODULE_SHIPPING_FEDEX_WEB_SERVICES_EXPRESS_SAVER == 'true') { $this->types['FEDEX_EXPRESS_SAVER'] = array('code' => 'FEDEX_EXPRESS_SAVER', 'icon' => '', 'handling_fee' => MODULE_SHIPPING_FEDEX_WEB_SERVICES_EXPRESS_HANDLING_FEE); } if (MODULE_SHIPPING_FEDEX_WEB_SERVICES_FREIGHT == 'true') { $this->types['FEDEX_FREIGHT'] = array('code' => 'FEDEX_FREIGHT', 'icon' => '', 'handling_fee' => MODULE_SHIPPING_FEDEX_WEB_SERVICES_EXPRESS_HANDLING_FEE); $this->types['FEDEX_NATIONAL_FREIGHT'] = array('code' => 'FEDEX_NATIONAL_FREIGHT', 'icon' => '', 'handling_fee' => MODULE_SHIPPING_FEDEX_WEB_SERVICES_EXPRESS_HANDLING_FEE); $this->types['FEDEX_1_DAY_FREIGHT'] = array('code' => 'FEDEX_1_DAY_FREIGHT', 'icon' => '', 'handling_fee' => MODULE_SHIPPING_FEDEX_WEB_SERVICES_EXPRESS_HANDLING_FEE); $this->types['FEDEX_2_DAY_FREIGHT'] = array('code' => 'FEDEX_2_DAY_FREIGHT', 'icon' => '', 'handling_fee' => MODULE_SHIPPING_FEDEX_WEB_SERVICES_EXPRESS_HANDLING_FEE); $this->types['FEDEX_3_DAY_FREIGHT'] = array('code' => 'FEDEX_3_DAY_FREIGHT', 'icon' => '', 'handling_fee' => MODULE_SHIPPING_FEDEX_WEB_SERVICES_EXPRESS_HANDLING_FEE); $this->types['INTERNATIONAL_ECONOMY_FREIGHT'] = array('code' => 'FEDEX_INTERNATIONAL_ECONOMY_FREIGHT', 'icon' => '', 'handling_fee' => MODULE_SHIPPING_FEDEX_WEB_SERVICES_INT_EXPRESS_HANDLING_FEE); $this->types['INTERNATIONAL_PRIORITY_FREIGHT'] = array('code' => 'FEDEX_INTERNATIONAL_PRIORITY_FREIGHT', 'icon' => '', 'handling_fee' => MODULE_SHIPPING_FEDEX_WEB_SERVICES_INT_EXPRESS_HANDLING_FEE); } // customer details $street_address = !empty($order->delivery['street_address']) ? $order->delivery['street_address'] : ''; $street_address2 = !empty($order->delivery['suburb']) ? $order->delivery['suburb'] : ''; $city = !empty($order->delivery['city']) ? $order->delivery['city'] : ''; if ($stateLookup = BitBase::getParameter($order->delivery, 'zone_id', BitBase::getParameter($order->delivery, 'state'))) { $stateCode = zen_get_zone_code($order->delivery['country']['countries_id'], $stateLookup, ''); if ($stateCode == "QC") { $stateCode = "PQ"; // is this needed? been here forever } } $postcode = str_replace(array(' ', '-'), '', $order->delivery['postcode']); $country_id = $order->delivery['country']['countries_iso_code_2']; if (is_object($order)) { $totals = $order->subtotal; } elseif (is_object($gBitCustomer->mCart)) { $totals = $gBitCustomer->mCart->show_total(); } $this->_setInsuranceValue($totals); $request['WebAuthenticationDetail'] = array('UserCredential' => array('Key' => MODULE_SHIPPING_FEDEX_WEB_SERVICES_KEY, 'Password' => MODULE_SHIPPING_FEDEX_WEB_SERVICES_PWD)); $request['ClientDetail'] = array('AccountNumber' => MODULE_SHIPPING_FEDEX_WEB_SERVICES_ACT_NUM, 'MeterNumber' => MODULE_SHIPPING_FEDEX_WEB_SERVICES_METER_NUM); $request['TransactionDetail'] = array('CustomerTransactionId' => ' *** Rate Request v10 using PHP ***'); $request['Version'] = array('ServiceId' => 'crs', 'Major' => '10', 'Intermediate' => '0', 'Minor' => '0'); $request['ReturnTransitAndCommit'] = true; $request['RequestedShipment']['DropoffType'] = $this->_setDropOff(); // valid values REGULAR_PICKUP, REQUEST_COURIER, ... $request['RequestedShipment']['ShipTimestamp'] = date('c'); //if (zen_not_null($method) && in_array($method, $this->types)) { //$request['RequestedShipment']['ServiceType'] = $method; // valid values STANDARD_OVERNIGHT, PRIORITY_OVERNIGHT, FEDEX_GROUND, ... //} $request['RequestedShipment']['PackagingType'] = 'YOUR_PACKAGING'; // valid values FEDEX_BOX, FEDEX_PAK, FEDEX_TUBE, YOUR_PACKAGING, ... $request['RequestedShipment']['TotalInsuredValue'] = array('Amount' => $this->insurance, 'Currency' => DEFAULT_CURRENCY); $request['WebAuthenticationDetail'] = array('UserCredential' => array('Key' => MODULE_SHIPPING_FEDEX_WEB_SERVICES_KEY, 'Password' => MODULE_SHIPPING_FEDEX_WEB_SERVICES_PWD)); $request['ClientDetail'] = array('AccountNumber' => MODULE_SHIPPING_FEDEX_WEB_SERVICES_ACT_NUM, 'MeterNumber' => MODULE_SHIPPING_FEDEX_WEB_SERVICES_METER_NUM); $request['RequestedShipment']['Shipper'] = array('Address' => array('StreetLines' => array(MODULE_SHIPPING_FEDEX_WEB_SERVICES_ADDRESS_1, MODULE_SHIPPING_FEDEX_WEB_SERVICES_ADDRESS_2), 'City' => MODULE_SHIPPING_FEDEX_WEB_SERVICES_CITY, 'StateOrProvinceCode' => MODULE_SHIPPING_FEDEX_WEB_SERVICES_STATE, 'PostalCode' => MODULE_SHIPPING_FEDEX_WEB_SERVICES_POSTAL, 'CountryCode' => $this->country)); $request['RequestedShipment']['Recipient'] = array('Address' => array('StreetLines' => array(utf8_encode($street_address), utf8_encode($street_address2)), 'City' => utf8_encode($city), 'PostalCode' => $postcode, 'CountryCode' => $country_id, 'Residential' => empty($order->delivery['company']))); //customer county code if (!empty($stateCode) && in_array($country_id, array('US', 'CA'))) { $request['RequestedShipment']['Recipient']['StateOrProvinceCode'] = $stateCode; } $request['RequestedShipment']['ShippingChargesPayment'] = array('PaymentType' => 'SENDER', 'Payor' => array('AccountNumber' => MODULE_SHIPPING_FEDEX_WEB_SERVICES_ACT_NUM, 'CountryCode' => $this->country)); $request['RequestedShipment']['RateRequestTypes'] = 'LIST'; $request['RequestedShipment']['PackageDetail'] = 'INDIVIDUAL_PACKAGES'; $request['RequestedShipment']['RequestedPackageLineItems'] = array(); $dimensions_failed = false; // check for ready to ship field if (MODULE_SHIPPING_FEDEX_WEB_SERVICES_READY_TO_SHIP == 'true') { // Not fixed for bitcommerce $products = $gBitCustomer->mCart->get_products(); $packages = array('default' => 0); $new_shipping_num_boxes = 0; foreach ($products as $product) { $dimensions_query = "SELECT products_length, products_width, products_height, products_ready_to_ship, products_dim_type FROM " . TABLE_PRODUCTS . " \r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t WHERE products_id = " . (int) $product['id'] . " \r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t AND products_length > 0 \r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t AND products_width > 0\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t AND products_height > 0 \r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t LIMIT 1;"; $dimensions = $this->mDb->query($dimensions_query); if ($dimensions->RecordCount() > 0 && $dimensions->fields['products_ready_to_ship'] == 1) { for ($i = 1; $i <= $product['quantity']; $i++) { $packages[] = array('weight' => $product['weight'], 'length' => $dimensions->fields['products_length'], 'width' => $dimensions->fields['products_width'], 'height' => $dimensions->fields['products_height'], 'units' => strtoupper($dimensions->fields['products_dim_type'])); } } else { $packages['default'] += $product['weight'] * $product['quantity']; } } if (count($packages) > 1) { $za_tare_array = preg_split("/[:,]/", SHIPPING_BOX_WEIGHT); $zc_tare_percent = $za_tare_array[0]; $zc_tare_weight = $za_tare_array[1]; $za_large_array = preg_split("/[:,]/", SHIPPING_BOX_PADDING); $zc_large_percent = $za_large_array[0]; $zc_large_weight = $za_large_array[1]; } foreach ($packages as $id => $values) { if ($id === 'default') { // divide the weight by the max amount to be shipped (can be done inside loop as this occurance should only ever happen once // note $values is not an array if ($values == 0) { continue; } $shippingNumBoxes = ceil((double) $values / (double) SHIPPING_MAX_WEIGHT); if ($shippingNumBoxes < 1) { $shippingNumBoxes = 1; } $shippingWeight = round((double) $values / $shippingNumBoxes, 2); // 2 decimal places max for ($i = 0; $i < $shippingNumBoxes; $i++) { $new_shipping_num_boxes++; if (SHIPPING_MAX_WEIGHT <= $shippingWeight) { $shippingWeight = $shippingWeight + $shippingWeight * ($zc_large_percent / 100) + $zc_large_weight; } else { $shippingWeight = $shippingWeight + $shippingWeight * ($zc_tare_percent / 100) + $zc_tare_weight; } if ($shippingWeight <= 0) { $shippingWeight = 0.1; } $new_shipping_weight += $shippingWeight; $request['RequestedShipment']['RequestedPackageLineItems'][] = array('Weight' => array('Value' => $shippingWeight, 'Units' => MODULE_SHIPPING_FEDEX_WEB_SERVICES_WEIGHT), 'GroupPackageCount' => 1); } } else { // note $values is an array $new_shipping_num_boxes++; if ($values['weight'] <= 0) { $values['weight'] = 0.1; } $new_shipping_weight += $values['weight']; $request['RequestedShipment']['RequestedPackageLineItems'][] = array('Weight' => array('Value' => $values['weight'], 'Units' => MODULE_SHIPPING_FEDEX_WEB_SERVICES_WEIGHT), 'Dimensions' => array('Length' => $values['length'], 'Width' => $values['width'], 'Height' => $values['height'], 'Units' => $values['units']), 'GroupPackageCount' => 1); } } $shippingNumBoxes = $new_shipping_num_boxes; $shippingWeight = round($new_shipping_weight / $shippingNumBoxes, 2); } else { if ($shippingWeight == 0) { $shippingWeight = 0.1; } for ($i = 0; $i < $shippingNumBoxes; $i++) { $request['RequestedShipment']['RequestedPackageLineItems'][] = array('Weight' => array('Value' => $shippingWeight, 'Units' => MODULE_SHIPPING_FEDEX_WEB_SERVICES_WEIGHT), 'GroupPackageCount' => 1); } } $request['RequestedShipment']['PackageCount'] = $shippingNumBoxes; if (MODULE_SHIPPING_FEDEX_WEB_SERVICES_SATURDAY == 'true') { $request['RequestedShipment']['ServiceOptionType'] = 'SATURDAY_DELIVERY'; } if (MODULE_SHIPPING_FEDEX_WEB_SERVICES_SIGNATURE_OPTION >= 0 && $totals >= MODULE_SHIPPING_FEDEX_WEB_SERVICES_SIGNATURE_OPTION) { $request['RequestedShipment']['SpecialServicesRequested'] = 'SIGNATURE_OPTION'; } try { $response = $client->getRates($request); if (!empty($response) && ($response->HighestSeverity != 'FAILURE' && $response->HighestSeverity != 'ERROR' && !empty($response->RateReplyDetails))) { if (is_object($response->RateReplyDetails)) { $response->RateReplyDetails = get_object_vars($response->RateReplyDetails); } //echo '<pre>'; //print_r($response->RateReplyDetails); //echo '</pre>'; switch (SHIPPING_BOX_WEIGHT_DISPLAY) { case 0: $show_box_weight = ''; break; case 1: $show_box_weight = ' (' . $shippingNumBoxes . ' ' . TEXT_SHIPPING_BOXES . ')'; break; case 2: $show_box_weight = ' (' . number_format($shippingWeight * $shippingNumBoxes, 2) . tra('lbs') . ')'; break; default: $show_box_weight = ' (' . $shippingNumBoxes . ' x ' . number_format($shippingWeight, 2) . tra('lbs') . ')'; break; } $this->quotes = array('id' => $this->code, 'module' => $this->title, 'info' => $this->info(), 'weight' => $show_box_weight); $methods = array(); foreach ($response->RateReplyDetails as $rateReply) { if (array_key_exists($rateReply->ServiceType, $this->types) && (empty($pShipHash['method']) || str_replace('_', '', $rateReply->ServiceType) == $pShipHash['method'])) { $cost = NULL; if (MODULE_SHIPPING_FEDEX_WEB_SERVICES_RATES == 'LIST') { foreach ($rateReply->RatedShipmentDetails as $ShipmentRateDetail) { if ($ShipmentRateDetail->ShipmentRateDetail->RateType == 'PAYOR_LIST_PACKAGE') { $cost = $ShipmentRateDetail->ShipmentRateDetail->TotalNetCharge->Amount; $cost = (double) round(preg_replace('/[^0-9.]/', '', $cost), 2); } } } else { $cost = $rateReply->RatedShipmentDetails[0]->ShipmentRateDetail->TotalNetCharge->Amount; $cost = (double) round(preg_replace('/[^0-9.]/', '', $cost), 2); } $methods[] = array('id' => str_replace('_', '', $rateReply->ServiceType), 'title' => ucwords(strtolower(str_replace('_', ' ', $rateReply->ServiceType))), 'cost' => $cost + (strpos($this->types[$rateReply->ServiceType]['handling_fee'], '%') ? $cost * (double) $this->types[$rateReply->ServiceType]['handling_fee'] / 100 : (double) $this->types[$rateReply->ServiceType]['handling_fee']), 'code' => $this->types[$rateReply->ServiceType]['code']); } } $this->quotes['methods'] = $methods; if ($this->tax_class > 0) { $this->quotes['tax'] = zen_get_tax_rate($this->tax_class, $order->delivery['country']['countries_id'], $order->delivery['zone_id']); } } else { $message = ''; if (is_array($response->Notifications)) { foreach ($response->Notifications as $notification) { $message .= tra($notification->Severity) . ': ' . tra($notification->Message); } } elseif (is_object($response->Notifications)) { $message .= tra($response->Notifications->Severity) . ': ' . tra($response->Notifications->Message); } } } catch (Exception $e) { $message = $e->getMessage(); } if (!empty($message)) { $this->quotes = array('module' => $this->title, 'error' => $message); } if (!empty($this->icon)) { $this->quotes['icon'] = $this->icon; } return $this->quotes; }
public function getFedexShippingCost($wsParams) { // Check config if (!Configuration::get('FEDEX_CARRIER_API_KEY')) { return array('connect' => false, 'cost' => 0); } // Check if class Soap is available if (!extension_loaded('soap')) { return array('connect' => false, 'cost' => 0); } // Getting module directory $dir = dirname(__FILE__); if (preg_match('/classes/i', $dir)) { $dir .= '/../modules/fedexcarrier/'; } // Enable Php Soap ini_set("soap.wsdl_cache_enabled", "0"); $client = new SoapClient($dir . '/RateService_v10.wsdl', array('trace' => 1)); // Refer to http://us3.php.net/manual/en/ref.soap.php for more information // Country / State $shipper_country = Db::getInstance()->getRow('SELECT `iso_code` FROM `' . _DB_PREFIX_ . 'country` WHERE `id_country` = ' . (int) Configuration::get('FEDEX_CARRIER_COUNTRY')); $shipper_state = Db::getInstance()->getRow('SELECT `iso_code` FROM `' . _DB_PREFIX_ . 'state` WHERE `id_state` = ' . (int) Configuration::get('FEDEX_CARRIER_STATE')); // Generating soap request $request['WebAuthenticationDetail']['UserCredential'] = array('Key' => Configuration::get('FEDEX_CARRIER_API_KEY'), 'Password' => Configuration::get('FEDEX_CARRIER_PASSWORD')); $request['ClientDetail'] = array('AccountNumber' => Configuration::get('FEDEX_CARRIER_ACCOUNT'), 'MeterNumber' => Configuration::get('FEDEX_CARRIER_METER')); $request['TransactionDetail'] = array('CustomerTransactionId' => ' *** Rate Available Services Request v10 using PHP ***'); $request['Version'] = array('ServiceId' => 'crs', 'Major' => '10', 'Intermediate' => '0', 'Minor' => '0'); $request['ReturnTransitAndCommit'] = true; $request['RequestedShipment']['DropoffType'] = Configuration::get('FEDEX_CARRIER_PICKUP_TYPE'); // valid values REGULAR_PICKUP, REQUEST_COURIER, ... $request['RequestedShipment']['ShipTimestamp'] = date('c'); $request['RequestedShipment']['ServiceType'] = $wsParams['service']; // valid values STANDARD_OVERNIGHT, PRIORITY_OVERNIGHT, FEDEX_GROUND, ... $request['RequestedShipment']['PackagingType'] = Configuration::get('FEDEX_CARRIER_PACKAGING_TYPE'); // valid values FEDEX_BOX, FEDEX_PAK, FEDEX_TUBE, YOUR_PACKAGING, ... // Service Type and Packaging Type are not passed in the request $request['RequestedShipment']['Shipper']['Address'] = array('StreetLines' => $wsParams['shipper_address1'], 'City' => $wsParams['shipper_city'], 'StateOrProvinceCode' => $wsParams['shipper_state_iso'], 'PostalCode' => $wsParams['shipper_postalcode'], 'CountryCode' => $wsParams['shipper_country_iso']); $request['RequestedShipment']['Recipient']['Address'] = array('StreetLines' => $wsParams['recipient_address1'], 'City' => $wsParams['recipient_city'], 'StateOrProvinceCode' => $wsParams['recipient_state_iso'], 'PostalCode' => $wsParams['recipient_postalcode'], 'CountryCode' => $wsParams['recipient_country_iso']); $request['RequestedShipment']['ShippingChargesPayment'] = array('PaymentType' => 'SENDER', 'Payor' => array('AccountNumber' => Configuration::get('FEDEX_CARRIER_ACCOUNT'), 'CountryCode' => 'US')); $request['RequestedShipment']['RateRequestTypes'] = 'ACCOUNT'; $request['RequestedShipment']['RateRequestTypes'] = 'LIST'; $request['RequestedShipment']['PackageCount'] = '2'; $count = 1; foreach ($wsParams['package_list'] as $p) { $request['RequestedShipment']['RequestedPackageLineItems'][] = array('SequenceNumber' => $count, 'GroupPackageCount' => $count, 'Weight' => array('Value' => $p['weight'], 'Units' => substr($this->_weightUnit, 0, 2)), 'Dimensions' => array('Length' => $p['depth'], 'Width' => $p['width'], 'Height' => $p['height'], 'Units' => $this->_dimensionUnit)); $count++; } $request['RequestedShipment']['PackageCount'] = count($request['RequestedShipment']['RequestedPackageLineItems']); // Get Rates try { $resultTab = $client->getRates($request); } catch (Exception $e) { } // Check currency $conversionRate = 1; if (isset($resultTab->RateReplyDetails->RatedShipmentDetails[0]->ShipmentRateDetail->TotalNetCharge->Currency)) { $id_currency_return = Db::getInstance()->getValue('SELECT `id_currency` FROM `' . _DB_PREFIX_ . 'currency` WHERE `iso_code` = \'' . pSQL($resultTab->RateReplyDetails->RatedShipmentDetails[0]->ShipmentRateDetail->TotalNetCharge->Currency) . '\''); $conversionRate = $this->getCartCurrencyRate($id_currency_return, (int) $wsParams['id_cart']); } // Return results if (isset($resultTab->HighestSeverity) && $resultTab->HighestSeverity != 'ERROR' && isset($resultTab->RateReplyDetails->RatedShipmentDetails[0]->ShipmentRateDetail->TotalNetCharge->Amount)) { return array('connect' => true, 'cost' => number_format($resultTab->RateReplyDetails->RatedShipmentDetails[0]->ShipmentRateDetail->TotalNetCharge->Amount, 2, '.', ',') * $conversionRate); } if (isset($resultTab->HighestSeverity) && $resultTab->HighestSeverity == 'ERROR') { $this->_webserviceError = $this->l('Error') . ' ' . (isset($resultTab->Notifications->Code) ? $resultTab->Notifications->Code : '') . ' : ' . (isset($resultTab->Notifications->Message) ? $resultTab->Notifications->Message : ''); } else { $this->_webserviceError = $this->l('Fedex Webservice seems to be down, please wait a few minutes and try again.'); } return array('connect' => false, 'cost' => 0); }
private function get_result($request) { $this->debug('FedEx REQUEST: <a href="#" class="debug_reveal">Reveal</a><pre class="debug_info" style="background:#EEE;border:1px solid #DDD;padding:5px;">' . print_r($request, true) . '</pre>'); $client = new SoapClient(plugin_dir_path(dirname(__FILE__)) . 'fedex-wsdl/' . ($this->production ? 'production' : 'test') . '/RateService_v' . $this->rateservice_version . '.wsdl', array('trace' => 1)); $result = $client->getRates($request); $this->debug('FedEx RESPONSE: <a href="#" class="debug_reveal">Reveal</a><pre class="debug_info" style="background:#EEE;border:1px solid #DDD;padding:5px;">' . print_r($result, true) . '</pre>'); wc_enqueue_js("\n\t\t\tjQuery('a.debug_reveal').on('click', function(){\n\t\t\t\tjQuery(this).closest('div').find('.debug_info').slideDown();\n\t\t\t\tjQuery(this).remove();\n\t\t\t\treturn false;\n\t\t\t});\n\t\t\tjQuery('pre.debug_info').hide();\n\t\t"); return $result; }
$request['RequestedShipment']['ShipTimestamp'] = date('c'); $request['RequestedShipment']['ServiceType'] = 'INTERNATIONAL_PRIORITY'; // valid values STANDARD_OVERNIGHT, PRIORITY_OVERNIGHT, FEDEX_GROUND, ... $request['RequestedShipment']['PackagingType'] = 'YOUR_PACKAGING'; // valid values FEDEX_BOX, FEDEX_PAK, FEDEX_TUBE, YOUR_PACKAGING, ... $request['RequestedShipment']['TotalInsuredValue'] = array('Ammount' => 100, 'Currency' => 'USD'); $request['RequestedShipment']['Shipper'] = addShipper(); $request['RequestedShipment']['Recipient'] = addRecipient(); $request['RequestedShipment']['ShippingChargesPayment'] = addShippingChargesPayment(); $request['RequestedShipment']['PackageCount'] = '1'; $request['RequestedShipment']['RequestedPackageLineItems'] = addPackageLineItem1(); try { if (setEndpoint('changeEndpoint')) { $newLocation = $client->__setLocation(setEndpoint('endpoint')); } $response = $client->getRates($request); if ($response->HighestSeverity != 'FAILURE' && $response->HighestSeverity != 'ERROR') { $rateReply = $response->RateReplyDetails; echo '<table border="1">'; echo '<tr><td>Service Type</td><td>Amount</td><td>Delivery Date</td></tr><tr>'; $serviceType = '<td>' . $rateReply->ServiceType . '</td>'; if ($rateReply->RatedShipmentDetails && is_array($rateReply->RatedShipmentDetails)) { $amount = '<td>$' . number_format($rateReply->RatedShipmentDetails[0]->ShipmentRateDetail->TotalNetCharge->Amount, 2, ".", ",") . '</td>'; } elseif ($rateReply->RatedShipmentDetails && !is_array($rateReply->RatedShipmentDetails)) { $amount = '<td>$' . number_format($rateReply->RatedShipmentDetails->ShipmentRateDetail->TotalNetCharge->Amount, 2, ".", ",") . '</td>'; } // endif if (array_key_exists('DeliveryTimestamp', $rateReply)) { $deliveryDate = '<td>' . $rateReply->DeliveryTimestamp . '</td>'; } else { if (array_key_exists('TransitTime', $rateReply)) {
/** * Based on passed address information, calculates the total shipping cost * * @param $fields * @param $cart * @param string $country * @param string $zipcode * @param string $state * @param string $city * @param string $address2 * @param string $address1 * @param string $company * @param string $lname * @param string $fname * @return array|bool */ public function total($fields, $cart, $country = '', $zipcode = '', $state = '', $city = '', $address2 = '', $address1 = '', $company = '', $lname = '', $fname = '') { $config = $this->getConfigValues(get_class($this)); $weight = $cart->Weight; if (_xls_get_conf('WEIGHT_UNIT', 'lb') != 'lb') { $weight = $weight * 2.2; } // one KG is 2.2 pounds $length = $cart->Length; $width = $cart->Width; $height = $cart->Height; if (_xls_get_conf('DIMENSION_UNIT', 'in') != 'in') { $length = round($length / 2.54); $width = round($width / 2.54); $height = round($height / 2.54); } if ($length < 1 && $length > 0) { $length = 1; } if ($width < 1 && $width > 0) { $width = 1; } if ($height < 1 && $height > 0) { $height = 1; } if (empty($config['securitycode']) || empty($config['accnumber']) || empty($config['meternumber'])) { return FALSE; } $ret = array(); $newline = "<br />"; //The WSDL is not included with the sample code. //Please include and reference in $path_to_wsdl variable. $path_to_wsdl = dirname(__FILE__) . "/RateService_v7.wsdl"; ini_set("soap.wsdl_cache_enabled", "0"); $client = new SoapClient($path_to_wsdl, array('trace' => 1)); $request['WebAuthenticationDetail'] = array('UserCredential' => array('Key' => $config['authkey'], 'Password' => $config['securitycode'])); $request['ClientDetail'] = array('AccountNumber' => $config['accnumber'], 'MeterNumber' => $config['meternumber']); $request['TransactionDetail'] = array('CustomerTransactionId' => ' *** Rate Request v7 using PHP ***'); $request['Version'] = array('ServiceId' => 'crs', 'Major' => '7', 'Intermediate' => '0', 'Minor' => '0'); $request['ReturnTransitAndCommit'] = true; $request['RequestedShipment']['DropoffType'] = 'REGULAR_PICKUP'; // valid values REGULAR_PICKUP, REQUEST_COURIER, ... $request['RequestedShipment']['ShipTimestamp'] = date('c'); //Uncomment these additional options below if they are needed for your shipments //$request['RequestedShipment']['SpecialServicesRequested'] = array( 'SpecialServiceTypes' => array('SIGNATURE_OPTION'), 'SignatureOptionDetail' => array('OptionType' => 'ADULT')); //$request['RequestedShipment']['SignatureOptionDetail']['OptionType'] = 'ADULT'; //$request['RequestedShipment']['ServiceType'] = 'PRIORITY_OVERNIGHT'; // valid values STANDARD_OVERNIGHT, PRIORITY_OVERNIGHT, FEDEX_GROUND, ... $config['origincountry'] = Country::CodeById($config['origincountry']); $config['originstate'] = State::CodeById($config['originstate']); if ($config['origincountry'] != "CA" && $config['origincountry'] != "US") { //Only required for these countries $config['originstate'] = ""; } $request['RequestedShipment']['PackagingType'] = $config['packaging']; $request['RequestedShipment']['Shipper'] = array('Address' => array('StreetLines' => array($config['originadde']), 'City' => $config['origincity'], 'StateOrProvinceCode' => $config['originstate'], 'PostalCode' => $config['originpostcode'], 'CountryCode' => $config['origincountry'])); if ($country != "CA" && $country != "US") { //Only required for these countries $state = ""; } $request['RequestedShipment']['Recipient'] = array('Address' => array('StreetLines' => array($address1, $address2), 'City' => $city, 'StateOrProvinceCode' => $state, 'PostalCode' => $zipcode, 'CountryCode' => $country, 'Residential' => $this->CheckoutForm->shippingResidential == 1 ? 1 : 0)); $request['RequestedShipment']['ShippingChargesPayment'] = array('PaymentType' => 'SENDER', 'Payor' => array('AccountNumber' => $config['accnumber'], 'CountryCode' => $config['origincountry'])); $request['RequestedShipment']['RateRequestTypes'] = 'ACCOUNT'; $request['RequestedShipment']['RateRequestTypes'] = 'LIST'; if ($config['origincountry'] != $country && $config['customs'] == "CLEARANCEFEE") { $request['RequestedShipment']['InternationalDetail'] = array('CustomsValue' => array('Amount' => $cart->subtotal, 'Currency' => _xls_get_conf('CURRENCY_DEFAULT', 'USD'))); } $request['RequestedShipment']['PackageCount'] = '1'; $request['RateRequest']['CurrencyType'] = _xls_get_conf('CURRENCY_DEFAULT', 'USD'); $request['RequestedShipment']['PackageDetail'] = 'INDIVIDUAL_PACKAGES'; if ($length + $width + $height == 0) { $request['RequestedShipment']['RequestedPackageLineItems'] = array('0' => array('SequenceNumber' => '1', 'InsuredValue' => array('Amount' => $cart->subtotal, 'Currency' => _xls_get_conf('CURRENCY_DEFAULT', 'USD')), 'ItemDescription' => 'Ordered items', 'Weight' => array('Value' => $weight, 'Units' => 'LB'), 'CustomerReferences' => array('CustomerReferenceType' => 'CUSTOMER_REFERENCE', 'Value' => _xls_get_conf('STORE_NAME', 'Web Order')))); } else { $request['RequestedShipment']['RequestedPackageLineItems'] = array('0' => array('SequenceNumber' => '1', 'InsuredValue' => array('Amount' => $cart->subtotal, 'Currency' => _xls_get_conf('CURRENCY_DEFAULT', 'USD')), 'ItemDescription' => 'Ordered items', 'Weight' => array('Value' => $weight, 'Units' => 'LB'), 'Dimensions' => array('Length' => $length, 'Width' => $width, 'Height' => $height, 'Units' => 'IN'), 'CustomerReferences' => array('CustomerReferenceType' => 'CUSTOMER_REFERENCE', 'Value' => _xls_get_conf('STORE_NAME', 'Web Order')))); } try { $response = $client->getRates($request); Yii::log(get_class($this) . " sending " . print_r($request, true), $this->logLevel, 'application.' . __CLASS__ . "." . __FUNCTION__); Yii::log(get_class($this) . " receiving " . print_r($response, true), $this->logLevel, 'application.' . __CLASS__ . "." . __FUNCTION__); if ($response->HighestSeverity != 'FAILURE' && $response->HighestSeverity != 'ERROR') { if (isset($response->RateReplyDetails)) { if (is_array($response->RateReplyDetails) === false) { $response->RateReplyDetails = array($response->RateReplyDetails); } foreach ($response->RateReplyDetails as $rateReply) { if (isset($rateReply->RatedShipmentDetails)) { foreach ($rateReply->RatedShipmentDetails as $choice) { if ($choice->ShipmentRateDetail->RateType == $config['ratetype']) { $ret[$rateReply->ServiceType] = $choice->ShipmentRateDetail->TotalNetCharge->Amount; } elseif ($rateReply->ServiceType == "FEDEX_GROUND" || $rateReply->ServiceType == "GROUND_HOME_DELIVERY") { $ret[$rateReply->ServiceType] = $rateReply->RatedShipmentDetails[1]->ShipmentRateDetail->TotalNetCharge->Amount; } } } } } } } catch (SoapFault $exception) { _xls_log("FedEx Soap Fault : " . $exception . " "); $response = $exception; } if (count($ret) <= 0) { _xls_log("FedEx could not get rate for {$country}, {$state}, {$zipcode} . "); _xls_log("FedEx request: " . print_r($request, true)); _xls_log("FedEx Response: " . print_r($response, true)); return false; } asort($ret); Yii::log(get_class($this) . " received shipping array " . print_r($ret, true), $this->logLevel, 'application.' . __CLASS__ . "." . __FUNCTION__); return $this->convertRetToDisplay($ret); }
/** * Get FedEx rate quotes. */ function fwd_fedex_rates($params, $settings) { // Configurable FedEx service methods. $service_list = array('FEDEX_GROUND' => 'Fedex Ground', 'FEDEX_EXPRESS_SAVER' => 'Fedex Express Saver', 'FEDEX_2_DAY' => 'Fedex 2-Day Air', 'FEDEX_2_DAY_AM' => 'Fedex 2-Day Air A.M.', 'STANDARD_OVERNIGHT' => 'Fedex Standard Overnight', 'PRIORITY_OVERNIGHT' => 'Fedex Priority Overnight', 'FIRST_OVERNIGHT' => 'Fedex First Overnight', 'INTERNATIONAL_PRIORITY' => 'Fedex Priority International'); // If params are empty, return available methods only. if (empty($params)) { $methods = array(); foreach ((array) $settings['methods'] as $key => $method) { if ($method) { $method = is_array($method) ? $method : array(); $methods[] = array('id' => $key, 'name' => $method['name'] ?: $service_list[$key]); } } return $methods; } // Get shipper, default or specific. $shipper = array_merge(array('package_weight' => 100), (array) $settings['shippers'][0], (array) $settings['shippers'][$params['shipper']]); // Disable WSDL caching. ini_set('soap.wsdl_cache_enabled', '0'); // Create SOAP client with Fedex RateService WSDL. $client = new SoapClient(dirname(__FILE__) . '/wsdl/RateService_v10.wsdl', array('trace' => 1)); // Set endpoint host? if ($settings['host']) { $client->__setLocation($settings['host']); } // Split package by weight limit? if ($shipper['package_weight'] && $params['weight'] > $shipper['package_weight']) { $num_packages = ceil($params['weight'] / $shipper['package_weight']); for ($i = 0; $i < $num_packages; $i++) { if ($i >= 200) { break; } $params['packages'][$i] = array('insurance_amount' => $params['insurance_amount'] / $num_packages, 'insurance_currency' => $params['insurance_currency'], 'weight' => $params['weight'] / $num_packages, 'units' => $params['units']); } } // Setup request. $request = array('WebAuthenticationDetail' => array('UserCredential' => array('Key' => $settings['key'], 'Password' => $settings['password'])), 'ClientDetail' => array('AccountNumber' => $settings['account'], 'MeterNumber' => $settings['meter']), 'TransactionDetail' => array('CustomerTransactionId' => '*** Rate Request v10 using PHP ***'), 'Version' => array('ServiceId' => 'crs', 'Major' => '10', 'Intermediate' => '0', 'Minor' => '0'), 'ReturnTransitAndCommit' => true, 'RequestedShipment' => array('DropoffType' => 'REGULAR_PICKUP', 'ShipTimestamp' => date('c'), 'PackagingType' => 'YOUR_PACKAGING', 'Shipper' => array('Address' => array('StreetLines' => array($shipper['address']), 'City' => $shipper['city'], 'StateOrProvinceCode' => $shipper['state'], 'PostalCode' => $shipper['zip'], 'CountryCode' => $shipper['country'] ?: 'US')), 'Recipient' => array('Address' => array('StreetLines' => array($params['address']), 'City' => $params['city'], 'StateOrProvinceCode' => $params['state'], 'PostalCode' => $params['zip'], 'CountryCode' => $params['country'] ?: 'US')), 'ShippingChargesPayment' => array('PaymentType' => 'SENDER', 'Payor' => array('AccountNumber' => $shipper['account'] ?: $settings['account'], 'CountryCode' => $shipper['country'] ?: 'US')), 'RateRequestTypes' => 'ACCOUNT', 'RateRequestTypes' => 'LIST', 'PackageCount' => $params['packages'] ? count($params['packages']) : '1', 'RequestedPackages' => array())); // Default single package? if (count($params['packages']) == 0) { $params['packages'][0] = array('insurance_amount' => $params['insurance_amount'], 'insurance_currency' => $params['insurance_currency'], 'weight' => $params['weight'] ?: 1, 'units' => $params['units']); if ($params['dimensions']) { $params['packages'][0]['dimensions'] = array('length' => $params['dimensions']['length'], 'width' => $params['dimensions']['width'], 'height' => $params['dimensions']['height'], 'units' => $params['dimensions']['units']); } } // Add package(s) to request. foreach ($params['packages'] as $seq => $package) { $request['RequestedShipment']['RequestedPackageLineItems'][$seq] = array('SequenceNumber' => $seq + 1, 'GroupPackageCount' => 1, 'InsuredValue' => array('Amount' => $package['insurance_amount'] ?: 0, 'Currency' => $package['insurance_currency'] ?: 'USD'), 'Weight' => array('Value' => $package['weight'], 'Units' => $package['units'] ?: 'LB')); // Dimensions? if ($package['dimensions']) { $request['RequestedShipment']['RequestedPackageLineItems'][$seq]['Dimensions'] = array('Length' => $package['dimensions']['length'], 'Width' => $package['dimensions']['width'], 'Height' => $package['dimensions']['height'], 'Units' => $package['dimensions']['units'] ?: 'IN'); } } // Try the request. try { $response = $client->getRates($request); if ($response->HighestSeverity != 'FAILURE' && $response->HighestSeverity != 'ERROR') { if (!is_array($response->RateReplyDetails)) { $response->RateReplyDetails = array($response->RateReplyDetails); } foreach ($response->RateReplyDetails as $RateReplyDetail) { $service_type = $RateReplyDetail->ServiceType; if ($service_list[$service_type]) { $rsd = end($RateReplyDetail->RatedShipmentDetails); $tnc = $rsd->ShipmentRateDetail->TotalNetCharge; $price = (double) preg_replace('/[^\\d\\.]/i', '', $tnc->Amount); // Markup? if ($settings['markup']) { $price = Discounts::apply_value($price, '+' . $settings['markup']); } // Discount? if ($settings['discount']) { $price = Discounts::apply_value($price, $settings['markup']); } // Rated method configured/available? if ($method = $settings['methods'][$service_type]) { $method = is_array($method) ? $method : array(); $service_name = $method['name'] ?: $service_list[$service_type]; $service_price = round($price, 2); $shipment_rates[] = array('id' => $service_type, 'name' => $service_name, 'price' => $service_price); } } } } elseif ($response->HighestSeverity == 'FAILURE' || $response->HighestSeverity == 'ERROR') { throw new Exception($response->Notifications->LocalizedMessage ?: $response->Notifications->Message); } } catch (SoapFault $e) { throw new Exception($e->getMessage()); } return $shipment_rates; }
private function _processRequest($address, $products) { require_once DIR_EXT . 'default_fedex/core/lib/fedex_func.php'; if ($this->config->get('default_fedex_test')) { $path_to_wsdl = DIR_EXT . 'default_fedex/core/lib/RateService_v9_test.wsdl'; } else { $path_to_wsdl = DIR_EXT . 'default_fedex/core/lib/RateService_v9.wsdl'; } $client = new SoapClient($path_to_wsdl, array('trace' => 1)); // Refer to http://us3.php.net/manual/en/ref.soap.php for more information //Fedex Key $fedex_key = $this->config->get('default_fedex_key'); //Fedex Password $fedex_password = $this->config->get('default_fedex_password'); //Fedex Meter Id $fedex_meter_id = $this->config->get('default_fedex_meter'); //Fedex Account $fedex_account = $this->config->get('default_fedex_account'); //Quote Type Residential or commercial $fedex_quote = $this->config->get('default_fedex_quote_type'); if ($fedex_quote == 'residential') { $fedex_residential = true; } else { $fedex_residential = false; } $fedex_addr = $this->config->get('default_fedex_address'); $fedex_city = $this->config->get('default_fedex_city'); $fedex_state = $this->config->get('default_fedex_state'); $fedex_zip = $this->config->get('default_fedex_zip'); $fedex_country = $this->config->get('default_fedex_country'); $fedex_add_chrg = $this->config->get('default_fedex_add_chrg'); if (strlen($fedex_state) > 2) { $this->messages->saveError('Fedex US error!', 'Fedex US Shipping Extension won\'t work because state code length must be 2 letters. Please check settings form on #admin#rt=extension/extensions/edit&extension=default_fedex'); } if (strlen($fedex_country) != 2) { $this->messages->saveError('Fedex US error!', 'Fedex US Shipping Extension won\'t work because country code length must be 2 letters. Please check settings form on #admin#rt=extension/extensions/edit&extension=default_fedex'); } //Recepient Info $shipping_address = $address; $ground_quote = 0; $first_overnight_quote = 0; $priority_overnight_quote = 0; $standard_overnight_quote = 0; $two_day_quote = 0; $express_saver_quote = 0; //Products info if ($products) { foreach ($products as $result) { $request = array(); $product_weight = $this->weight->convert($result['weight'], $this->config->get('config_weight_class'), 'lb'); $product_weight = $product_weight < 0.1 ? 0.1 : $product_weight; $product_length = $this->length->convert($result['length'], $this->config->get('config_length_class'), 'in'); $product_width = $this->length->convert($result['width'], $this->config->get('config_length_class'), 'in'); $product_height = $this->length->convert($result['height'], $this->config->get('config_length_class'), 'in'); $product_quantity = $result['quantity']; $product_total = $result['total']; //BUILD REQUEST START $request['WebAuthenticationDetail'] = array('UserCredential' => array('Key' => $fedex_key, 'Password' => $fedex_password)); $request['ClientDetail'] = array('AccountNumber' => $fedex_account, 'MeterNumber' => $fedex_meter_id); $request['TransactionDetail'] = array('CustomerTransactionId' => ' *** Rate Request v9 using PHP ***'); $request['Version'] = array('ServiceId' => 'crs', 'Major' => '9', 'Intermediate' => '0', 'Minor' => '0'); $request['ReturnTransitAndCommit'] = true; $request['RequestedShipment']['DropoffType'] = 'REGULAR_PICKUP'; // valid values REGULAR_PICKUP, REQUEST_COURIER, ... $request['RequestedShipment']['ShipTimestamp'] = date('c'); //$request['RequestedShipment']['ServiceType'] = 'GROUND_HOME_DELIVERY'; // valid values STANDARD_OVERNIGHT, PRIORITY_OVERNIGHT, FEDEX_GROUND, ... $request['RequestedShipment']['PackagingType'] = 'YOUR_PACKAGING'; // valid values FEDEX_BOX, FEDEX_PAK, FEDEX_TUBE, YOUR_PACKAGING, ... $request['RequestedShipment']['TotalInsuredValue'] = array('Ammount' => $product_total, 'Currency' => 'USD'); $request['RequestedShipment']['Shipper'] = array('Address' => array('StreetLines' => array($fedex_addr), 'City' => $fedex_city, 'StateOrProvinceCode' => $fedex_state, 'PostalCode' => $fedex_zip, 'CountryCode' => $fedex_country)); $request['RequestedShipment']['Recipient'] = array('Address' => array('StreetLines' => array($shipping_address['address_1'], $shipping_address['address_2']), 'City' => $shipping_address['city'], 'StateOrProvinceCode' => $shipping_address['zone_code'], 'PostalCode' => $shipping_address['postcode'], 'CountryCode' => $shipping_address['iso_code_2'], 'Residential' => $fedex_residential)); $request['RequestedShipment']['ShippingChargesPayment'] = array('PaymentType' => 'SENDER', 'Payor' => array('AccountNumber' => $fedex_account, 'CountryCode' => 'US')); $request['RequestedShipment']['RateRequestTypes'] = 'ACCOUNT'; $request['RequestedShipment']['RateRequestTypes'] = 'LIST'; $request['RequestedShipment']['PackageCount'] = $product_quantity; $request['RequestedShipment']['PackageDetail'] = 'INDIVIDUAL_PACKAGES'; // Or PACKAGE_SUMMARY for ($q = 0; $q < $product_quantity; $q++) { $request['RequestedShipment']['RequestedPackageLineItems'] = array('Weight' => array('Value' => $product_weight, 'Units' => 'LB'), 'Dimensions' => array('Length' => $product_length, 'Width' => $product_width, 'Height' => $product_height, 'Units' => 'IN')); } try { if (setEndpoint('changeEndpoint')) { $newLocation = $client->__setLocation(setEndpoint('endpoint')); } $response = $client->getRates($request); if ($response->HighestSeverity != 'FAILURE' && $response->HighestSeverity != 'ERROR') { if (count($response->RateReplyDetails) > 1) { foreach ($response->RateReplyDetails as $rateReply) { if ($rateReply->ServiceType == 'FEDEX_GROUND' || $rateReply->ServiceType == 'GROUND_HOME_DELIVERY') { $ground_quote = $ground_quote + $product_quantity * number_format($rateReply->RatedShipmentDetails[0]->ShipmentRateDetail->TotalNetCharge->Amount, 2, ".", ","); } else { if ($rateReply->ServiceType == 'FIRST_OVERNIGHT') { $first_overnight_quote = $first_overnight_quote + $product_quantity * number_format($rateReply->RatedShipmentDetails[0]->ShipmentRateDetail->TotalNetCharge->Amount, 2, ".", ","); } else { if ($rateReply->ServiceType == 'PRIORITY_OVERNIGHT') { $priority_overnight_quote = $priority_overnight_quote + $product_quantity * number_format($rateReply->RatedShipmentDetails[0]->ShipmentRateDetail->TotalNetCharge->Amount, 2, ".", ","); } else { if ($rateReply->ServiceType == 'STANDARD_OVERNIGHT') { $standard_overnight_quote = $standard_overnight_quote + $product_quantity * number_format($rateReply->RatedShipmentDetails[0]->ShipmentRateDetail->TotalNetCharge->Amount, 2, ".", ","); } else { if ($rateReply->ServiceType == 'FEDEX_2_DAY') { $two_day_quote = $two_day_quote + $product_quantity * number_format($rateReply->RatedShipmentDetails[0]->ShipmentRateDetail->TotalNetCharge->Amount, 2, ".", ","); } else { if ($rateReply->ServiceType == 'FEDEX_EXPRESS_SAVER') { $express_saver_quote = $express_saver_quote + $product_quantity * number_format($rateReply->RatedShipmentDetails[0]->ShipmentRateDetail->TotalNetCharge->Amount, 2, ".", ","); } } } } } } } } else { $rateReply = $response->RateReplyDetails; if ($rateReply->ServiceType == 'FEDEX_GROUND' || $rateReply->ServiceType == 'GROUND_HOME_DELIVERY') { $ground_quote = $ground_quote + $product_quantity * number_format($rateReply->RatedShipmentDetails[0]->ShipmentRateDetail->TotalNetCharge->Amount, 2, ".", ","); } else { if ($rateReply->ServiceType == 'FIRST_OVERNIGHT') { $first_overnight_quote = $first_overnight_quote + $product_quantity * number_format($rateReply->RatedShipmentDetails[0]->ShipmentRateDetail->TotalNetCharge->Amount, 2, ".", ","); } else { if ($rateReply->ServiceType == 'PRIORITY_OVERNIGHT') { $priority_overnight_quote = $priority_overnight_quote + $product_quantity * number_format($rateReply->RatedShipmentDetails[0]->ShipmentRateDetail->TotalNetCharge->Amount, 2, ".", ","); } else { if ($rateReply->ServiceType == 'STANDARD_OVERNIGHT') { $standard_overnight_quote = $standard_overnight_quote + $product_quantity * number_format($rateReply->RatedShipmentDetails[0]->ShipmentRateDetail->TotalNetCharge->Amount, 2, ".", ","); } else { if ($rateReply->ServiceType == 'FEDEX_2_DAY') { $two_day_quote = $two_day_quote + $product_quantity * number_format($rateReply->RatedShipmentDetails[0]->ShipmentRateDetail->TotalNetCharge->Amount, 2, ".", ","); } else { if ($rateReply->ServiceType == 'FEDEX_EXPRESS_SAVER') { $express_saver_quote = $express_saver_quote + $product_quantity * number_format($rateReply->RatedShipmentDetails[0]->ShipmentRateDetail->TotalNetCharge->Amount, 2, ".", ","); } } } } } } } } else { $error_msg = $this->getNotifications($response->Notifications); } } catch (SoapFault $exception) { $error_text = 'Fault' . "<br>\n"; $error_text .= "Code:" . $exception->faultcode . "\n"; $error_text .= "String:" . $exception->faultstring . "\n"; $error_text .= $client; $this->message->saveError('fedex extension soap error', $error_text); $this->log->write($error_text); } } } if ($first_overnight_quote > 0 && $this->config->get('default_fedex_default_fedex_us_01') > 0) { $first_overnight_quote = $first_overnight_quote + $fedex_add_chrg; $quote_data['FEDEX_FIRST_OVERNIGHT'] = array('id' => 'default_fedex.' . 'FEDEX_FIRST_OVERNIGHT', 'title' => 'Fedex First Overnight', 'cost' => $this->currency->convert($first_overnight_quote, 'USD', $this->currency->getCode()), 'tax_class_id' => 0, 'text' => $this->currency->format($this->currency->convert($first_overnight_quote, 'USD', $this->currency->getCode()))); } if ($priority_overnight_quote > 0 && $this->config->get('default_fedex_default_fedex_us_02') > 0) { $priority_overnight_quote = $priority_overnight_quote + $fedex_add_chrg; $quote_data['FEDEX_PRIORITY_OVERNIGHT'] = array('id' => 'default_fedex.' . 'FEDEX_PRIORITY_OVERNIGHT', 'title' => 'Fedex Priority Overnight', 'cost' => $this->currency->convert($priority_overnight_quote, 'USD', $this->currency->getCode()), 'tax_class_id' => 0, 'text' => $this->currency->format($this->currency->convert($priority_overnight_quote, 'USD', $this->currency->getCode()))); } if ($standard_overnight_quote > 0 && $this->config->get('default_fedex_default_fedex_us_03') > 0) { $standard_overnight_quote = $standard_overnight_quote + $fedex_add_chrg; $quote_data['FEDEX_STANDARD_OVERNIGHT'] = array('id' => 'default_fedex.' . 'FEDEX_STANDARD_OVERNIGHT', 'title' => 'Fedex Standard Overnight', 'cost' => $this->currency->convert($standard_overnight_quote, 'USD', $this->currency->getCode()), 'tax_class_id' => 0, 'text' => $this->currency->format($this->currency->convert($standard_overnight_quote, 'USD', $this->currency->getCode()))); } if ($two_day_quote > 0 && $this->config->get('default_fedex_default_fedex_us_04') > 0) { $two_day_quote = $two_day_quote + $fedex_add_chrg; $quote_data['FEDEX_2_DAY'] = array('id' => 'default_fedex.' . 'FEDEX_2_DAY', 'title' => 'Fedex 2 Day', 'cost' => $this->currency->convert($two_day_quote, 'USD', $this->currency->getCode()), 'tax_class_id' => 0, 'text' => $this->currency->format($this->currency->convert($two_day_quote, 'USD', $this->currency->getCode()))); } if ($express_saver_quote > 0 && $this->config->get('default_fedex_default_fedex_us_05') > 0) { $express_saver_quote = $express_saver_quote + $fedex_add_chrg; $quote_data['FEDEX_EXPRESS_SAVER'] = array('id' => 'default_fedex.' . 'FEDEX_EXPRESS_SAVER', 'title' => 'Fedex Express Saver', 'cost' => $this->currency->convert($express_saver_quote, 'USD', $this->currency->getCode()), 'tax_class_id' => 0, 'text' => $this->currency->format($this->currency->convert($express_saver_quote, 'USD', $this->currency->getCode()))); } if ($ground_quote > 0 && $this->config->get('default_fedex_default_fedex_us_06') > 0) { $ground_quote = $ground_quote + $fedex_add_chrg; $quote_data['FEDEX_GROUND'] = array('id' => 'default_fedex.' . 'FEDEX_GROUND', 'title' => 'Fedex Ground', 'cost' => $this->currency->convert($ground_quote, 'USD', $this->currency->getCode()), 'tax_class_id' => 0, 'text' => $this->currency->format($this->currency->convert($ground_quote, 'USD', $this->currency->getCode()))); } return array('quote_data' => $quote_data, 'error_msg' => $error_msg); }
function quote($method = '') { /* FedEx integration starts */ global $shipping_weight, $shipping_num_boxes, $cart, $order; require_once DIR_FS_CATALOG . DIR_WS_INCLUDES . 'library/fedex-common.php5'; //if (MODULE_SHIPPING_FEDEX_WEB_SERVICES_SERVER == 'test') { //$request['Version'] = array('ServiceId' => 'crs', 'Major' => '7', 'Intermediate' => '0', 'Minor' => '0'); //$path_to_wsdl = DIR_WS_INCLUDES . "wsdl/RateService_v7_test.wsdl"; //} else { $path_to_wsdl = DIR_FS_CATALOG . DIR_WS_INCLUDES . "wsdl/RateService_v9.wsdl"; //} ini_set("soap.wsdl_cache_enabled", "0"); $client = new SoapClient($path_to_wsdl, array('trace' => 1)); $this->types = array(); if (MODULE_SHIPPING_FEDEX_WEB_SERVICES_INTERNATIONAL_PRIORITY == 'true') { $this->types['INTERNATIONAL_PRIORITY'] = array('icon' => '', 'handling_fee' => MODULE_SHIPPING_FEDEX_WEB_SERVICES_INT_EXPRESS_HANDLING_FEE); $this->types['EUROPE_FIRST_INTERNATIONAL_PRIORITY'] = array('icon' => '', 'handling_fee' => MODULE_SHIPPING_FEDEX_WEB_SERVICES_INT_EXPRESS_HANDLING_FEE); } if (MODULE_SHIPPING_FEDEX_WEB_SERVICES_INTERNATIONAL_ECONOMY == 'true') { $this->types['INTERNATIONAL_ECONOMY'] = array('icon' => '', 'handling_fee' => MODULE_SHIPPING_FEDEX_WEB_SERVICES_INT_EXPRESS_HANDLING_FEE); } if (MODULE_SHIPPING_FEDEX_WEB_SERVICES_STANDARD_OVERNIGHT == 'true') { $this->types['STANDARD_OVERNIGHT'] = array('icon' => '', 'handling_fee' => MODULE_SHIPPING_FEDEX_WEB_SERVICES_EXPRESS_HANDLING_FEE); } if (MODULE_SHIPPING_FEDEX_WEB_SERVICES_FIRST_OVERNIGHT == 'true') { $this->types['FIRST_OVERNIGHT'] = array('icon' => '', 'handling_fee' => MODULE_SHIPPING_FEDEX_WEB_SERVICES_EXPRESS_HANDLING_FEE); } if (MODULE_SHIPPING_FEDEX_WEB_SERVICES_PRIORITY_OVERNIGHT == 'true') { $this->types['PRIORITY_OVERNIGHT'] = array('icon' => '', 'handling_fee' => MODULE_SHIPPING_FEDEX_WEB_SERVICES_EXPRESS_HANDLING_FEE); } if (MODULE_SHIPPING_FEDEX_WEB_SERVICES_2DAY == 'true') { $this->types['FEDEX_2_DAY'] = array('icon' => '', 'handling_fee' => MODULE_SHIPPING_FEDEX_WEB_SERVICES_EXPRESS_HANDLING_FEE); } // because FEDEX_GROUND also is returned for Canadian Addresses, we need to check if the country matches the store country and whether international ground is enabled if (MODULE_SHIPPING_FEDEX_WEB_SERVICES_GROUND == 'true' && $order->delivery['country']['id'] == STORE_COUNTRY || MODULE_SHIPPING_FEDEX_WEB_SERVICES_GROUND == 'true' && $order->delivery['country']['id'] != STORE_COUNTRY && MODULE_SHIPPING_FEDEX_WEB_SERVICES_INTERNATIONAL_GROUND == 'true') { $this->types['FEDEX_GROUND'] = array('icon' => '', 'handling_fee' => $order->delivery['country']['id'] == STORE_COUNTRY ? MODULE_SHIPPING_FEDEX_WEB_SERVICES_HANDLING_FEE : MODULE_SHIPPING_FEDEX_WEB_SERVICES_INT_HANDLING_FEE); $this->types['GROUND_HOME_DELIVERY'] = array('icon' => '', 'handling_fee' => $order->delivery['country']['id'] == STORE_COUNTRY ? MODULE_SHIPPING_FEDEX_WEB_SERVICES_HOME_DELIVERY_HANDLING_FEE : MODULE_SHIPPING_FEDEX_WEB_SERVICES_INT_HANDLING_FEE); } if (MODULE_SHIPPING_FEDEX_WEB_SERVICES_INTERNATIONAL_GROUND == 'true') { $this->types['INTERNATIONAL_GROUND'] = array('icon' => '', 'handling_fee' => MODULE_SHIPPING_FEDEX_WEB_SERVICES_INT_HANDLING_FEE); } if (MODULE_SHIPPING_FEDEX_WEB_SERVICES_EXPRESS_SAVER == 'true') { $this->types['FEDEX_EXPRESS_SAVER'] = array('icon' => '', 'handling_fee' => MODULE_SHIPPING_FEDEX_WEB_SERVICES_EXPRESS_HANDLING_FEE); } if (MODULE_SHIPPING_FEDEX_WEB_SERVICES_FREIGHT == 'true') { $this->types['FEDEX_FREIGHT'] = array('icon' => '', 'handling_fee' => MODULE_SHIPPING_FEDEX_WEB_SERVICES_EXPRESS_HANDLING_FEE); $this->types['FEDEX_NATIONAL_FREIGHT'] = array('icon' => '', 'handling_fee' => MODULE_SHIPPING_FEDEX_WEB_SERVICES_EXPRESS_HANDLING_FEE); $this->types['FEDEX_1_DAY_FREIGHT'] = array('icon' => '', 'handling_fee' => MODULE_SHIPPING_FEDEX_WEB_SERVICES_EXPRESS_HANDLING_FEE); $this->types['FEDEX_2_DAY_FREIGHT'] = array('icon' => '', 'handling_fee' => MODULE_SHIPPING_FEDEX_WEB_SERVICES_EXPRESS_HANDLING_FEE); $this->types['FEDEX_3_DAY_FREIGHT'] = array('icon' => '', 'handling_fee' => MODULE_SHIPPING_FEDEX_WEB_SERVICES_EXPRESS_HANDLING_FEE); $this->types['INTERNATIONAL_ECONOMY_FREIGHT'] = array('icon' => '', 'handling_fee' => MODULE_SHIPPING_FEDEX_WEB_SERVICES_INT_EXPRESS_HANDLING_FEE); $this->types['INTERNATIONAL_PRIORITY_FREIGHT'] = array('icon' => '', 'handling_fee' => MODULE_SHIPPING_FEDEX_WEB_SERVICES_INT_EXPRESS_HANDLING_FEE); } // $this->types[] = 'SMART_POST'; // customer details $street_address = $order->delivery['street_address']; $street_address2 = $order->delivery['suburb']; $city = $order->delivery['city']; $state = tep_get_zone_code($order->delivery['country']['id'], $order->delivery['zone_id'], ''); if ($state == "QC") { $state = "PQ"; } $postcode = str_replace(array(' ', '-'), '', $order->delivery['postcode']); $country_id = $order->delivery['country']['iso_code_2']; $totals = $order->info['subtotal'] || $_SESSION['cart']->show_total(); $this->_setInsuranceValue($totals); $request['WebAuthenticationDetail'] = array('UserCredential' => array('Key' => $this->fedex_key, 'Password' => $this->fedex_pwd)); $request['ClientDetail'] = array('AccountNumber' => $this->fedex_act_num, 'MeterNumber' => $this->fedex_meter_num); $request['TransactionDetail'] = array('CustomerTransactionId' => ' *** Rate Request v9 using PHP ***'); // $request['RequestedShipment']['SmartPostDetail'] = array( // 'Indicia' => 'MEDIA_MAIL', // 'AncillaryEndorsement' => 'CARRIER_LEAVE_IF_NO_RESPONSE', // 'SpecialServices' => 'USPS_DELIVERY_CONFIRMATION', // 'HubId' => '5254', // 'CustomerManifestId' => 1101); // $request['RequestedShipment']['ServiceType'] = 'SMART_POST'; $request['Version'] = array('ServiceId' => 'crs', 'Major' => '9', 'Intermediate' => '0', 'Minor' => '0'); $request['ReturnTransitAndCommit'] = true; $request['RequestedShipment']['DropoffType'] = $this->_setDropOff(); // valid values REGULAR_PICKUP, REQUEST_COURIER, ... $request['RequestedShipment']['ShipTimestamp'] = date('c'); $request['RequestedShipment']['PackagingType'] = 'YOUR_PACKAGING'; // valid values FEDEX_BOX, FEDEX_PAK, FEDEX_TUBE, YOUR_PACKAGING, ... $request['RequestedShipment']['TotalInsuredValue'] = array('Ammount' => $this->insurance, 'Currency' => $_SESSION['currency']); $request['WebAuthenticationDetail'] = array('UserCredential' => array('Key' => $this->fedex_key, 'Password' => $this->fedex_pwd)); $request['ClientDetail'] = array('AccountNumber' => $this->fedex_act_num, 'MeterNumber' => $this->fedex_meter_num); // print_r($request['WebAuthenticationDetail']); // print_r($request['ClientDetail']); // exit; $request['RequestedShipment']['Shipper'] = array('Address' => array('StreetLines' => array(MODULE_SHIPPING_FEDEX_WEB_SERVICES_ADDRESS_1, MODULE_SHIPPING_FEDEX_WEB_SERVICES_ADDRESS_2), 'City' => MODULE_SHIPPING_FEDEX_WEB_SERVICES_CITY, 'StateOrProvinceCode' => MODULE_SHIPPING_FEDEX_WEB_SERVICES_STATE, 'PostalCode' => MODULE_SHIPPING_FEDEX_WEB_SERVICES_POSTAL, 'CountryCode' => $this->country)); $request['RequestedShipment']['Recipient'] = array('Address' => array('StreetLines' => array($street_address, $street_address2), 'City' => $city, 'PostalCode' => $postcode, 'CountryCode' => $country_id, 'Residential' => $order->delivery['company'] != '' ? false : true)); //customer county code if (in_array($country_id, array('US', 'CA'))) { $request['RequestedShipment']['Recipient']['StateOrProvinceCode'] = $state; } // print_r($request['RequestedShipment']['Recipient']) ; // exit; $request['RequestedShipment']['ShippingChargesPayment'] = array('PaymentType' => 'SENDER', 'Payor' => array('AccountNumber' => $this->fedex_act_num, 'CountryCode' => $this->country)); $request['RequestedShipment']['RateRequestTypes'] = 'LIST'; $request['RequestedShipment']['PackageDetail'] = 'INDIVIDUAL_PACKAGES'; $request['RequestedShipment']['RequestedPackageLineItems'] = array(); $dimensions_failed = false; // check for ready to ship field if (MODULE_SHIPPING_FEDEX_WEB_SERVICES_READY_TO_SHIP == 'true') { $products = $_SESSION['cart']->get_products(); $packages = array('default' => 0); $product_dim_type = 'in'; $new_shipping_num_boxes = 0; foreach ($products as $product) { $dimensions_query = "SELECT products_ready_to_ship, products_ship_sep FROM " . TABLE_PRODUCTS . " \r\n WHERE products_id = " . (int) $product['id'] . " \r\n LIMIT 1;"; $dimensions = tep_db_query($dimensions_query); if ($product_dimensions = tep_db_fetch_array($dimensions)) { if ($product_dimensions['products_ready_to_ship'] == 1 || $product_dimensions['products_ship_sep'] == 1) { for ($i = 1; $i <= $product['quantity']; $i++) { $packages[] = array('weight' => $product['weight']); } } else { $packages['default'] += $product['weight'] * $product['quantity']; } } } if (count($packages) > 1) { $za_tare_array = preg_split("/[:,]/", SHIPPING_BOX_WEIGHT); $zc_tare_percent = $za_tare_array[0]; $zc_tare_weight = $za_tare_array[1]; $za_large_array = preg_split("/[:,]/", SHIPPING_BOX_PADDING); $zc_large_percent = $za_large_array[0]; $zc_large_weight = $za_large_array[1]; } foreach ($packages as $id => $values) { if ($id === 'default') { // divide the weight by the max amount to be shipped (can be done inside loop as this occurance should only ever happen once // note $values is not an array if ($values == 0) { continue; } $shipping_num_boxes = ceil((double) $values / (double) SHIPPING_MAX_WEIGHT); if ($shipping_num_boxes < 1) { $shipping_num_boxes = 1; } $shipping_weight = round((double) $values / $shipping_num_boxes, 2); // 2 decimal places max for ($i = 0; $i < $shipping_num_boxes; $i++) { $new_shipping_num_boxes++; if (SHIPPING_MAX_WEIGHT <= $shipping_weight) { $shipping_weight = $shipping_weight + $shipping_weight * ($zc_large_percent / 100) + $zc_large_weight; } else { $shipping_weight = $shipping_weight + $shipping_weight * ($zc_tare_percent / 100) + $zc_tare_weight; } if ($shipping_weight <= 0) { $shipping_weight = 0.1; } $new_shipping_weight += $shipping_weight; $request['RequestedShipment']['RequestedPackageLineItems'][] = array('Weight' => array('Value' => $shipping_weight, 'Units' => MODULE_SHIPPING_FEDEX_WEB_SERVICES_WEIGHT)); } } else { // note $values is an array $new_shipping_num_boxes++; if ($values['weight'] <= 0) { $values['weight'] = 0.1; } $new_shipping_weight += $values['weight']; $request['RequestedShipment']['RequestedPackageLineItems'][] = array('Weight' => array('Value' => $values['weight'], 'Units' => MODULE_SHIPPING_FEDEX_WEB_SERVICES_WEIGHT)); } } $shipping_num_boxes = $new_shipping_num_boxes; if (!$shipping_num_boxes || $shipping_num_boxes == 0) { $shipping_num_boxes = 1; } $shipping_weight = round($new_shipping_weight / $shipping_num_boxes, 2); } else { // Zen Cart default method for calculating number of packages if ($shipping_weight == 0) { $shipping_weight = 0.1; } for ($i = 0; $i < $shipping_num_boxes; $i++) { $request['RequestedShipment']['RequestedPackageLineItems'][] = array('Weight' => array('Value' => $shipping_weight, 'Units' => MODULE_SHIPPING_FEDEX_WEB_SERVICES_WEIGHT)); } } $request['RequestedShipment']['PackageCount'] = $shipping_num_boxes; if (MODULE_SHIPPING_FEDEX_WEB_SERVICES_SATURDAY == 'true') { $request['RequestedShipment']['ServiceOptionType'] = 'SATURDAY_DELIVERY'; } if (MODULE_SHIPPING_FEDEX_WEB_SERVICES_SIGNATURE_OPTION >= 0 && $totals >= MODULE_SHIPPING_FEDEX_WEB_SERVICES_SIGNATURE_OPTION) { $request['RequestedShipment']['SpecialServicesRequested'] = 'SIGNATURE_OPTION'; } // echo '<!-- shippingWeight: ' . $shipping_weight . ' ' . $shipping_num_boxes . ' -->'; // echo '<!-- '; // echo '<pre>'; // print_r($request); // echo '</pre>'; // echo ' -->'; $response = $client->getRates($request); // echo '<!-- '; // echo '<pre>'; // print_r($response); // echo '</pre>'; // echo ' -->'; if ($response->HighestSeverity != 'FAILURE' && $response->HighestSeverity != 'ERROR' && is_array($response->RateReplyDetails) || is_object($response->RateReplyDetails)) { if (is_object($response->RateReplyDetails)) { $response->RateReplyDetails = get_object_vars($response->RateReplyDetails); } // echo '<pre>'; // print_r($response->RateReplyDetails); // echo '</pre>'; $show_box_weight = " (Total items: " . $shipping_num_boxes . ' pcs. Total weight: ' . number_format($shipping_weight * $shipping_num_boxes, 2) . ' ' . strtolower(MODULE_SHIPPING_FEDEX_WEB_SERVICES_WEIGHT) . 's.)'; $this->quotes = array('id' => $this->code, 'module' => $this->title . $show_box_weight, 'info' => $this->info()); // echo '<pre>'; // print_r($response->RateReplyDetails); // echo '</pre>'; // EXIT(); $methods = array(); // echo '<pre>'; // print_r($this->types); // echo '</pre>'; foreach ($response->RateReplyDetails as $rateReply) { if (array_key_exists($rateReply->ServiceType, $this->types) && ($method == '' || str_replace('_', '', $rateReply->ServiceType) == $method)) { if (MODULE_SHIPPING_FEDEX_WEB_SERVICES_RATES == 'LIST') { foreach ($rateReply->RatedShipmentDetails as $ShipmentRateDetail) { if ($ShipmentRateDetail->ShipmentRateDetail->RateType == 'PAYOR_LIST_PACKAGE') { $cost = $ShipmentRateDetail->ShipmentRateDetail->TotalNetCharge->Amount; $cost = (double) round(preg_replace('/[^0-9.]/', '', $cost), 2); } } } else { $cost = $rateReply->RatedShipmentDetails[0]->ShipmentRateDetail->TotalNetCharge->Amount; $cost = (double) round(preg_replace('/[^0-9.]/', '', $cost), 2); } if (in_array($rateReply->ServiceType, array('GROUND_HOME_DELIVERY', 'FEDEX_GROUND', 'INTERNATIONAL_GROUND'))) { // print_r($rateReply); $transitTime = ' (' . str_replace(array('_', 'one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight', 'nine', 'ten', 'eleven', 'twelve', 'thirteen', 'fourteeen'), array(' ', 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14), strtolower($rateReply->TransitTime)) . ')'; } $methods[] = array('id' => str_replace('_', '', $rateReply->ServiceType), 'title' => ucwords(strtolower(str_replace('_', ' ', $rateReply->ServiceType))) . $transitTime, 'cost' => $cost + (strpos($this->types[$rateReply->ServiceType]['handling_fee'], '%') ? $cost * (double) $this->types[$rateReply->ServiceType]['handling_fee'] / 100 : (double) $this->types[$rateReply->ServiceType]['handling_fee'])); } } // usort($methods, 'cmp'); $this->quotes['methods'] = $methods; if ($this->tax_class > 0) { $this->quotes['tax'] = tep_get_tax_rate($this->tax_class, $order->delivery['country']['id'], $order->delivery['zone_id']); } } else { $message = 'Error in processing transaction.<br /><br />'; foreach ($response->Notifications as $notification) { if (is_array($response->Notifications)) { $message .= $notification->Severity; $message .= ': '; $message .= $notification->Message . '<br />'; } else { $message .= $notification->Message . '<br />'; } } $this->quotes = array('module' => $this->title, 'error' => $message); } // po box hack by JD if (eregi("^P(.+)O(.+)BOX", $order->delivery['street_address']) || eregi("^PO BOX", $order->delivery['street_address']) || eregi("^P(.+)O(.+)BOX", $order->delivery['suburb']) || eregi("^[A-Z]PO", $order->delivery['street_address']) || eregi("^[A-Z]PO", $order->delivery['suburb'])) { $this->quotes = array('module' => $this->title, 'error' => '<font size=+2 color=red><b>Federal Express cannot ship to Post Office Boxes.<b></font><br>Use the Change Address button above to use a FedEx accepted street address.'); } // end po box hack by JD if (tep_not_null($this->icon)) { $this->quotes['icon'] = tep_image($this->icon, $this->title); } // echo '<!-- Quotes: '; // print_r($this->quotes); // print_r($_SESSION['shipping']); // echo ' -->'; return $this->quotes; }
function _FEDEXrequestMethods($data, $rate) { global $fedex_methods; $path_to_wsdl = dirname(__FILE__) . DS . 'fedex_rate.wsdl'; ini_set("soap.wsdl_cache_enabled", "0"); if (!class_exists('SoapClient')) { $app = JFactory::getApplication(); $app->enqueueMessage('The FEDEX shipping plugin needs the SOAP library installed but it seems that it is not available on your server. Please contact your web hosting to set it up.', 'error'); return false; } $client = new SoapClient($path_to_wsdl, array('exceptions' => false)); $shipment = array(); foreach ($data['methods'] as $k => $v) { $request['WebAuthenticationDetail'] = array('UserCredential' => array('Key' => $data['fedex_api_key'], 'Password' => $data['fedex_api_password'])); $request['ClientDetail'] = array('AccountNumber' => $data['fedex_account_number'], 'MeterNumber' => $data['fedex_meter_number']); $request['TransactionDetail'] = array('CustomerTransactionId' => ' *** Rate Request v10 using PHP ***'); $request['Version'] = array('ServiceId' => 'crs', 'Major' => '10', 'Intermediate' => '0', 'Minor' => '0'); $request['ReturnTransitAndCommit'] = true; $request['RequestedShipment']['DropoffType'] = 'REGULAR_PICKUP'; // valid values REGULAR_PICKUP, REQUEST_COURIER, ... $request['RequestedShipment']['ShipTimestamp'] = date('c'); $request['RequestedShipment']['ServiceType'] = $v; // valid values STANDARD_OVERNIGHT, PRIORITY_OVERNIGHT, FEDEX_GROUND, ... $request['RequestedShipment']['PackagingType'] = $data['packaging_type']; // valid values FEDEX_BOX, FEDEX_PAK, FEDEX_TUBE, YOUR_PACKAGING, ... $request['RequestedShipment']['TotalInsuredValue'] = array('Ammount' => $data['total_insured'], 'Currency' => 'USD'); $request['RequestedPackageDetailType'] = 'PACKAGE_SUMMARY'; $shipper = array('Contact' => array('PersonName' => $data['sender_company'], 'CompanyName' => $data['sender_company'], 'PhoneNumber' => $data['sender_phone']), 'Address' => array('StreetLines' => array($data['sender_address']), 'City' => $data['sender_city'], 'StateOrProvinceCode' => $data['sender_state'], 'PostalCode' => $data['sender_postcode'], 'CountryCode' => $data['country'])); $recipient_StateOrProvinceCode = ''; if (isset($data['recipient']->address_state->zone_code_2) && strlen($data['recipient']->address_state->zone_code_2) == 2) { $recipient_StateOrProvinceCode = $data['recipient']->address_state->zone_code_2; } elseif (strlen($data['recipient']->address_state->zone_code_3) == 2) { $recipient_StateOrProvinceCode = $data['recipient']->address_state->zone_code_3; } $recipient = array('Contact' => array('PersonName' => $data['recipient']->address_title . " " . $data['recipient']->address_firstname . " " . $data['recipient']->address_lastname, 'CompanyName' => $data['recipient']->address_company, 'PhoneNumber' => $data['recipient']->address_telephone), 'Address' => array('StreetLines' => array($data['recipient']->address_street), 'City' => $data['recipient']->address_city, 'StateOrProvinceCode' => $recipient_StateOrProvinceCode, 'PostalCode' => $data['recipient']->address_post_code, 'CountryCode' => $data['recipient']->address_country->zone_code_2, 'Residential' => true)); if (@$rate->shipping_params->destination_type == 'res') { $recipient['Address']['Residential'] = true; } if (@$rate->shipping_params->destination_type == 'com' || @$rate->shipping_params->destination_type == 'auto' && $v == 'FEDEX_GROUND') { $recipient['Address']['Residential'] = false; } $shippingChargesPayment = array('PaymentType' => 'SENDER', 'Payor' => array('AccountNumber' => $data['fedex_account_number'], 'CountryCode' => $data['country'])); $pkg_values = $this->xml2array('<root>' . $data['XMLpackage'] . '</root>'); $pkg_values = $pkg_values['root']; $pkg_count = count($pkg_values); $request['RequestedShipment']['Shipper'] = $shipper; $request['RequestedShipment']['Recipient'] = $recipient; $request['RequestedShipment']['ShippingChargesPayment'] = $shippingChargesPayment; $request['RequestedShipment']['RateRequestTypes'] = 'ACCOUNT'; if (empty($rate->shipping_params->rate_types) || $rate->shipping_params->rate_types != 'ACCOUNT') { $request['RequestedShipment']['RateRequestTypes'] = 'LIST'; } $request['RequestedShipment']['PackageCount'] = $pkg_count; $request['RequestedShipment']['RequestedPackageLineItems'] = $this->addPackageLineItem($pkg_values); if (@$rate->shipping_params->debug) { echo "<br/> Request {$v} : <br/>"; echo '<pre>' . var_export($request, true) . '</pre>'; } $response = $client->getRates($request); if (isset($response->HighestSeverity) && $response->HighestSeverity == "ERROR") { static $notif = false; if (!$notif && isset($response->Notifications->Message) && $response->Notifications->Message == 'Authentication Failed') { $app = JFactory::getApplication(); $app->enqueueMessage('FEDEX Authentication Failed'); $notif = true; } if (!$notif && !empty($response->Notifications->Message) && strpos($response->Notifications->Message, 'Service is not allowed') === FALSE) { $app = JFactory::getApplication(); $app->enqueueMessage('The FedEx request failed with the message : ' . $response->Notifications->Message); } } if (@$rate->shipping_params->debug) { echo "<br/> Response {$v} : <br/>"; echo '<pre>' . var_export($response, true) . '</pre>'; } if (!empty($response->HighestSeverity) && ($response->HighestSeverity == "SUCCESS" || $response->HighestSeverity == "NOTE" || $response->HighestSeverity == "WARNING")) { $code = ''; $notes = array(); if ($response->HighestSeverity == "NOTE" || $response->HighestSeverity == "WARNING") { $notes = $response->Notifications; } foreach ($this->fedex_methods as $k => $v) { if ($v['code'] == $response->RateReplyDetails->ServiceType) { $code = $v['code']; } } $delayType = hikashop_get('type.delay'); if (!empty($response->RateReplyDetails->DeliveryTimestamp)) { $timestamp = strtotime($response->RateReplyDetails->DeliveryTimestamp); } else { $timestamp = 0; $response->RateReplyDetails->DeliveryTimestamp = 0; } $totalNetPrice = 0; $discountAmount = 0; if (is_array($response->RateReplyDetails->RatedShipmentDetails)) { $totalNetPrice = $response->RateReplyDetails->RatedShipmentDetails[0]->ShipmentRateDetail->TotalNetCharge->Amount; if ($request['RequestedShipment']['RateRequestTypes'] != 'ACCOUNT') { $discountAmount = $response->RateReplyDetails->RatedShipmentDetails[0]->ShipmentRateDetail->TotalFreightDiscounts->Amount; } $shipment[] = array('value' => $totalNetPrice + $discountAmount, 'code' => $code, 'delivery_timestamp' => $timestamp, 'day' => $response->RateReplyDetails->DeliveryTimestamp, 'delivery_day' => date("m/d/Y", $timestamp), 'delivery_delay' => parent::displayDelaySECtoDAY($timestamp - strtotime('now'), 2), 'delivery_time' => date("H:i:s", $timestamp), 'currency_code' => $response->RateReplyDetails->RatedShipmentDetails[0]->ShipmentRateDetail->TotalNetCharge->Currency, 'old_currency_code' => $response->RateReplyDetails->RatedShipmentDetails[0]->ShipmentRateDetail->TotalNetCharge->Currency, 'notes' => $notes); } else { if (is_object($response->RateReplyDetails->RatedShipmentDetails)) { $totalNetPrice = $response->RateReplyDetails->RatedShipmentDetails->ShipmentRateDetail->TotalNetCharge->Amount; if ($request['RequestedShipment']['RateRequestTypes'] != 'ACCOUNT') { $discountAmount = $response->RateReplyDetails->RatedShipmentDetails->ShipmentRateDetail->TotalFreightDiscounts->Amount; } $shipment[] = array('value' => $totalNetPrice + $discountAmount, 'code' => $code, 'delivery_timestamp' => $timestamp, 'day' => $response->RateReplyDetails->DeliveryTimestamp, 'delivery_day' => date("m/d/Y", $timestamp), 'delivery_delay' => parent::displayDelaySECtoDAY($timestamp - strtotime('now'), 2), 'delivery_time' => date("H:i:s", $timestamp), 'currency_code' => $response->RateReplyDetails->RatedShipmentDetails->ShipmentRateDetail->TotalNetCharge->Currency, 'old_currency_code' => $response->RateReplyDetails->RatedShipmentDetails->ShipmentRateDetail->TotalNetCharge->Currency, 'notes' => $notes); } } } else { if (!empty($response->HighestSeverity) && $response->HighestSeverity == "ERROR") { static $errorsDisplayed = array(); $acceptedCodes = array(836); if (!empty($response->Notifications)) { foreach ($response->Notifications as $notif) { if (!is_object($notif)) { continue; } $errorCode = $notif->Code; if (!in_array($errorCode, $acceptedCodes)) { if (!isset($errorsDisplayed[$errorCode])) { $app = JFactory::getApplication(); $app->enqueueMessage($notif->Message); } $errorsDisplayed[$errorCode] = true; } } } } } } return $shipment; }
/** * Sends the RateRequest and returns the response * * @param ComplexType\RateRequest $rateRequest * @return stdClass */ public function getRateReply(ComplexType\RateRequest $rateRequeset) { return $this->_soapClient->getRates($rateRequeset->toArray()); }
/** * calculate_shipping function. * * @access public * @param mixed $package * @return void */ public function calculate_shipping($package) { global $woocommerce; $this->found_rates = array(); $package_requests = $this->get_package_requests($package); if ($package_requests) { try { $client = new SoapClient(plugin_dir_path(dirname(__FILE__)) . 'api/' . ($this->production ? 'production' : 'test') . '/RateService_v' . $this->rateservice_version . '.wsdl', array('trace' => 1)); foreach ($package_requests as $key => $request) { if ($this->debug) { $woocommerce->add_message('FedEx REQUEST: <pre style="height:200px">' . print_r($request, true) . '</pre>'); } $result = $client->getRates($request); if ($this->debug) { $woocommerce->add_message('FedEx RESPONSE: <pre style="height:200px">' . print_r($result, true) . '</pre>'); } } } catch (Exception $e) { $woocommerce->add_error(print_r($e, true)); return false; } if ($result) { if (!empty($result->RateReplyDetails)) { $rate_reply_details =& $result->RateReplyDetails; // Workaround for when an object is returned instead of array if (is_object($rate_reply_details) && isset($rate_reply_details->ServiceType)) { $rate_reply_details = array($rate_reply_details); } if (!is_array($rate_reply_details)) { return false; } foreach ($rate_reply_details as $quote) { if (is_array($quote->RatedShipmentDetails)) { foreach ($quote->RatedShipmentDetails as $i => $d) { if ($d->ShipmentRateDetail->RateType == $quote->ActualRateType) { $details =& $quote->RatedShipmentDetails[$i]; break; } } } else { $details =& $quote->RatedShipmentDetails; } if (empty($details)) { continue; } $rate_code = strval($quote->ServiceType); $rate_id = $this->id . ':' . $rate_code; $rate_name = (string) $this->services[$quote->ServiceType]; $rate_cost = (double) $details->ShipmentRateDetail->TotalNetCharge->Amount; $this->prepare_rate($rate_code, $rate_id, $rate_name, $rate_cost); } } } } // Ensure rates were found for all packages if ($this->found_rates) { foreach ($this->found_rates as $key => $value) { if ($value['packages'] < sizeof($package_requests)) { unset($this->found_rates[$key]); } } } // Add rates if ($this->found_rates) { if ($this->offer_rates == 'all') { uasort($this->found_rates, array($this, 'sort_rates')); foreach ($this->found_rates as $key => $rate) { $this->add_rate($rate); } } else { $cheapest_rate = ''; foreach ($this->found_rates as $key => $rate) { if (!$cheapest_rate || $cheapest_rate['cost'] > $rate['cost']) { $cheapest_rate = $rate; } } $cheapest_rate['label'] = $this->title; $this->add_rate($cheapest_rate); } } }
function rates() { $this->CI->load->library('session'); // get customer info $customer = $this->CI->jcart->customer(); $customer_address = $customer['ship_address']; // Weight of order $weight = $this->CI->jcart->order_weight(); // retrieve settings $settings = $this->CI->Settings_model->get_settings('fedex'); //check if we're enabled if (!$settings['enabled'] || $settings['enabled'] < 1) { return array(); } $key = $settings['key']; $password = $settings['password']; $shipAccount = $settings['shipaccount']; $meter = $settings['meter']; $dropofftype = $settings['dropofftype']; $service = explode(',', $settings['service']); $package = $settings['package']; $handling_method = $settings['handling_method']; $handling_amount = $settings['handling_amount']; $pkg_width = $settings['width']; $pkg_height = $settings['height']; $pkg_length = $settings['length']; $insurance = $settings['insurance']; $billAccount = $shipAccount; // Build Request ini_set("soap.wsdl_cache_enabled", "0"); $client = new SoapClient($this->path_to_wsdl, array('trace' => 1)); // Refer to http://us3.php.net/manual/en/ref.soap.php for more information $request['WebAuthenticationDetail'] = array('UserCredential' => array('Key' => $key, 'Password' => $password)); $request['ClientDetail'] = array('AccountNumber' => $shipAccount, 'MeterNumber' => $meter); $request['TransactionDetail'] = array('CustomerTransactionId' => '*** Rate Request v14 using PHP ***'); $request['Version'] = array('ServiceId' => 'crs', 'Major' => '14', 'Intermediate' => '0', 'Minor' => '0'); $request['ReturnTransitAndCommit'] = false; $request['RequestedShipment']['RequestedCurrency'] = $this->CI->config->item('currency'); $request['RequestedShipment']['DropoffType'] = $dropofftype; $request['RequestedShipment']['ShipTimestamp'] = date('c'); $request['RequestedShipment']['PackagingType'] = $package; if ($insurance == 'yes') { $request['RequestedShipment']['TotalInsuredValue'] = array('Ammount' => $this->CI->jcart->order_insurable_value(), 'Currency' => $this->CI->config->item('currency')); } $request['RequestedShipment']['Shipper'] = array('Contact' => array('CompanyName' => $this->CI->config->item('company_name'), 'EMailAddress' => $this->CI->config->item('email')), 'Address' => array('StreetLines' => array($this->CI->config->item('address1'), $this->CI->config->item('address2')), 'City' => $this->CI->config->item('city'), 'StateOrProvinceCode' => $this->CI->config->item('state'), 'PostalCode' => $this->CI->config->item('zip'), 'CountryCode' => $this->CI->config->item('country'))); $request['RequestedShipment']['Recipient'] = array('Contact' => array('PersonName' => "{$customer_address['firstname']} {$customer_address['lastname']}", 'CompanyName' => $customer_address['company'], 'PhoneNumber' => $customer_address['phone']), 'Address' => array('StreetLines' => array($customer_address['address1'], $customer_address['address2']), 'City' => $customer_address['city'], 'StateOrProvinceCode' => $customer_address['zone'], 'PostalCode' => $customer_address['zip'], 'CountryCode' => $customer_address['country_code'])); $request['RequestedShipment']['RateRequestTypes'] = 'LIST'; $request['RequestedShipment']['PackageCount'] = '1'; $request['RequestedShipment']['RequestedPackageLineItems'] = array('SequenceNumber' => 1, 'GroupPackageCount' => 1, 'Weight' => array('Value' => $this->CI->jcart->order_weight(), 'Units' => $this->CI->config->item('weight_unit')), 'Dimensions' => array('Length' => $pkg_length, 'Width' => $pkg_width, 'Height' => $pkg_height, 'Units' => $this->CI->config->item('dimension_unit'))); // Send the request to FedEx $response = $client->getRates($request); // Handle response if ($response->HighestSeverity != 'FAILURE' && $response->HighestSeverity != 'ERROR') { if (!is_array(@$response->RateReplyDetails)) { return array(); // No Results } foreach ($response->RateReplyDetails as $rateReply) { if (in_array($rateReply->ServiceType, $service)) { $amount = $rateReply->RatedShipmentDetails[0]->ShipmentRateDetail->TotalNetCharge->Amount; if (is_numeric($handling_amount)) { if ($handling_method == 'price') { $amount += $handling_amount; } elseif ($handling_method == 'percent') { $amount += $amount * ($handling_amount / 100); } } $rates[$this->service_list[$rateReply->ServiceType]] = number_format($amount, 2, ".", ","); } } return $rates; } else { return array(); // fail } }
function get_live_rates($option_value = "ALL") { // manually set the weight at 1lb as a minimum $this->EE =& get_instance(); $this->EE->load->library('cartthrob_shipping_plugins'); $this->core->cart->set_custom_data("shipping_error", ""); if ($this->plugin_settings('mode') == "dev") { $wsdl_path = PATH_THIRD . "cartthrob/third_party/lib/fedex/wsdl/RateService_v9_dev_version.wsdl"; } else { $wsdl_path = PATH_THIRD . "cartthrob/third_party/lib/fedex/wsdl/RateService_v9.wsdl"; } $client = new SoapClient($wsdl_path, array('trace' => 1)); // Refer to http://us3.php.net/manual/en/ref.soap.php for more information $shipping = array('error_message' => NULL, 'price' => array(), 'option_value' => array(), 'option_name' => array()); if (!$this->plugin_settings('access_key') || !$this->plugin_settings('account_number') || !$this->plugin_settings('password') || !$this->plugin_settings('meter_number')) { $shipping['error_message'] = $this->EE->lang->line('shipping_settings_not_configured'); $this->core->cart->set_custom_data("shipping_error", $shipping['error_message']); $this->core->cart->save(); return $shipping; } /******************************************* ASSEMBLE REQUEST & SEND *********************************/ $request['WebAuthenticationDetail'] = array('UserCredential' => array('Key' => $this->plugin_settings('access_key'), 'Password' => $this->plugin_settings('password'))); $request['ClientDetail'] = array('AccountNumber' => $this->plugin_settings('account_number'), 'MeterNumber' => $this->plugin_settings('meter_number')); $request['TransactionDetail'] = array('CustomerTransactionId' => ' *** Rate Available Services Request v9 using PHP ***'); $request['Version'] = array('ServiceId' => 'crs', 'Major' => '9', 'Intermediate' => '0', 'Minor' => '0'); $request['ReturnTransitAndCommit'] = true; $request['RequestedShipment']['DropoffType'] = $this->plugin_settings('rate_chart'); // valid values REGULAR_PICKUP, REQUEST_COURIER, ... $request['RequestedShipment']['ShipTimestamp'] = date('c'); $orig_state = $this->plugin_settings('origination_state') ? $this->plugin_settings('origination_state') : $this->EE->cartthrob_shipping_plugins->customer_location_defaults('state'); //@TODO add state $orig_zip = $this->plugin_settings('origination_zip') ? $this->plugin_settings('origination_zip') : $this->EE->cartthrob_shipping_plugins->customer_location_defaults("zip"); // @TODO add zip $orig_country_code = $this->plugin_settings('orig_country_code') ? $this->plugin_settings('orig_country_code') : $this->EE->cartthrob_shipping_plugins->customer_location_defaults("country_code"); //@TODO add country $orig_res_com = $this->plugin_settings('origination_res_com') == "RES" ? 1 : 0; $destination_res_com = $this->plugin_settings('destination_res_com') == "RES" ? 1 : 0; $request['RequestedShipment']['TotalInsuredValue'] = array('Amount' => $this->plugin_settings('insurance_default'), 'Currency' => $this->plugin_settings('insurance_currency')); $request['RequestedShipment']['Shipper'] = array('Address' => array('StreetLines' => array($this->plugin_settings('origination_address'), $this->plugin_settings('origination_address2')), 'City' => $this->plugin_settings('origination_city'), 'StateOrProvinceCode' => $orig_state, 'PostalCode' => $orig_zip, 'CountryCode' => $this->EE->cartthrob_shipping_plugins->alpha2_country_code($orig_country_code), 'Residential' => $orig_res_com)); if ($option_value == "SMART_POST") { $request['RequestedShipment']['SmartPostDetail'] = array('Indicia' => $this->plugin_settings('sp_indicia'), 'AncillaryEndorsement' => $this->plugin_settings('sp_ancillary_services'), 'HubId' => $this->plugin_settings('hubid'), 'CustomerManifestId' => date("md0B")); } $request['RequestedShipment']['Recipient'] = array('Address' => array('StreetLines' => array($this->EE->cartthrob_shipping_plugins->customer_location_defaults("address"), $this->EE->cartthrob_shipping_plugins->customer_location_defaults('address2')), 'City' => $this->EE->cartthrob_shipping_plugins->customer_location_defaults("city", NULL), 'StateOrProvinceCode' => $this->EE->cartthrob_shipping_plugins->customer_location_defaults("state", NULL), 'PostalCode' => $this->EE->cartthrob_shipping_plugins->customer_location_defaults("zip", NULL), 'CountryCode' => $this->EE->cartthrob_shipping_plugins->alpha2_country_code($this->EE->cartthrob_shipping_plugins->customer_location_defaults("country_code")), 'Residential' => $destination_res_com)); $request['RequestedShipment']['ShippingChargesPayment'] = array('PaymentType' => 'SENDER', 'Payor' => array('AccountNumber' => $this->plugin_settings('account_number'), 'CountryCode' => $this->EE->cartthrob_shipping_plugins->alpha2_country_code($orig_country_code))); $request['RequestedShipment']['RateRequestTypes'] = 'ACCOUNT'; $request['RequestedShipment']['RateRequestTypes'] = 'LIST'; $request['RequestedShipment']['PackageCount'] = $this->core->cart->count_all(); $request['RequestedShipment']['PackageDetail'] = 'INDIVIDUAL_PACKAGES'; // Or PACKAGE_SUMMARY $count = 0; foreach ($this->core->cart->items() as $key => $item) { $request['RequestedShipment']['RequestedPackageLineItems'][$count] = array('Weight' => array('Value' => ($item->weight() > 0 ? $item->weight() : 1) * $item->quantity(), 'Units' => $this->plugin_settings('weight_code')), 'Dimensions' => array('Length' => $item->item_options('length') ? $item->item_options('length') : $this->plugin_settings('def_length'), 'Width' => $item->item_options('width') ? $item->item_options('width') : $this->plugin_settings('def_width'), 'Height' => $item->item_options('height') ? $item->item_options('height') : $this->plugin_settings('def_height'), 'Units' => $this->plugin_settings('length_code'))); $count++; } try { if (setEndpoint('changeEndpoint')) { $newLocation = $client->__setLocation(setEndpoint('endpoint')); } $response = $client->getRates($request); if ($response->HighestSeverity != 'FAILURE' && $response->HighestSeverity != 'ERROR' && !empty($response->RateReplyDetails)) { foreach ($response->RateReplyDetails as $rateReply) { // if only ONE rate is returned.... then $rateReply is not an array, and we need to go up to the $response if (is_string($rateReply)) { if (isset($response->RateReplyDetails->RatedShipmentDetails[0]->ShipmentRateDetail->TotalNetCharge->Amount)) { $shipping['error_message'] = NULL; $shipping['price'][] = number_format($response->RateReplyDetails->RatedShipmentDetails[0]->ShipmentRateDetail->TotalNetCharge->Amount, 2, ".", ","); $shipping['option_value'][] = $response->RateReplyDetails->ServiceType; $shipping['option_name'][] = $this->shipping_methods($response->RateReplyDetails->ServiceType); } // breaking, because any additional iteration will continue to return the result above. break; } else { if (isset($rateReply->RatedShipmentDetails[0]->ShipmentRateDetail->TotalNetCharge->Amount)) { $shipping['error_message'] = NULL; $shipping['price'][] = number_format($rateReply->RatedShipmentDetails[0]->ShipmentRateDetail->TotalNetCharge->Amount, 2, ".", ","); $shipping['option_value'][] = $rateReply->ServiceType; $shipping['option_name'][] = $this->shipping_methods($rateReply->ServiceType); } } } } else { $shipping = array('error_message' => $this->build_errors($response->Notifications), 'price' => array(), 'option_value' => array(), 'option_name' => array()); } } catch (SoapFault $exception) { $shipping = array('error_message' => $exception->faultcode . " " . $exception->faultstring . " " . $this->build_faults($exception), 'price' => array(), 'option_value' => array(), 'option_name' => array()); } // CHECKING THE PRESELECTED OPTIONS THAT ARE AVAILABLE $available_shipping = array(); foreach ($shipping['option_value'] as $key => $value) { // REMOVE THE ONES THAT ARE NOT OPTIONS if ($this->plugin_settings($value) != "n") { $available_shipping['price'][$key] = $shipping['price'][$key]; $available_shipping['option_value'][$key] = $shipping['option_value'][$key]; $available_shipping['option_name'][$key] = $shipping['option_name'][$key]; } } if ($shipping['error_message']) { $available_shipping['error_message'] = $shipping['error_message']; $this->core->cart->set_custom_data("shipping_error", $shipping['error_message']); } // update cart shipping hash $this->cart_hash($available_shipping); // if there's no errors, but we removed all of the shipping options, it's because none of the values were configured on the backend. We need to warn. if (empty($available_shipping['error_message']) && empty($available_shipping['price']) && !empty($available_shipping)) { $available_shipping['error_message'] = "Shipping options compatible with your location: (" . $shipping_address . " " . $shipping_address2 . " " . $shipping_city . " " . ($shipping_state ? "," . $shipping_state : "") . " " . $shipping_zip . " " . $dest_country_code . ") have not been configured in the cart settings. Please contact the webmaster"; if ($dest_country_code != $orig_country_code) { $available_shipping['error_message'] .= " International shipping options may need to be added. "; } $this->core->cart->set_custom_data("shipping_error", $available_shipping['error_message']); } $this->core->cart->save(); return $available_shipping; }
public function getRates($items) { global $order; require_once BASE . 'external/fedex-php/fedex-common.php'; //require_once('fedex-common.php'); //The WSDL is not included with the sample code. //Please include and reference in $path_to_wsdl variable. $path_to_wsdl = BASE . 'external/fedex-php/RateService_v9.wsdl'; ini_set("soap.wsdl_cache_enabled", "0"); $client = new SoapClient($path_to_wsdl, array('trace' => 1)); // Refer to http://us3.php.net/manual/en/ref.soap.php for more information $request['WebAuthenticationDetail'] = array('UserCredential' => array('Key' => $this->configdata['fedex_key'], 'Password' => $this->configdata['fedex_password'])); $request['ClientDetail'] = array('AccountNumber' => $this->configdata['fedex_account_number'], 'MeterNumber' => $this->configdata['fedex_meter_number']); //$request['TransactionDetail'] = array('CustomerTransactionId' => ' *** Rate Available Services Request v9 using PHP ***'); $request['TransactionDetail'] = array('CustomerTransactionId' => md5("Probody " . date('c'))); $request['Version'] = array('ServiceId' => 'crs', 'Major' => '9', 'Intermediate' => '0', 'Minor' => '0'); $request['ReturnTransitAndCommit'] = true; $request['RequestedShipment']['DropoffType'] = 'REGULAR_PICKUP'; // valid values REGULAR_PICKUP, REQUEST_COURIER, ... $request['RequestedShipment']['ShipTimestamp'] = date('c'); // Service Type and Packaging Type are not passed in the request $this->configdata['shipfrom']['StreetLines'][] = $this->configdata['shipfrom']['address1']; if (!empty($this->configdata['shipfrom']['address2'])) { $this->configdata['shipfrom']['StreetLines'][] = $this->configdata['shipfrom']['address2']; } if (!empty($this->configdata['shipfrom']['address3'])) { $this->configdata['shipfrom']['StreetLines'][] = $this->configdata['shipfrom']['address3']; } unset($this->configdata['shipfrom']['address1']); unset($this->configdata['shipfrom']['address2']); unset($this->configdata['shipfrom']['address3']); unset($this->configdata['shipfrom']['state']); unset($this->configdata['shipfrom']['country']); //eDebug($this->configdata['shipfrom'],true); $request['RequestedShipment']['Shipper'] = array('Address' => $this->configdata['shipfrom']); // get the current shippingmethod and format the address for ups $currentmethod = $order->getCurrentShippingMethod(); $request['RequestedShipment']['Recipient'] = array('Address' => $this->formatAddress($currentmethod)); $request['RequestedShipment']['ShippingChargesPayment'] = array('PaymentType' => 'SENDER', 'Payor' => array('AccountNumber' => $this->configdata['fedex_account_number'], 'CountryCode' => $this->configdata['shipfrom']['CountryCode'])); $request['RequestedShipment']['RateRequestTypes'] = 'ACCOUNT'; $request['RequestedShipment']['RateRequestTypes'] = 'LIST'; $request['RequestedShipment']['PackageDetail'] = 'INDIVIDUAL_PACKAGES'; // set the standard box sizes. $box_width = empty($this->configdata['default_width']) ? 0 : $this->configdata['default_width']; $box_height = empty($this->configdata['default_height']) ? 0 : $this->configdata['default_height']; $box_length = empty($this->configdata['default_length']) ? 0 : $this->configdata['default_length']; $box_volume = $box_height * $box_width * $box_length; // set some starting/default values $weight = 0; $volume = 0; $count = 0; $package_items = array(); // loop each product in this shipment and create the packages foreach ($items->orderitem as $item) { for ($i = 0; $i < $item->quantity; $i++) { if (empty($item->product->no_shipping) && $item->product->requiresShipping == true) { $lbs = empty($item->product->weight) ? $this->configdata['default_max_weight'] : $item->product->weight; $width = empty($item->product->width) ? $this->configdata['default_width'] : $item->product->width; $height = empty($item->product->height) ? $this->configdata['default_height'] : $item->product->height; $length = empty($item->product->length) ? $item->product->width : $item->product->length; $length = empty($length) ? $this->configdata['default_length'] : $length; $package_items[$count]->volume = $width * $length * $height; $package_items[$count]->weight = $lbs; $package_items[$count]->w = $width; $package_items[$count]->h = $height; $package_items[$count]->l = $length; $package_items[$count]->name = $item->product->title; $count += 1; } } } //eDebug($package_items); // sort the items by volume $package_items = expSorter::sort(array('array' => $package_items, 'sortby' => 'volume', 'order' => 'DESC')); // loop over all the items and try to put them into packages in a semi-intelligent manner // we have sorted the list of items from biggest to smallest. Items with a volume larger than // our standard box will generate a package with the dimensions set to the size of the item. // otherwise we just keep stuffing items in the current package until we can't find anymore that will // fit. Once that happens we close that package and start a new one...repeating until we are out of items $space_left = $box_volume; //eDebug($space_left); $total_weight = 0; $box_count = 0; $fedexItemArray = array(); while (!empty($package_items)) { $no_more_room = false; $used = array(); foreach ($package_items as $idx => $pi) { /*if ($pi->volume > $box_volume) { # echo $pi->name."is too big for standard box <br>"; # eDebug('created OVERSIZED package with weight of '.$pi->weight); # eDebug('dimensions: height: '.$pi->h." width: ".$pi->w." length: ".$pi->l); # echo "<hr>"; $weight = $pi->weight > 1 ? $pi->weight : 1; $upsRate->package(array('description'=>'shipment','weight'=>$weight,'code'=>'02','length'=>$pi->l,'width'=>$pi->w,'height'=>$pi->h)); $used[] = $idx; $no_more_room = false; } elseif($pi->volume <= $space_left) {*/ if ($pi->volume >= $space_left) { $no_more_room = true; break; } $space_left = $space_left - $pi->volume; $total_weight += $pi->weight; # echo "Adding ".$pi->name."<br>"; # echo "Space left in current box: ".$space_left."<br>"; $used[] = $idx; //} } // remove the used items from the array so they wont be there on the next go around. foreach ($used as $idx) { unset($package_items[$idx]); } // if there is no more room left on the current package or we are out of items then // add the package to the shippment. if ($no_more_room || empty($package_items) && $total_weight > 0) { $box_count++; $total_weight = $total_weight > 1 ? $total_weight : 1; # eDebug('created standard sized package with weight of '.$total_weight); # echo "<hr>"; //$upsRate->package(array('description'=>'shipment','weight'=>$total_weight,'code'=>'02','length'=>$box_length,'width'=>$box_width,'height'=>$box_height)); $fedexItemArray[] = array('Weight' => array('Value' => $total_weight, 'Units' => 'LB'), 'Dimensions' => array('Length' => $box_length, 'Width' => $box_width, 'Height' => $box_height, 'Units' => 'IN')); $space_left = $box_volume; $total_weight = 0; } } //eDebug($fedexItemArray,true); //eDebug($box_count . " boxes in this shipment."); $request['RequestedShipment']['PackageCount'] = "{$box_count}"; $request['RequestedShipment']['RequestedPackageLineItems'] = $fedexItemArray; //eDebug($request['RequestedShipment']['PackageCount']); //eDebug($request['RequestedShipment']['RequestedPackageLineItems'],true); /*array( '0' => array( 'Weight' => array( 'Value' => 2.0, 'Units' => 'LB'), 'Dimensions' => array( 'Length' => 10, 'Width' => 10, 'Height' => 3, 'Units' => 'IN')), '1' => array( 'Weight' => array( 'Value' => 5.0, 'Units' => 'LB'), 'Dimensions' => array( 'Length' => 20, 'Width' => 20, 'Height' => 10, 'Units' => 'IN') ) ); */ try { if (setEndpoint('changeEndpoint')) { $newLocation = $client->__setLocation(setEndpoint('endpoint')); } $response = $client->getRates($request); //eDebug($response,true); if ($response->HighestSeverity != 'FAILURE' && $response->HighestSeverity != 'ERROR') { //echo 'Rates for following service type(s) were returned.'. Newline. Newline; //echo '<table border="1">'; //echo '<tr><td>Service Type</td><td>Amount</td><td>Delivery Date</td>'; $rates = array(); //array( //"03"=>array("id"=>"03", "title"=>"UPS Ground", "cost"=>5.00), //"02"=>array("id"=>"02", "title"=>"UPS Second Day Air", "cost"=>10.00), //"01"=>array("id"=>"01", "title"=>"UPS Next Day Air", "cost"=>20.00) //); /*eDebug($this->configdata['shipping_methods'],true); eDebug($response -> RateReplyDetails,true);*/ foreach ($response->RateReplyDetails as $rateReply) { if (in_array($rateReply->ServiceType, $this->configdata['shipping_methods'])) { $rates[$rateReply->ServiceType] = array("id" => $rateReply->ServiceType, "title" => $this->shippingmethods[$rateReply->ServiceType], "cost" => number_format($rateReply->RatedShipmentDetails[0]->ShipmentRateDetail->TotalNetCharge->Amount, 2, ".", ",")); } /* $amount = '<td>$' . number_format($rateReply->RatedShipmentDetails[0]->ShipmentRateDetail->TotalNetCharge->Amount,2,".",",") . '</td>'; if(array_key_exists('DeliveryTimestamp',$rateReply)){ $deliveryDate= '<td>' . $rateReply->DeliveryTimestamp . '</td>'; }else{ $deliveryDate= '<td>' . $rateReply->TransitTime . '</td>'; } echo $serviceType . $amount. $deliveryDate; echo '</tr>';*/ } //eDebug($rates,true); return array_reverse($rates); } else { printError($client, $response); } writeToLog($client); // Write to log file } catch (SoapFault $exception) { printFault($exception, $client); } }
/** * Get available delivery types for selected items. Each type needs * to return estimated delivery time, cost and name of service. * * @param array $items * @param array $shipper * @param array $recipient * @param string $transaction_id * @return array */ public function getDeliveryTypes($items, $shipper, $recipient, $transaction_id, $preferred_currency) { $shop = shop::getInstance(); $debug = $shop->isDebug(); $result = array(); $request = array(); $client = new SoapClient($this->wsdl[FedEx_DeliveryMethod::RATE_SERVICE], array('trace' => $debug)); if (empty($shipper)) { throw new Exception('Missing shipper information!'); } if (empty($recipient)) { throw new Exception('Missing recipient information!'); } // populate request header $this->_populateCredentials($request); $this->_populateClientDetails($request); $this->_populateTransactionDetails($request, $transaction_id); $this->_populateVersionInformation($request, FedEx_DeliveryMethod::RATE_SERVICE); // add remaining request information $request['ReturnTransitAndCommit'] = true; // request tranzit time and commit data $request['RequestedShipment'] = array('RateRequestTypes' => 'PREFERRED'); $request['RequestedShipment']['DropoffType'] = 'REGULAR_PICKUP'; $request['RequestedShipment']['ShipTimestamp'] = date('c'); $request['RequestedShipment']['PackagingType'] = 'YOUR_PACKAGING'; $request['RequestedShipment']['PreferredCurrency'] = $preferred_currency; $request['RequestedShipment']['Shipper'] = array('Contact' => array(), 'Address' => array('StreetLines' => $shipper['street'], 'City' => $shipper['city'], 'PostalCode' => $shipper['zip_code'], 'StateOrProvinceCode' => $shipper['state'], 'CountryCode' => $shipper['country'])); $request['RequestedShipment']['Recipient'] = array('Contact' => array(), 'Address' => array('StreetLines' => $recipient['street'], 'City' => $recipient['city'], 'PostalCode' => $recipient['zip_code'], 'StateOrProvinceCode' => strlen($recipient['state']) >= 2 ? '' : $recipient['state'], 'CountryCode' => $recipient['country'])); $request['RequestedShipment']['ShippingChargesPayment'] = array('PaymentType' => 'SENDER', 'Payor' => array('ResponsibleParty' => array('AccountNumber' => $this->parent->settings['fedex_account'], 'CountryCode' => $shipper['country']))); // get package id's and count items for each package $packages = array(); foreach ($items as $item) { $package_id = $item['package']; if (array_key_exists($package_id, $packages)) { $packages[$package_id]++; } else { $packages[$package_id] = 1; } } // append all the items to list $fedex_items = array(); foreach ($items as $item) { $new_item = array('Weight' => array('Value' => $item['weight'], 'Units' => 'KG'), 'Dimensions' => array('Width' => $item['width'], 'Height' => $item['height'], 'Length' => $item['length'], 'Units' => 'CM')); $new_item['SequenceNumber'] = $item['package']; $new_item['GroupPackageCount'] = $packages[$item['package']]; $fedex_items[] = $new_item; } $request['RequestedShipment']['PackageCount'] = count($packages); $request['RequestedShipment']['RequestedPackageLineItems'] = $fedex_items; // get response from server $response = $client->getRates($request); if (count($response->RateReplyDetails) > 0) { foreach ($response->RateReplyDetails as $type) { // extract data from response $id = $type->ServiceType; $name = $this->parent->getLanguageConstant($id); $timestamp = strtotime($type->DeliveryTimestamp); $amount = $type->RatedShipmentDetails[0]->ShipmentRateDetail->TotalNetCharge->Amount; $currency = $type->RatedShipmentDetails[0]->ShipmentRateDetail->TotalNetCharge->Currency; // add new delivery type to result $result[] = array(!empty($name) ? $name : $id, $amount, $currency, null, $timestamp ? $timestamp : null); } } return $result; }
private function _processRequest($address) { require_once DIR_EXT . 'default_fedex/core/lib/fedex_func.php'; if ($this->config->get('default_fedex_test')) { $path_to_wsdl = DIR_EXT . 'default_fedex/core/lib/RateService_v9_test.wsdl'; } else { $path_to_wsdl = DIR_EXT . 'default_fedex/core/lib/RateService_v9.wsdl'; } $client = new SoapClient($path_to_wsdl, array('trace' => 1)); // Refer to http://us3.php.net/manual/en/ref.soap.php for more information //Fedex Key $fedex_key = $this->config->get('default_fedex_key'); //Fedex Password $fedex_password = $this->config->get('default_fedex_password'); //Fedex Meter Id $fedex_meter_id = $this->config->get('default_fedex_meter'); //Fedex Account $fedex_account = $this->config->get('default_fedex_account'); //Quote Type Residential or commercial $fedex_quote = $this->config->get('default_fedex_quote_type'); if ($fedex_quote == 'residential') { $fedex_residential = true; } else { $fedex_residential = false; } $fedex_addr = $this->config->get('default_fedex_address'); $fedex_city = $this->config->get('default_fedex_city'); $fedex_state = $this->config->get('default_fedex_state'); $fedex_zip = $this->config->get('default_fedex_zip'); $fedex_country = $this->config->get('default_fedex_country'); $fedex_add_chrg = $this->config->get('default_fedex_add_chrg'); //Recepient Info $shipping_address = $address; $request = array(); $product_weight = 1.0; $product_length = 1.0; $product_width = 1.0; $product_height = 1.0; $product_quantity = 1; $product_total = 1.0; //BUILD REQUEST START $request['WebAuthenticationDetail'] = array('UserCredential' => array('Key' => $fedex_key, 'Password' => $fedex_password)); $request['ClientDetail'] = array('AccountNumber' => $fedex_account, 'MeterNumber' => $fedex_meter_id); $request['TransactionDetail'] = array('CustomerTransactionId' => ' *** Rate Request v9 using PHP ***'); $request['Version'] = array('ServiceId' => 'crs', 'Major' => '9', 'Intermediate' => '0', 'Minor' => '0'); $request['ReturnTransitAndCommit'] = true; $request['RequestedShipment']['DropoffType'] = 'REGULAR_PICKUP'; // valid values REGULAR_PICKUP, REQUEST_COURIER, ... $request['RequestedShipment']['ShipTimestamp'] = date('c'); //$request['RequestedShipment']['ServiceType'] = 'GROUND_HOME_DELIVERY'; // valid values STANDARD_OVERNIGHT, PRIORITY_OVERNIGHT, FEDEX_GROUND, ... $request['RequestedShipment']['PackagingType'] = 'YOUR_PACKAGING'; // valid values FEDEX_BOX, FEDEX_PAK, FEDEX_TUBE, YOUR_PACKAGING, ... $request['RequestedShipment']['TotalInsuredValue'] = array('Ammount' => $product_total, 'Currency' => 'USD'); $request['RequestedShipment']['Shipper'] = array('Address' => array('StreetLines' => array($fedex_addr), 'City' => $fedex_city, 'StateOrProvinceCode' => $fedex_state, 'PostalCode' => $fedex_zip, 'CountryCode' => $fedex_country)); $request['RequestedShipment']['Recipient'] = array('Address' => array('StreetLines' => array($shipping_address['address_1'], $shipping_address['address_2']), 'City' => $shipping_address['city'], 'StateOrProvinceCode' => $shipping_address['zone_code'], 'PostalCode' => $shipping_address['postcode'], 'CountryCode' => $shipping_address['iso_code_2'], 'Residential' => $fedex_residential)); $request['RequestedShipment']['ShippingChargesPayment'] = array('PaymentType' => 'SENDER', 'Payor' => array('AccountNumber' => $fedex_account, 'CountryCode' => 'US')); $request['RequestedShipment']['RateRequestTypes'] = 'ACCOUNT'; $request['RequestedShipment']['RateRequestTypes'] = 'LIST'; $request['RequestedShipment']['PackageCount'] = $product_quantity; $request['RequestedShipment']['PackageDetail'] = 'INDIVIDUAL_PACKAGES'; // Or PACKAGE_SUMMARY for ($q = 0; $q < $product_quantity; $q++) { $request['RequestedShipment']['RequestedPackageLineItems'] = array('Weight' => array('Value' => $product_weight, 'Units' => 'LB'), 'Dimensions' => array('Length' => $product_length, 'Width' => $product_width, 'Height' => $product_height, 'Units' => 'IN')); } $error_msg = ''; try { if (setEndpoint('changeEndpoint')) { $newLocation = $client->__setLocation(setEndpoint('endpoint')); } $response = $client->getRates($request); if ($response->HighestSeverity == 'FAILURE' || $response->HighestSeverity == 'ERROR') { $error_msg = $this->_get_notifications($response->Notifications); } } catch (SoapFault $exception) { $error_text = 'Fault' . "<br>\n"; $error_text .= "Code:" . $exception->faultcode . "\n"; $error_text .= "String:" . $exception->faultstring . "\n"; $error_text .= $client; $this->message->saveError('fedex extension soap error', $error_text); $this->log->write($error_text); } return array('error' => $error_msg); }
function rates() { $this->CI->load->library('session'); // get customer info $customer = $this->CI->go_cart->customer(); $customer_address = $customer['ship_address']; // Weight of order $weight = $this->CI->go_cart->order_weight(); // retrieve settings $settings = $this->CI->Settings_model->get_settings('fedex'); //check if we're enabled if (!$settings['enabled'] || $settings['enabled'] < 1) { return array(); } $key = $settings['key']; $password = $settings['password']; $shipAccount = $settings['shipaccount']; $meter = $settings['meter']; $service = explode(',', $settings['service']); $package = $settings['package']; $handling_method = $settings['handling_method']; $handling_amount = $settings['handling_amount']; $pkg_width = $settings['width']; $pkg_height = $settings['height']; $pkg_length = $settings['length']; $billAccount = $shipAccount; //====== Fedex code start require_once 'lib/fedex-common.php5'; ini_set("soap.wsdl_cache_enabled", "0"); $client = new SoapClient($this->path_to_wsdl, array('trace' => 1)); // Refer to http://us3.php.net/manual/en/ref.soap.php for more information $request['WebAuthenticationDetail'] = array('UserCredential' => array('Key' => $key, 'Password' => $password)); $request['ClientDetail'] = array('AccountNumber' => $shipAccount, 'MeterNumber' => $meter); $request['TransactionDetail'] = array('CustomerTransactionId' => ' *** Rate Available Services Request v8 using PHP ***'); $request['Version'] = array('ServiceId' => 'crs', 'Major' => '8', 'Intermediate' => '0', 'Minor' => '0'); $request['ReturnTransitAndCommit'] = true; $request['RequestedShipment']['DropoffType'] = 'REGULAR_PICKUP'; // valid values REGULAR_PICKUP, REQUEST_COURIER, ... $request['RequestedShipment']['ShipTimestamp'] = date('c'); $request['RequestedShipment']['Shipper'] = array('Address' => array('StreetLines' => array($this->CI->config->item('address1'), $this->CI->config->item('address2')), 'City' => $this->CI->config->item('city'), 'StateOrProvinceCode' => $this->CI->config->item('state'), 'PostalCode' => $this->CI->config->item('zip'), 'CountryCode' => $this->CI->config->item('country'))); $request['RequestedShipment']['Recipient'] = array('Address' => array('StreetLines' => array($customer_address['address1'], $customer_address['address2']), 'City' => $customer_address['city'], 'StateOrProvinceCode' => $customer_address['state'], 'PostalCode' => $customer_address['zip'], 'CountryCode' => $customer_address['country_code'])); $request['RequestedShipment']['ShippingChargesPayment'] = array('PaymentType' => 'SENDER', 'Payor' => array('AccountNumber' => $billAccount, 'CountryCode' => $customer_address['country_code'])); $request['RequestedShipment']['RateRequestTypes'] = 'ACCOUNT'; $request['RequestedShipment']['RateRequestTypes'] = 'LIST'; $request['RequestedShipment']['PackageCount'] = '1'; $request['RequestedShipment']['PackageDetail'] = 'INDIVIDUAL_PACKAGES'; $request['RequestedShipment']['PackagingType'] = $package; $request['RequestedShipment']['RequestedPackageLineItems'] = array('0' => array('Weight' => array('Value' => $weight, 'Units' => 'LB'), 'Dimensions' => array('Length' => $pkg_length, 'Width' => $pkg_width, 'Height' => $pkg_height, 'Units' => 'IN'))); // send request $response = $client->getRates($request); if ($response->HighestSeverity != 'FAILURE' && $response->HighestSeverity != 'ERROR') { if (!isset($response->RateReplyDetails) || !is_array($response->RateReplyDetails)) { return array(); // No Results } foreach ($response->RateReplyDetails as $rateReply) { if (in_array($rateReply->ServiceType, $service)) { $amount = $rateReply->RatedShipmentDetails[0]->ShipmentRateDetail->TotalNetCharge->Amount; if (is_numeric($handling_amount)) { if ($handling_method == '$') { $amount += $handling_amount; } elseif ($handling_method == '%') { $amount += $amount * ($handling_amount / 100); } } $rates[$this->service_list[$rateReply->ServiceType]] = number_format($amount, 2, ".", ","); } } return $rates; } else { return array(); // fail } //======== Fedex Code End }
function getFedexRate($from_zip, $to_zip, $weight) { // Colaesce Dev Account: $key = 'kEX6SaVxmKkWBrv4'; $account_number = '510087100'; $password = '******'; $meter_number = '7001787'; // $service_type = 'FEDEX_GROUND'; // valid values STANDARD_OVERNIGHT, PRIORITY_OVERNIGHT, FEDEX_GROUND, ... $packaging_type = 'YOUR_PACKAGING'; // valid values FEDEX_BOK, FEDEX_PAK, FEDEX_TUBE, YOUR_PACKAGING, ... $drop_off_type = 'REGULAR_PICKUP'; // valid values REGULAR_PICKUP, REQUEST_COURIER, ... $shipper = array('Address' => array('StreetLines' => array('2980 Highway 378'), 'City' => 'Conway', 'StateOrProvinceCode' => 'SC', 'PostalCode' => $from_zip, 'CountryCode' => 'US')); $recipient = array('Address' => array('StreetLines' => array(''), 'City' => '', 'StateOrProvinceCode' => '', 'PostalCode' => $to_zip, 'CountryCode' => 'US')); $requested_packages = array('0' => array('SequenceNumber' => '1', 'InsuredValue' => array('Amount' => 0, 'Currency' => 'USD'), 'ItemDescription' => 'Website Order', 'Weight' => array('Value' => $weight, 'Units' => 'LB'), 'Dimensions' => array('Length' => 0, 'Width' => 0, 'Height' => 0, 'Units' => 'IN'), 'CustomerReferences' => array('CustomerReferenceType' => 'CUSTOMER_REFERENCE', 'Value' => 'Website Order'))); // Copyright 2008, FedEx Corporation. All rights reserved. // Version 4.0.0 require_once APP . '/vendors/fedex/fedex-common.php'; $newline = "<br />"; //The WSDL is not included with the sample code. //Please include and reference in $path_to_wsdl variable. $path_to_wsdl = APP . '/vendors/fedex/RateService_v4.wsdl'; ini_set("soap.wsdl_cache_enabled", "0"); $client = new SoapClient($path_to_wsdl, array('trace' => 1)); // Refer to http://us3.php.net/manual/en/ref.soap.phpfor more information $request['WebAuthenticationDetail'] = array('UserCredential' => array('Key' => $this->credentials['fedex']['key'], 'Password' => $this->credentials['fedex']['password'])); $request['ClientDetail'] = array('AccountNumber' => $this->credentials['fedex']['account_number'], 'MeterNumber' => $this->credentials['fedex']['meter_number']); $request['TransactionDetail'] = array('CustomerTransactionId' => ' *** Rate Request v4 using PHP ***'); $request['Version'] = array('ServiceId' => 'crs', 'Major' => '4', 'Intermediate' => '0', 'Minor' => '0'); $request['RequestedShipment']['DropoffType'] = $drop_off_type; $request['RequestedShipment']['ShipTimestamp'] = date('c'); $request['RequestedShipment']['ServiceType'] = $service_type; $request['RequestedShipment']['PackagingType'] = $packaging_type; $request['RequestedShipment']['Shipper'] = $shipper; $request['RequestedShipment']['Recipient'] = $recipient; $request['RequestedShipment']['ShippingChargesPayment'] = array('PaymentType' => 'SENDER', 'Payor' => array('AccountNumber' => $account_number, 'CountryCode' => 'US')); $request['RequestedShipment']['RateRequestTypes'] = 'ACCOUNT'; $request['RequestedShipment']['RateRequestTypes'] = 'LIST'; $request['RequestedShipment']['PackageCount'] = '1'; $request['RequestedShipment']['PackageDetail'] = 'INDIVIDUAL_PACKAGES'; $request['RequestedShipment']['RequestedPackages'] = $requested_packages; try { $response = $client->getRates($request); if ($response->HighestSeverity != 'FAILURE' && $response->HighestSeverity != 'ERROR') { // print_r($response); exit(); return $response->RateReplyDetails->RatedShipmentDetails['0']->ShipmentRateDetail->TotalNetCharge->Amount; // printRequestResponse($client); } else { echo 'Error in processing transaction.' . $newline . $newline; foreach ($response->Notifications as $notification) { if (is_array($response->Notifications)) { echo $notification->Severity; echo ': '; echo $notification->Message . $newline; } else { echo $notification . $newline; } } } // writeToLog($client); // Write to log file } catch (SoapFault $exception) { printFault($exception, $client); } }