private function GetQuote() { $packages = $this->BuildPackages(); $shippingCharge = 0; $transitTime = 0; // Set the description of the method $description = ""; // Load up the module variables $this->SetCustomVars(); foreach ($this->_variables['deliverytypes']['options'] as $k => $v) { if ($v == $this->_deliverytype) { $description = $k; } } $handle = fopen(dirname(__FILE__) . "/data/royalmail.csv", "r"); $shippingData = array(); while (($data = fgetcsv($handle, 1000, ",")) !== false) { $shippingData[] = $data; } fclose($handle); // Now loop through all of the packages we'll be sending foreach ($packages as $package) { // Convert the dimensions, and convert the weight to grams $weight = ConvertWeight($package['weight'], 'kilograms'); foreach (array_keys($shippingData) as $key) { if ($shippingData[$key][0] == $this->_deliverytype && $weight <= (double) $shippingData[$key][1]) { $shippingCharge = $shippingData[$key][2]; break; } } } if ($shippingCharge == 'Unavailable') { return ''; } // OK, so create the actual quote $packageCount = ''; if (count($packages) > 1) { $packageCount = count($packages) . ' x '; } $quote = new ISC_SHIPPING_QUOTE($this->GetId(), $this->GetDisplayName(), number_format($shippingCharge, 2), $packageCount . $description); return $quote; }
private function GetQuote() { // The following array will be returned to the calling function. // It will contain at least one ISC_SHIPPING_QUOTE object if // the shipping quote was successful. $usps_quote = array(); $origincountry = $this->GetCountry($this->_origincountry); $destcountry = $this->GetCountry($this->_destcountry); // Is this an international quote? if ($origincountry != $destcountry) { $this->_api = "IntlRate"; } else { $this->_api = "RateV3"; } // Build the start of the USPS XML query - password can be anything but empty $usps_xml = sprintf("<%sRequest USERID=\"%s\">", $this->_api, $this->_username); $usps_xml .= "<Package ID=\"0\">"; // Which server are we shipping with? if ($this->_service == "PARCEL") { $usps_xml .= "<Service>PARCEL</Service>"; } else { $usps_xml .= sprintf("<Service>%s</Service>", $this->_service); } if ($this->_service == "FIRST CLASS" || $this->_service == "PARCEL") { $usps_xml .= "<FirstClassMailType>PARCEL</FirstClassMailType>"; } // get the amount of pounds $fractional_pounds = ConvertWeight($this->_weight, 'pounds'); $pounds = floor($fractional_pounds); // get the amount of ounces for the fractional remainder $ounces = round(ConvertWeight($fractional_pounds - $pounds, 'ounces', 'pounds'), 3); $weight_xml = sprintf("<Pounds>%s</Pounds>", $pounds); $weight_xml .= sprintf("<Ounces>%s</Ounces>", $ounces); // Must output weight before mailtype for international if ($this->_api == "IntlRate") { $usps_xml .= $weight_xml; } if ($this->_api == "IntlRate") { $usps_xml .= "<MailType>Package</MailType>"; $usps_xml .= sprintf("<Country>%s</Country>", $destcountry); } else { $usps_xml .= sprintf("<ZipOrigination>%s</ZipOrigination>", $this->_originzip); $usps_xml .= sprintf("<ZipDestination>%s</ZipDestination>", $this->_destzip); } // Must output weight after mailtype for domestic if ($this->_api != "IntlRate") { $usps_xml .= $weight_xml; } // Which container to use depends on which method was chosen switch ($this->_service) { case "EXPRESS": $this->_container = $this->_expressmailcontainertype; $this->_size = $this->_expressmailpackagesize; break; case "FIRST CLASS": $this->_container = $this->_firstclasscontainertype; $this->_size = $this->_firstclasspackagesize; break; case "PRIORITY": $this->_container = $this->_prioritycontainertype; $this->_size = $this->_prioritypackagesize; break; case "PARCEL": $this->_size = $this->_parcelpostmachpackagesize; break; case "BPM": $this->_size = $this->_bpmpackagesize; break; case "LIBRARY": $this->_size = $this->_librarypackagesize; break; case "MEDIA": $this->_size = $this->_mediapackagesize; break; } $this->_container = $this->GetContainerType($this->_container); $this->_size = $this->GetContainerSize($this->_size); $usps_xml .= sprintf("<Container>%s</Container>", $this->_container); $usps_xml .= sprintf("<Size>%s</Size>", $this->_size); if ($this->_service == "PRIORITY" && $this->_size == "LARGE") { $usps_xml .= sprintf("<Width>%s</Width>", number_format(ConvertLength($this->_prioritywidth, "in"), 2)); $usps_xml .= sprintf("<Length>%s</Length>", number_format(ConvertLength($this->_prioritylength, "in"), 2)); $usps_xml .= sprintf("<Height>%s</Height>", number_format(ConvertLength($this->_priorityheight, "in"), 2)); if ($this->_prioritygirth > 0) { $usps_xml .= sprintf("<Girth>%s</Girth>", ConvertLength($this->_prioritygirth, "in")); } } // Add the Machinable element if it's a parcel post if ($this->_service == "PARCEL") { $usps_xml .= "<Machinable>true</Machinable>"; } $usps_xml .= "</Package>"; $usps_xml .= sprintf("</%sRequest>", $this->_api); // If it's an international quote then we'll strip out // the service, container and size elements if ($this->_api == "IntlRate") { $usps_xml = preg_replace("#<Service>(.*)</Service>#si", "", $usps_xml); $usps_xml = preg_replace("#<Container>(.*)</Container>#si", "", $usps_xml); $usps_xml = preg_replace("#<Size>(.*)</Size>#si", "", $usps_xml); $usps_xml = preg_replace("#<Width>(.*)</Width>#si", "", $usps_xml); $usps_xml = preg_replace("#<Length>(.*)</Length>#si", "", $usps_xml); $usps_xml = preg_replace("#<Height>(.*)</Height>#si", "", $usps_xml); $usps_xml = preg_replace("#<Girth>(.*)</Girth>#si", "", $usps_xml); $usps_xml = preg_replace("#<FirstClassMailType>(.*)</FirstClassMailType>#si", "", $usps_xml); $usps_xml = preg_replace("#<Machinable>(.*)</Machinable>#si", "", $usps_xml); } // Connect to USPS to retrieve a live shipping quote $result = ""; $valid_quote = false; // Should we test on the test or production server? $usps_mode = $this->GetValue("servertype"); if ($usps_mode == "test") { $usps_url = "http://testing.shippingapis.com/ShippingAPITest.dll?"; } else { $usps_url = "http://production.shippingapis.com/ShippingAPI.dll?"; } $post_vars = implode("&", array("API={$this->_api}", "XML={$usps_xml}")); if (function_exists("curl_exec")) { // Use CURL if it's available $ch = @curl_init($usps_url); curl_setopt($ch, CURLOPT_POST, 1); curl_setopt($ch, CURLOPT_POSTFIELDS, $post_vars); curl_setopt($ch, CURLOPT_TIMEOUT, 60); curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); // Setup the proxy settings if there are any if (GetConfig('HTTPProxyServer')) { curl_setopt($ch, CURLOPT_PROXY, GetConfig('HTTPProxyServer')); if (GetConfig('HTTPProxyPort')) { curl_setopt($ch, CURLOPT_PROXYPORT, GetConfig('HTTPProxyPort')); } } if (GetConfig('HTTPSSLVerifyPeer') == 0) { curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); } $result = curl_exec($ch); if ($result != "") { $valid_quote = true; } } $this->DebugLog($result); if ($valid_quote) { // Was the user authenticated? if (is_numeric(isc_strpos($result, "Authorization failure"))) { $this->SetError(GetLang('USPSAuthError')); return false; } else { $xml = xmlize($result); // Are we dealing with a domestic or international shipment? if (isset($xml['RateV3Response'])) { // Domestic if (is_numeric(isc_strpos($result, "Error"))) { // Bad quote $this->SetError($xml['RateV3Response']["#"]['Package'][0]["#"]['Error'][0]["#"]['Description'][0]["#"]); return false; } else { // Create a quote object $quote = new ISC_SHIPPING_QUOTE($this->GetId(), $this->GetDisplayName(), $xml['RateV3Response']["#"]['Package'][0]["#"]['Postage'][0]["#"]['Rate'][0]["#"], $xml['RateV3Response']["#"]['Package'][0]["#"]['Postage'][0]["#"]['MailService'][0]["#"]); return $quote; } } else { if (isset($xml['IntlRateResponse'])) { // International if (is_numeric(isc_strpos($result, "Error"))) { // Bad quote $this->SetError($xml['IntlRateResponse']["#"]['Package'][0]["#"]['Error'][0]["#"]['Description'][0]["#"]); return false; } else { // Success $QuoteList = array(); $USPSServices = $xml['IntlRateResponse']["#"]['Package'][0]["#"]['Service']; // get the list of enabled services $services = $this->GetIntlServices($this->_service); foreach ($USPSServices as $Service) { $serviceId = $Service['@']['ID']; // check if this service is enabled if (!in_array($serviceId, $services)) { continue; } // Create a quote object $quote = new ISC_SHIPPING_QUOTE($this->GetId(), $this->GetDisplayName(), $Service["#"]['Postage'][0]["#"], GetLang('USPSIntlService_' . $serviceId)); //save quotes in an array $QuoteList[] = $quote; } return $QuoteList; } } else { if (isset($xml['Error'])) { // Error $this->SetError($xml['Error']["#"]['Description'][0]["#"]); return false; } } } } } else { // Couldn't get to USPS $this->SetError(GetLang('USPSOpenError')); return false; } }
private function GetQuote() { // The following array will be returned to the calling function. // It will contain at least one ISC_SHIPPING_QUOTE object if // the shipping quote was successful. $usps_quote = array(); $origincountry = $this->GetCountry($this->_origin_country['country_iso']); $destcountry = $this->GetCountry($this->_destination_country['country_iso']); // Is this an international quote? if($origincountry != $destcountry) { $api = "IntlRate"; } else { $api = "RateV3"; } $uspsXML = new SimpleXMLElement('<'.$api.'Request USERID="'.$this->GetValue('username').'" />'); $package = $uspsXML->addChild('Package'); $package->addAttribute('ID', 0); if($api != 'IntlRate') { $package->addChild('Service', $this->_service); if($this->_service == "FIRST CLASS" || $this->_service == "PARCEL") { $package->addChild('FirstClassMailType', 'PARCEL'); } } // Get the amount of pounds $fractionalPounds = ConvertWeight($this->_weight, 'pounds'); $pounds = floor($fractionalPounds); // Get the amount of ounces for the fractional remainder $ounces = round(ConvertWeight($fractionalPounds - $pounds, 'ounces', 'pounds'), 2); $weight_xml = sprintf("<Pounds>%s</Pounds>", $pounds); $weight_xml .= sprintf("<Ounces>%s</Ounces>", $ounces); // International rates require the weight before the mail type if($api == "IntlRate") { $package->addChild('Pounds', $pounds); $package->addChild('Ounces', $ounces); $package->addChild('MailType', 'Package'); $package->addChild('Country', $destcountry); } // Domestic rates require the destination before the weight else { $package->addChild('ZipOrigination', $this->_origin_zip); $package->addChild('ZipDestination', $this->_destination_zip); $package->addChild('Pounds', $pounds); $package->addChild('Ounces', $ounces); // Which container to use depends on which method was chosen switch($this->_service) { case "EXPRESS": { $containerType = $this->_expressmailcontainertype; $containerSize = $this->_expressmailpackagesize; break; } case "FIRST CLASS": { $containerType = $this->_firstclasscontainertype; $containerSize = $this->_firstclasspackagesize; break; } case "PRIORITY": { $containerType = $this->_prioritycontainertype; $containerSize = $this->_prioritypackagesize; break; } case "PARCEL": { $containerSize = $this->_parcelpostmachpackagesize; break; } case "BPM": { $containerSize = $this->_bpmpackagesize; break; } case "LIBRARY": { $containerSize = $this->_librarypackagesize; break; } case "MEDIA": { $containerSize = $this->_mediapackagesize; break; } } if(!empty($containerType)) { $containerType = $this->GetContainerType($containerType); } else { $containerType =''; } $package->addChild('Container', $containerType); $containerSize = $this->GetContainerSize($containerSize); $package->addChild('Size', $containerSize); if($this->_service == "PRIORITY" && $containerSize == "LARGE") { $dimensions = $this->Getcombinedshipdimensions(); $package->addChild('Width', number_format(ConvertLength($dimensions['width'], "in"), 2)); $package->addChild('Length', number_format(ConvertLength($dimensions['length'], "in"), 2)); $package->addChild('Height', number_format(ConvertLength($dimensions['height'], "in"), 2)); } // Add the Machinable element if it's a parcel post if($this->_service == "PARCEL") { $package->addChild('Machinable', 'true'); } } // Should we test on the test or production server? if($this->GetValue("servertype") == "test") { $uspsURL = "http://testing.shippingapis.com/ShippingAPITest.dll"; } else { $uspsURL = "http://production.shippingapis.com/ShippingAPI.dll"; } $postVars = array( 'API' => $api, 'XML' => $uspsXML->asXML() ); $postVars = http_build_query($postVars); $result = postToRemoteFileAndGetResponse($uspsURL, $postVars); if(!$result) { // Couldn't get to USPS $this->SetError(GetLang('USPSOpenError')); return false; } // Parse the XML response from USPS $xml = simplexml_load_string($result); if(!is_object($xml)) { $this->SetError(GetLang('USPSOpenError')); return false; } // Invalid username or access credentials supplied to USPS if(isc_strpos($result, "Authorization failure") !== false) { $this->SetError(GetLang('USPSAuthError')); return false; } // Return with the error message if the USPS request returned an error if(isset($xml->Package->Error)) { // Bad quote $this->SetError((string)$xml->Package->Error->Description); return false; } // Domestic quote responses return a single shipping quote // as we supplied a particular service if($api == 'RateV3') { $classId = (string)$xml->Package->Postage['CLASSID']; $service = $this->GetDomesticServiceByClassId($classId); $quote = new ISC_SHIPPING_QUOTE( $this->GetId(), $this->GetDisplayName(), (string)$xml->Package->Postage->Rate, $service['description'] ); return $quote; } // International quotes return a series of available shipping services // so we need to loop through them and return an array of matching // quotes $quotes = array(); $enabledServices = $this->GetIntlServices($this->_service); foreach($xml->Package->Service as $service) { $attributes = $service->attributes(); $serviceId = (int)$attributes['ID']; // Check if this service is enabled if (!in_array($serviceId, $enabledServices)) { continue; } // Create a quote object $quotes[] = new ISC_SHIPPING_QUOTE( $this->GetId(), $this->GetDisplayName(), (string)$service->Postage, GetLang('USPSIntlService_' . $serviceId) ); } if(empty($quotes)) { $this->SetError(GetLang('USPSNoShippingMethods')); return false; } return $quotes; }
/** * Generate the XML to be sent to UPS to calculate shipping quotes. * * @return string The generated XML. */ private function GenerateRateXML() { $shipFromCity = GetConfig('CompanyCity'); $shipFromState = GetStateISO2ByName(GetConfig('CompanyState')); $shipFromZip = GetConfig('CompanyZip'); $shipFromCountry = GetCountryISO2ByName(GetConfig('CompanyCountry')); // Build the XML for the shipping quote $xml = new SimpleXMLElement("<AccessRequest xml:lang='en-US'/>"); $xml->addChild('AccessLicenseNumber', $this->GetValue('accesslicenseno')); $xml->addChild('UserId', $this->GetValue('accessuserid')); $xml->addChild('Password', $this->GetValue('accesspassword')); $accessRequest = $xml->asXML(); $xml = new SimpleXMLElement('<RatingServiceSelectionRequest/>'); $request = $xml->addChild('Request'); // Add in the transaction reference $transRef = $request->addChild('TransactionReference'); $transRef->addChild('CustomerContext', 'Rating and Service'); $transRef->addChild('XpciVersion', '1.0'); $request->addChild('RequestAction', 'Rate'); $request->addChild('RequestOption', 'Shop'); // Add in the pickup type we'll be using $xml->addChild('PickupType')->addChild('Code', $this->GetValue('pickuptypes')); // Provide information about the shipment $shipment = $xml->addChild('Shipment'); // Add the information about the shipper $shipper = $shipment->addChild('Shipper'); $shipperNumber = $this->GetValue('upsaccount'); if ($shipperNumber) { $shipper->addChild('ShipperNumber', $shipperNumber); } $address = $shipper->addChild('Address'); $address->addChild('City', $shipFromCity); $address->addChild('StateProvinceCode', $shipFromState); $address->addChild('PostalCode', $shipFromZip); $address->addChild('CountryCode', $shipFromCountry); // Now add the information about the destination address $address = $shipment->addChild('ShipTo')->addChild('Address'); //$address->addChild('City', 'Sydney'); if ($this->_destination_state['state_iso']) { $state = $this->_destination_state['state_iso']; } else { $state = $this->_destination_state['state_name']; } $address->addChild('StateProvinceCode', $state); $address->addChild('PostalCode', $this->_destination_zip); $address->addChild('CountryCode', $this->_destination_country['country_iso']); // Add in the location we're shipping from $shipFrom = $shipment->addChild('ShipFrom'); $address = $shipFrom->addChild('Address'); $address->addChild('City', $shipFromCity); $address->addChild('StateProvinceCode', $shipFromState); $address->addChild('PostalCode', $shipFromZip); $address->addChild('CountryCode', $shipFromCountry); // Add in the package information $package = $shipment->addChild('Package'); $package->addChild('PackagingType')->addChild('Code', $this->GetValue('packagingtype')); $packageWeight = $package->addChild('PackageWeight'); switch (strtolower($shipFromCountry)) { case 'us': case 'lr': case 'mm': $weightCode = 'LBS'; $dimensionsCode = 'IN'; break; default: $weightCode = 'KGS'; $dimensionsCode = 'CM'; } $packageWeight->addChild('UnitOfMeasurement')->addChild('Code', $weightCode); $weight = ConvertWeight($this->_weight, $weightCode); if ($weightCode == 'LBS' && $weight < 0.1) { $weight = 0.1; } $packageWeight->addChild('Weight', $weight); $shipmentDimensions = $this->GetCombinedShipDimensions(); if ($shipmentDimensions['width'] + $shipmentDimensions['height'] + $shipmentDimensions['length'] > 0) { $dimensions = $package->addChild('Dimensions'); $dimensions->addChild('UnitsOfMeasurement')->addChild('Code', $dimensionsCode); $dimensions->addChild('Length', number_format(ConvertLength($shipmentDimensions['length'], $dimensionsCode), 2, '.', '')); $dimensions->addChild('Width', number_format(ConvertLength($shipmentDimensions['width'], $dimensionsCode), 2, '.', '')); $dimensions->addChild('Height', number_format(ConvertLength($shipmentDimensions['height'], $dimensionsCode), 2, '.', '')); } $combinedXML = $accessRequest . $xml->asXML(); //print_R($combinedXML); return $combinedXML; }
private function GetQuote() { // The following array will be returned to the calling function. // It will contain at least one ISC_SHIPPING_QUOTE object if // the shipping quote was successful. $is_quote = array(); // Connect to Intershipper to retrieve a live shipping quote $items = ""; $result = ""; $valid_quote = false; $is_url = "http://www.intershipper.com/Interface/Intershipper/XML/v2.0/HTTP.jsp?"; // Workout the carrier data $carrier_data = array(); $carrier_count = 1; if(!is_array($this->_carriers) && $this->_carriers != "") { $this->_carriers = array($this->_carriers); } foreach($this->_carriers as $carrier) { array_push($carrier_data, sprintf("CarrierCode%d=%s", $carrier_count, $carrier)); array_push($carrier_data, sprintf("CarrierInvoiced%d=1", $carrier_count)); $carrier_count++; } $post_vars = implode("&", array("Version=2.0.0.0", "Username="******"Password="******"TotalCarriers=" . count($this->_carriers) ) ); $post_vars .= "&" . implode("&", $carrier_data); $post_vars .= "&TotalClasses=" . count($this->_shipclasses); // Workout the classes data $class_data = array(); $class_count = 1; if(!is_array($this->_shipclasses) && $this->_shipclasses != "") { $this->_shipclasses = array($this->_shipclasses); } foreach($this->_shipclasses as $shipclass) { array_push($class_data, sprintf("ClassCode%d=%s", $class_count, $shipclass)); $class_count++; } $post_vars .= "&" . implode("&", $class_data) . "&"; $post_vars .= implode("&", array("DeliveryType=" . $this->_destinationtype, "ShipMethod=" . $this->_shippingmethod, "OriginationPostal=" . $this->_origin_zip, "OriginationCountry=" . $this->_origin_country['country_iso'], "DestinationPostal=" . $this->_destzip, "DestinationCountry=" . $this->_destcountry, "Currency=USD", "SortBy=" . $this->_sort, "TotalPackages=" . $this->getnumproducts() ) ); // Workout the box data $box_data = array(); $box_count = 1; if(isc_strtolower(GetConfig('LengthMeasurement')) == "inches") { $length_measure = "IN"; } else { $length_measure = "CM"; } foreach($this->getproducts() as $item) { array_push($box_data, sprintf("BoxID%d=item%d", $box_count, $box_count)); array_push($box_data, sprintf("Weight%d=%s", $box_count, ConvertWeight($item->getweight(), 'kgs'))); array_push($box_data, sprintf("WeightUnit%d=%s", $box_count, 'KG')); array_push($box_data, sprintf("Length%d=%s", $box_count, ConvertLength($item->getlength(), $length_measure))); array_push($box_data, sprintf("Width%d=%s", $box_count, ConvertLength($item->getwidth(), $length_measure))); array_push($box_data, sprintf("Height%d=%s", $box_count, ConvertLength($item->getheight(), $length_measure))); array_push($box_data, sprintf("DimensionalUnit%d=%s", $box_count, $length_measure)); array_push($box_data, sprintf("Packaging%d=%s", $box_count, $this->_packagingtype)); array_push($box_data, sprintf("Contents%d=OTR", $box_count)); $box_count++; } $post_vars .= "&" . implode("&", $box_data); $post_vars .= "&TotalOptions=0"; if(function_exists("curl_exec")) { // Use CURL if it's available $ch = @curl_init($is_url); curl_setopt($ch, CURLOPT_POST, 1); curl_setopt($ch, CURLOPT_POSTFIELDS, $post_vars); curl_setopt($ch, CURLOPT_TIMEOUT, 60); curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); // Setup the proxy settings if there are any if (GetConfig('HTTPProxyServer')) { curl_setopt($ch, CURLOPT_PROXY, GetConfig('HTTPProxyServer')); if (GetConfig('HTTPProxyPort')) { curl_setopt($ch, CURLOPT_PROXYPORT, GetConfig('HTTPProxyPort')); } } if (GetConfig('HTTPSSLVerifyPeer') == 0) { curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); } $result = curl_exec($ch); if($result != "") { $valid_quote = true; } } else { // Use fopen instead if($fp = @fopen($is_url . $post_vars, "rb")) { $result = ""; while(!feof($fp)) { $result .= fgets($fp, 4096); } @fclose($fp); $valid_quote = true; } } if($valid_quote) { if(is_numeric(isc_strpos($result, "Invalid User"))) { $this->SetError(GetLang('IntershipperAuthError')); return false; } else { $xml = xmlize($result); if(isset($xml['shipment'])) { // Is there an error? if(isset($xml['shipment']["#"]['error'])) { $this->SetError($xml['shipment']["#"]['error'][0]["#"]); return false; } else { if(isset($xml['shipment']["#"]['package'][0]["#"]['quote'])) { // Successful quote foreach($xml['shipment']["#"]['package'][0]["#"]['quote'] as $quote) { $shipper = $quote["#"]['carrier'][0]["#"]['name'][0]["#"]; // Shorten the length of the shipper's name // DHL $shipper = str_replace(" World Wide Express", "", $shipper); // UPS $shipper = str_replace("United Parcel Service", "", $shipper); // FedEx $shipper = str_replace("Federal Express", "FedEx", $shipper); // USPS $shipper = str_replace("U.S. Postal Service", "USPS", $shipper); $method = $quote["#"]['service'][0]["#"]['name'][0]["#"]; // Shorten the length of the method // USPS $method = str_replace("USP ", "", $method); $desc = trim(sprintf("%s %s", $shipper, $method)); $price = $quote["#"]['rate'][0]["#"]['amount'][0]["#"] / 100; $transit_time = -1; // Workout the time in transit (if any) $today_stamp = mktime(0, 0, 0, date("m"), date("d"), date("Y")); if(isset($quote["#"]['guaranteedarrival'])) { $delivered = $quote["#"]['guaranteedarrival'][0]["#"]['date'][0]["#"]; $arr_delivered = explode("/", $delivered); if(count($arr_delivered) == 3) { $delivered_stamp = mktime(0, 0, 0, $arr_delivered[0], $arr_delivered[1], $arr_delivered[2]); $transit_time = $delivered_stamp - $today_stamp; // Convert transit time to days $transit_time = floor($transit_time/60/60/24); } } else if(isset($quote["#"]['nonguaranteedarrival'])) { $delivered = $quote["#"]['nonguaranteedarrival'][0]["#"]['earliestarrivaldate'][0]["#"]; $arr_delivered = explode("/", $delivered); if(count($arr_delivered) == 3) { $delivered_stamp = mktime(0, 0, 0, $arr_delivered[0], $arr_delivered[1], $arr_delivered[2]); $transit_time = $delivered_stamp - $today_stamp; // Convert transit time to days $transit_time = floor($transit_time/60/60/24); } } // Create a quote object $quote = new ISC_SHIPPING_QUOTE($this->GetId(), $this->GetDisplayName(), $price, $desc, $transit_time); // Append it to the list of shipping methods array_push($is_quote, $quote); } } else { $this->SetError(GetLang('IntershipperBadDestination')); return false; } } } else { // Error $this->SetError(GetLang('IntershipperBadResponse')); return false; } } } else { // Couldn't get to Intershipper $this->SetError(GetLang('IntershipperOpenError')); return false; } return $is_quote; }
private function GetQuote() { // The following array will be returned to the calling function. // It will contain at least one ISC_SHIPPING_QUOTE object if // the shipping quote was successful. $cp_quote = array(); // Connect to Canada Post to retrieve a live shipping quote $items = ""; $result = ""; $valid_quote = false; $cp_url = "http://sellonline.canadapost.ca:30000?"; $readytoship = ''; if($this->_readytoship == 'yes') { $readytoship = "<readyToShip/>"; } foreach($this->_products as $product) { $items .= sprintf("<item> <quantity>%d</quantity> <weight>%s</weight> <length>%s</length> <width>%s</width> <height>%s</height> <description><![CDATA[%s]]></description> %s </item>", $product->getquantity(), ConvertWeight($product->GetWeight(), 'kgs'), ConvertLength($product->getlength(), "cm"), ConvertLength($product->getwidth(), "cm"), ConvertLength($product->getheight(), "cm"), $product->getdesc(), $readytoship ); } $cp_xml = sprintf("<" . "?" . "xml version=\"1.0\" ?" . "> <eparcel> <language>en</language> <ratesAndServicesRequest> <merchantCPCID>%s</merchantCPCID> <fromPostalCode>%s</fromPostalCode> <lineItems> %s </lineItems> <city></city> <provOrState>%s</provOrState> <country>%s</country> <postalCode>%s</postalCode> </ratesAndServicesRequest> </eparcel> ", $this->_merchantid, $this->_origin_zip, $items, $this->_deststate, isc_strtoupper($this->_destcountry), $this->_destzip); $post_vars = implode("&", array("XMLRequest=$cp_xml" ) ); $result = PostToRemoteFileAndGetResponse($cp_url, $post_vars); if($result) { $valid_quote = true; } if(!$valid_quote) { $this->SetError(GetLang('CanadaPostOpenError')); return false; } $xml = @simplexml_load_string($result); if(!is_object($xml)) { $this->SetError(GetLang('CanadaPostBadResponse')); return false; } if(isset($xml->error)) { $this->SetError((string)$xml->error->statusMessage); return false; } if(isset($xml->ratesAndServicesResponse)) { foreach($xml->ratesAndServicesResponse->product as $ship_method) { // Calculate the transit time $transit_time = -1; $today = $ship_method->shippingDate; $arr_today = explode("-", $today); $today_stamp = mktime(0, 0, 0, $arr_today[1], $arr_today[2], $arr_today[0]); $delivered = $ship_method->deliveryDate; $arr_delivered = explode("-", $delivered); if(count($arr_delivered) == 3) { $delivered_stamp = mktime(0, 0, 0, $arr_delivered[1], $arr_delivered[2], $arr_delivered[0]); $transit_time = $delivered_stamp - $today_stamp; // Convert transit time to days $transit_time = floor($transit_time/60/60/24); } $quote = new ISC_SHIPPING_QUOTE($this->GetId(), $this->GetDisplayName(), (float)$ship_method->rate, (string)$ship_method->name, $transit_time); $cp_quote[] = $quote; } } return $cp_quote; }
private function GetQuote() { // The following array will be returned to the calling function. // It will contain at least one ISC_SHIPPING_QUOTE object if // the shipping quote was successful. $fx_quote = array(); // Connect to FedEx to retrieve a live shipping quote $items = ""; $result = ""; $valid_quote = false; $fx_url = "https://gateway.fedex.com/GatewayDC"; $weight = number_format(max(ConvertWeight($this->_weight, 'lbs'), 0.1), 1); // If we're shipping from US or Canada, originstate is required if (GetConfig('CompanyCountry') == "United States" || GetConfig('CompanyCountry') == "Canada") { $this->_originstate = GetStateISO2ByName(GetConfig('CompanyState')); } // If we're shipping to the US or Canada, deststate is required, otherwise it isn't - based off post codes if ($this->_destcountry != "US" && $this->_destcountry != "CA") { $this->_deststate = ''; } if ($this->_ratetype == "account") { $listRate = "false"; } else { $listRate = "true"; } $fx_xml = sprintf("<" . "?" . "xml version=\"1.0\" encoding=\"UTF-8\" " . "?" . ">\n\t\t\t\t<FDXRateRequest xmlns:api=\"http://www.fedex.com/fsmapi\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xsi:noNamespaceSchemaLocation=\"FDXRateRequest.xsd\">\n\t\t\t\t\t<RequestHeader>\n\t\t\t\t\t\t<CustomerTransactionIdentifier>Express Rate</CustomerTransactionIdentifier>\n\t\t\t\t\t\t<AccountNumber>%s</AccountNumber>\n\t\t\t\t\t\t<MeterNumber>%s</MeterNumber>\n\t\t\t\t\t\t<CarrierCode>%s</CarrierCode>\n\t\t\t\t\t</RequestHeader>\n\t\t\t\t\t<DropoffType>%s</DropoffType>\n\t\t\t\t\t<Service>%s</Service>\n\t\t\t\t\t<Packaging>%s</Packaging>\n\t\t\t\t\t<WeightUnits>LBS</WeightUnits>\n\t\t\t\t\t<Weight>%s</Weight>\n\t\t\t\t\t<OriginAddress>\n\t\t\t\t\t\t<StateOrProvinceCode>%s</StateOrProvinceCode>\n\t\t\t\t\t\t<PostalCode>%s</PostalCode>\n\t\t\t\t\t\t<CountryCode>%s</CountryCode>\n\t\t\t\t\t</OriginAddress>\n\t\t\t\t\t<DestinationAddress>\n\t\t\t\t\t\t<StateOrProvinceCode>%s</StateOrProvinceCode>\n\t\t\t\t\t\t<PostalCode>%s</PostalCode>\n\t\t\t\t\t\t<CountryCode>%s</CountryCode>\n\t\t\t\t\t</DestinationAddress>\n\t\t\t\t\t<Payment>\n\t\t\t\t\t\t<PayorType>SENDER</PayorType>\n\t\t\t\t\t</Payment>\n\t\t\t\t\t<PackageCount>1</PackageCount>\n\t\t\t\t\t<ListRate>%s</ListRate>\n\t\t\t\t</FDXRateRequest>\n\t\t\t", $this->_accountno, $this->_meterno, $this->_carriercode, $this->_dropofftype, $this->_service, $this->_packagingtype, $weight, $this->_originstate, $this->_originzip, $this->_origincountry, $this->_deststate, $this->_destzip, $this->_destcountry, $listRate); $result = PostToRemoteFileAndGetResponse($fx_url, $fx_xml); if ($result === false) { $valid_quote = false; } else { $valid_quote = true; $xml = @simplexml_load_string($result); } if (!$valid_quote || !is_object($xml)) { $this->SetError(GetLang('FedExBadResponse') . ' ' . isc_html_escape(print_r($result, true))); return false; } $netCharge = 0; if ($this->_ratetype == "list" && isset($xml->EstimatedCharges->ListCharges->NetCharge)) { $netCharge = $xml->EstimatedCharges->ListCharges->NetCharge; } elseif ($this->_ratetype == "account" && isset($xml->EstimatedCharges->DiscountedCharges->NetCharge)) { $netCharge = $xml->EstimatedCharges->DiscountedCharges->NetCharge; } if ($netCharge != 0) { $serviceType = $this->_deliverytypes[$this->_deliverytype] . ", " . $this->_servicetypes[$this->_service]; $quote = new ISC_SHIPPING_QUOTE($this->GetId(), $this->GetDisplayName(), (double) $netCharge, $serviceType); return $quote; } else { $Error = true; if (isset($xml->Error->Message)) { $this->SetError((string) $xml->Error->Message); return false; } else { $this->SetError(GetLang('FedExBadResponse') . ' ' . print_r($result, true)); return false; } } }
public function BuildPackages() { $packages = array(); // Everything is going to be sent in different packages, break down per item if($this->GetValue('packingmethod') == 'multiple') { foreach($this->_products as $product) { for($i = 1; $i <= $product->GetQuantity(); ++$i) { // Australia Post only supports packages up to 20kg; split packages into 20kg increments $itemTotalWeight = ConvertWeight($product->GetWeight(), 'kg'); $itemRemainingWeight = $itemTotalWeight; while ($itemRemainingWeight > 0) { // if the remaining weight for this item is less than 20kg, place it all in this package if($itemRemainingWeight <= 20) { $parcelWeight = $itemRemainingWeight; $itemRemainingWeight = 0; } else { // remaining weight for this item is more than 20kg, so create 20kg package and carry remaining weight over $parcelWeight = 20; $itemRemainingWeight -= 20; } $packages[] = array( 'height' => $product->GetHeight(), 'width' => $product->GetWidth(), 'length' => $product->GetLength(), 'weight' => ConvertWeight($parcelWeight, GetConfig('WeightMeasurement'),'kg'), 'items' => 1 ); } } } return $packages; } // Everything is going in the one package, simply calculate the dimensions else { // Workout the dimensions of the package Australia posts measures in grams and cms hence the multiplication $dimensions = $this->getcombinedshipdimensions(); $dimensions['weight'] = $this->GetWeight(); $dimensions['items'] = count($this->_products); $packages[] = $dimensions; return $packages; } }
private function GetQuote() { $packages = $this->BuildPackages(); $shippingCharge = 0; $transitTime = 0; // Set the description of the method $description = ""; // Load up the module variables $this->SetCustomVars(); foreach ($this->_variables['deliverytypes']['options'] as $k => $v) { if ($v == $this->_deliverytype) { $description = $k; } } // Now loop through all of the packages we'll be sending foreach ($packages as $package) { // Convert the dimensions, and convert the weight to grams $height = ConvertLength($package['height'], 'mm'); $length = ConvertLength($package['length'], 'mm'); $width = ConvertLength($package['width'], 'mm'); $weight = ConvertWeight($package['weight'], 'grams'); // minimum dimensions for auspost drc is 50x50x30 if ($height < 50) { $height = 50; } if ($length < 50) { $length = 50; } if ($width < 30) { $width = 30; } $data = array(); // Connect to Australia Post to retrieve a live shipping quote $validQuote = false; $ausPostURL = 'http://drc.edeliver.com.au/ratecalc.asp?'; $postVars = array('Height' => $height, 'Length' => $length, 'Width' => $width, 'Weight' => $weight, 'Quantity' => 1, 'Pickup_Postcode' => $this->_originzip, 'Destination_Postcode' => $this->_destzip, 'Country' => $this->_destcountry, 'Service_Type' => $this->_deliverytype); $postRequest = ''; foreach ($postVars as $k => $v) { $postRequest .= '&' . $k . '=' . urlencode($v); } $postRequest = ltrim($postRequest, '&'); $result = PostToRemoteFileAndGetResponse($ausPostURL, $postRequest); if ($result !== false) { $result = str_replace("\n", "&", $result); $result = str_replace("\r", "", $result); $result = rtrim($result, '&'); parse_str($result, $data); if (isset($data['charge']) && isset($data['days']) && isset($data['err_msg']) && $data['err_msg'] == "OK") { $shippingCharge += $data['charge']; $transitTime = max($transitTime, $data['days']); } else { if (isset($data['err_msg'])) { $this->SetError($data['err_msg']); return false; } else { $this->SetError(GetLang('AusPostOpenError')); return false; } } } else { $this->SetError(GetLang('AusPostOpenError')); return false; } } // OK, so create the actual quote $packageCount = ''; if (count($packages) > 1) { $packageCount = count($packages) . ' x '; } $quote = new ISC_SHIPPING_QUOTE($this->GetId(), $this->GetDisplayName(), number_format($shippingCharge, 2), $packageCount . $description, $transitTime); return $quote; }
private function GetQuote() { $shipperAddress = array( 'CountryCode' => $this->_origin_country['country_iso'], 'PostalCode' => $this->_origin_zip ); // United States or Canada require state/province if ($this->_origin_country['country_iso'] == 'US' || $this->_origin_country['country_iso'] == 'CA') { $shipperAddress['StateOrProvinceCode'] = $this->_origin_state['state_iso']; } $recipientAddress = array( 'CountryCode' => $this->_destcountry, 'PostalCode' => $this->_destzip, 'Residential' => ($this->GetValue('destinationtype') == 'residential'), ); // United States or Canada require state/province if ($this->_destcountry == 'US' || $this->_destcountry == "CA") { $recipientAddress['StateOrProvinceCode'] = $this->_deststate; } $weight = number_format(max(ConvertWeight($this->_weight, 'lbs'), 0.1), 1, '.', ''); // if today is on the weekend, set the date to the next monday $shipTime = isc_gmmktime(); $day = date('l', $shipTime); if ($day == 'Saturday') { $shipTime += 172800; } elseif ($day == 'Sunday') { $shipTime += 86400; } // create the shipment $shipDate = date('c', $shipTime); $xml = array( 'WebAuthenticationDetail' => array ( 'UserCredential' => array( 'Key' => $this->GetValue('key'), 'Password' => $this->GetValue('password') ) ), 'ClientDetail' => array( 'AccountNumber' => $this->GetValue('accountno'), 'MeterNumber' => $this->GetValue('meterno') ), 'Version' => array( 'ServiceId' => 'crs', 'Major' => '7', 'Intermediate' => '0', 'Minor' => '0' ), 'ReturnTransitAndCommit' => true, 'RequestedShipment' => array( 'Shipper' => array( 'Address' => $shipperAddress ), 'Recipient' => array( 'Address' => $recipientAddress ), 'ShippingChargesPayment' => array( 'PaymentType' => 'SENDER' ), 'RateRequestTypes' => $this->GetValue('ratetype'), 'PackageCount' => 1, 'PackageDetail' => 'INDIVIDUAL_PACKAGES', 'PackagingType' => $this->GetValue('packagingtype'), 'DropoffType' => $this->GetValue('dropofftype'), 'ShipTimestamp' => $shipDate, 'RequestedPackageLineItems' => array( 'Weight' => array( 'Units' => 'LB', 'Value' => $weight ) ), ) ); if (!empty($this->_service)) { $xml['RequestedShipment']['ServiceType'] = $this->_service; $services = array($this->_service); } else { $services = $this->GetValue("service"); if(!is_array($services) && $services != "") { $services = array($services); } } $new_xml['RateRequest'] = $xml; require_once(dirname(__FILE__) . "/../../../lib/nusoap/nusoap.php"); if ($this->GetValue('testmode') == "NO") { $wsdl = "RateService_v7.wsdl"; } else { $wsdl = "RateService_v7_dev.wsdl"; } $client = new nusoap_client(dirname(__FILE__) . "/" . $wsdl, 'wsdl'); $result = $client->call('getRates', $new_xml); if ($result['HighestSeverity'] == 'FAILURE' || $result['HighestSeverity'] == 'ERROR' || !isset($result['RateReplyDetails'])) { if (isset($result['Notifications'])) { $notifications = $result['Notifications']; if (key($notifications) != '0') { $notifications = array($notifications); } foreach ($notifications as $notification) { $this->SetError($notification['Severity'] . ' - ' . $notification['Message']); } } else { $this->SetError(GetLang('FedExBadResponse')); } return false; } if ($this->GetValue('ratetype') == 'LIST') { $responseRateTypes = array('RATED_LIST', 'PAYOR_LIST'); $preferredRateType = 'RATED_LIST'; } else { $responseRateTypes = array('RATED_ACCOUNT', 'PAYOR_ACCOUNT'); $preferredRateType = 'RATED_ACCOUNT'; } $currency = GetDefaultCurrency(); $quotes = array(); $rateReplyDetails = $result['RateReplyDetails']; if (key($rateReplyDetails) != '0') { $rateReplyDetails = array($rateReplyDetails); } $serviceQuotes = array(); $serviceRateTypes = array(); foreach ($rateReplyDetails as $rate) { // skip if this service hasn't been enabled if (!in_array($rate['ServiceType'], $services)) { continue; } $shipmentDetails = $rate['RatedShipmentDetails']; if (key($shipmentDetails) != '0') { $shipmentDetails = array($shipmentDetails); } foreach ($shipmentDetails as $shipmentRate) { $rateDetail = $shipmentRate['ShipmentRateDetail']; // ensure we have the correct rate type response if (!in_array($rateDetail['RateType'], $responseRateTypes)) { continue; } // multiple rate types for the same service can be returned, we preferabbly want the 'RATED' rate type if (isset($serviceRateTypes[$rate['ServiceType']]) && $serviceRateTypes[$rate['ServiceType']] == $preferredRateType) { continue; } // ensure the amount is in the currency of the store $totalNetCharge = $rateDetail['TotalNetCharge']; if ($totalNetCharge['Currency'] != $currency['currencycode']) { $this->SetError(GetLang('FedExUnexpectedCurrency', array('quoteCurrency' => $totalNetCharge['Currency'], 'storeCurrency' => $currency['currencycode']))); return false; } // build a new shipping quote $serviceQuotes[$rate['ServiceType']] = new ISC_SHIPPING_QUOTE( $this->GetId(), $this->GetDisplayName(), (float)$totalNetCharge['Amount'], $this->_servicetypes[$rate['ServiceType']] ); // store the type of rate for this service $serviceRateTypes[$rate['ServiceType']] = $rateDetail['RateType']; } $quotes = array_values($serviceQuotes); } return $quotes; }
private function getOrderData($orderRow, $addressIndex) { // Get the customer data if ($orderRow['ordcustid'] == 0){ $customerData = array( 'CustomerID' => -1, 'Phone' => $orderRow['ordbillphone'], 'Email' => $orderRow['ordbillemail'] ); } else { $customer = GetCustomer($orderRow['ordcustid']); $customerData = array( 'CustomerID' => $orderRow['ordcustid'], 'Phone' => $customer['custconphone'], 'Email' => $customer['custconemail'] ); } $orderId = $orderRow['orderid']; if ($orderRow['shipping_address_count'] > 1) { $orderId .= '-' . $addressIndex; } $data = array( 'OrderNumber' => $orderId, 'OrderDate' => gmdate('Y-m-d H:i:s', $orderRow['orddate']), 'LastModified' => gmdate('Y-m-d H:i:s', $orderRow['ordlastmodified']), 'LastModifiedLocal' => isc_date('Y-m-d H:i:s', $orderRow['ordlastmodified']), 'ShippingMethod' => $orderRow['method'], 'StatusCode' => $orderRow['ordstatus'], 'CustomerComment' => $orderRow['ordcustmessage'], 'Customer' => $customerData, 'ShipAddress' => array( 'Name' => $orderRow['first_name'] . ' ' . $orderRow['last_name'], 'Company' => $orderRow['company'], 'Street1' => $orderRow['address_1'], 'Street2' => $orderRow['address_2'], 'Street3' => '', 'City' => $orderRow['city'], 'PostalCode'=> $orderRow['zip'], 'State' => $orderRow['state'], 'Country' => $orderRow['country_iso2'] ), 'BillAddress' => array( 'Name' => $orderRow['ordbillfirstname'] . ' ' . $orderRow['ordbilllastname'], 'Company' => $orderRow['ordbillcompany'], 'Street1' => $orderRow['ordbillstreet1'], 'Street2' => $orderRow['ordbillstreet2'], 'Street3' => '', 'City' => $orderRow['ordbillsuburb'], 'PostalCode'=> $orderRow['ordbillzip'], 'State' => $orderRow['ordbillstate'], 'Country' => $orderRow['ordbillcountrycode'] ), 'Payment' => array( 'Method' => $orderRow['orderpaymentmethod'], ), ); $incTaxPrices = false; if (GetConfig('taxDefaultTaxDisplayOrders') != TAX_PRICES_DISPLAY_EXCLUSIVE) { $incTaxPrices = true; } // get the products for the order $items = array(); $totalWrapCost = 0; $query = ' SELECT op.*, pi.* FROM [|PREFIX|]order_products op LEFT JOIN [|PREFIX|]product_images pi ON (pi.imageprodid = op.ordprodid AND pi.imageisthumb = 1) WHERE op.order_address_id = ' . $orderRow['address_id']; $res = $GLOBALS['ISC_CLASS_DB']->Query($query); while ($productRow = $GLOBALS['ISC_CLASS_DB']->Fetch($res)) { $item = array( 'ItemID' => $productRow['orderprodid'], 'ProductID' => $productRow['ordprodid'], 'Code' => $productRow['ordprodsku'], 'Name' => $productRow['ordprodname'], 'Quantity' => $productRow['ordprodqty'], 'Weight' => ConvertWeight($productRow['ordprodweight'], 'lbs'), ); if ($incTaxPrices) { $item['UnitPrice'] = $productRow['price_inc_tax']; $totalWrapCost += $productRow['wrapping_cost_inc_tax'] * $productRow['ordprodqty']; } else { $item['UnitPrice'] = $productRow['price_ex_tax']; $totalWrapCost += $productRow['wrapping_cost_ex_tax'] * $productRow['ordprodqty']; } try { $image = new ISC_PRODUCT_IMAGE(); $image->populateFromDatabaseRow($productRow); $item['Image'] = $image->getResizedUrl(ISC_PRODUCT_IMAGE_SIZE_ZOOM, true); } catch (Exception $ex) { } $items['Item'][] = $item; } $data['Items'] = $items; // get the totals $totals = array(); $totalID = 1; // gift wrapping cost if ($totalWrapCost > 0) { $total = array( 'TotalID' => $totalID++, 'Name' => GetLang('ShipWorksGiftWrapping'), 'Text' => FormatPrice($totalWrapCost), 'Value' => $totalWrapCost, 'Class' => 'Adjust' ); $totals['Total'][] = $total; } // shipping cost if ($orderRow['shipping_cost_ex_tax'] > 0) { if ($incTaxPrices) { $shippingCost = $orderRow['shipping_cost_inc_tax']; } else { $shippingCost = $orderRow['shipping_cost_ex_tax']; } $total = array( 'TotalID' => $totalID++, 'Name' => GetLang('ShipWorksShipping'), 'Text' => FormatPrice($shippingCost), 'Value' => $shippingCost, 'Class' => 'Shipping' ); $totals['Total'][] = $total; } // handling cost if ($orderRow['handling_cost_ex_tax'] > 0) { if ($incTaxPrices) { $handlingCost = $orderRow['handling_cost_inc_tax']; } else { $handlingCost = $orderRow['handling_cost_ex_tax']; } $total = array( 'TotalID' => $totalID++, 'Name' => GetLang('ShipWorksHandling'), 'Text' => FormatPrice($handlingCost), 'Value' => $handlingCost, 'Class' => 'Shipping' ); $totals['Total'][] = $total; } // tax (not included in total) if ($orderRow['total_tax'] > 0 && !$incTaxPrices) { $total = array( 'TotalID' => $totalID++, 'Name' => 'Tax', 'Text' => FormatPrice($orderRow['total_tax']), 'Value' => $orderRow['total_tax'], 'Class' => 'Tax' ); $totals['Total'][] = $total; } // total if ($incTaxPrices) { $orderTotal = $orderRow['total_inc_tax']; } else { $orderTotal = $orderRow['total_ex_tax']; } $total = array( 'TotalID' => $totalID++, 'Name' => GetLang('ShipWorksTotal'), 'Text' => FormatPrice($orderTotal), 'Value' => $orderTotal, 'Class' => 'ot_total' ); $totals['Total'][] = $total; // gift certificates if ($orderRow['ordgiftcertificateamount'] > 0) { $total = array( 'TotalID' => $totalID++, 'Name' => GetLang('ShipWorksGiftCertificates'), 'Text' => FormatPrice($orderRow['ordgiftcertificateamount']), 'Value' => $orderRow['ordgiftcertificateamount'] * -1, 'Class' => 'Adjust' ); $totals['Total'][] = $total; } // other discount amount if ($orderRow['orddiscountamount'] > 0) { $total = array( 'TotalID' => $totalID++, 'Name' => GetLang('ShipWorksDiscounts'), 'Text' => FormatPrice($orderRow['orddiscountamount']), 'Value' => $orderRow['orddiscountamount'] * -1, 'Class' => 'Adjust' ); $totals['Total'][] = $total; } $data['Totals'] = $totals; return $data; }
public function GetServiceQuotes() { $this->ResetErrors(); $QuoteList = array(); // Set the UPS-specific variables $this->_destcountry = $this->_destination_country['country_iso']; $this->_destzip = $this->_destination_zip; $this->_shippingrate = $this->GetValue("shippingrate"); $this->_packagingtype = $this->GetValue("packagingtype"); $this->_destination_rescom = $this->GetValue("destination"); if($this->_destination_rescom == "COM") { $this->_destination = "0"; } else { $this->_destination = "1"; } // Convert the weight to pounds $this->_weight = ConvertWeight($this->_weight, 'pounds'); // Return quotes for all available UPS service types $services = $this->GetValue("deliverytypes"); if(!is_array($services) && $services != "") { $services = array($services); } foreach($services as $service) { // Set the service type $this->_deliverytype = $service; // Next actually retrieve the quote $err = ""; $result = $this->GetQuote($err); // Was it a valid quote? if(is_object($result)) { array_push($QuoteList, $result); // Invalid quote, log the error } else { foreach($this->GetErrors() as $error) { $GLOBALS['ISC_CLASS_LOG']->LogSystemError(array('shipping', $this->GetName()), $this->_deliverytypes[$service].": " .GetLang('ShippingQuoteError'), $error); } } } return $QuoteList; }
/** * Generate the XML to be sent to UPS to calculate shipping quotes. * * @return string The generated XML. */ private function GenerateRateXML() { $shipFromCity = $this->_origin_city; $shipFromState = $this->_origin_state['state_iso']; $shipFromZip = $this->_origin_zip; $shipFromCountry = $this->_origin_country['country_iso']; // Build the XML for the shipping quote $xml = new SimpleXMLElement("<AccessRequest xml:lang='en-US'/>"); $xml->addChild('AccessLicenseNumber', $this->GetValue('accesslicenseno')); $xml->addChild('UserId', $this->GetValue('accessuserid')); $xml->addChild('Password', $this->GetValue('accesspassword')); $accessRequest = $xml->asXML(); $xml = new SimpleXMLElement('<RatingServiceSelectionRequest/>'); $request = $xml->addChild('Request'); // Add in the transaction reference $transRef = $request->addChild('TransactionReference'); $transRef->addChild('CustomerContext', 'Rating and Service'); $transRef->addChild('XpciVersion', '1.0'); $request->addChild('RequestAction', 'Rate'); $request->addChild('RequestOption', 'Shop'); // Add in the pickup type we'll be using $xml->addChild('PickupType')->addChild('Code', $this->GetValue('pickuptypes')); // Provide information about the shipment $shipment = $xml->addChild('Shipment'); // Add the information about the shipper $shipper = $shipment->addChild('Shipper'); $shipperNumber = $this->GetValue('upsaccount'); if($shipperNumber) { $shipper->addChild('ShipperNumber', $shipperNumber); $rateInformation = $shipment->addChild('RateInformation'); $rateInformation->addChild('NegotiatedRatesIndicator'); } $address = $shipper->addChild('Address'); $address->addChild('City', $shipFromCity); $address->addChild('StateProvinceCode', $shipFromState); $address->addChild('PostalCode', $shipFromZip); $address->addChild('CountryCode', $shipFromCountry); // Now add the information about the destination address $address = $shipment->addChild('ShipTo')->addChild('Address'); //$address->addChild('City', 'Sydney'); if($this->_destination_state['state_iso']) { $state = $this->_destination_state['state_iso']; } else { $state = $this->_destination_state['state_name']; } $address->addChild('StateProvinceCode', $state); $address->addChild('PostalCode', $this->_destination_zip); $address->addChild('CountryCode', $this->_destination_country['country_iso']); //is the destination residential address if($this->GetValue('destinationtype') == 1) { $address->addChild('ResidentialAddress'); } // Add in the location we're shipping from $shipFrom = $shipment->addChild('ShipFrom'); $address = $shipFrom->addChild('Address'); $address->addChild('City', $shipFromCity); $address->addChild('StateProvinceCode', $shipFromState); $address->addChild('PostalCode', $shipFromZip); $address->addChild('CountryCode', $shipFromCountry); // Add in the package information $package = $shipment->addChild('Package'); $package->addChild('PackagingType')->addChild('Code', $this->GetValue('packagingtype')); $packageWeight = $package->addChild('PackageWeight'); switch(strtolower($shipFromCountry)) { case 'us': case 'lr': case 'mm': case 'ca': $weightCode = 'LBS'; $dimensionsCode = 'IN'; break; default: $weightCode = 'KGS'; $dimensionsCode = 'CM'; } $packageWeight->addChild('UnitOfMeasurement')->addChild('Code', $weightCode); $weight = ConvertWeight($this->_weight, $weightCode); if ($weight < 0.1) { $weight = 0.1; } else if ($weight > 150) { $weight = 150; } $packageWeight->addChild('Weight', $weight); /** * Quotes are wildly inaccurate when adding dimensions, they come out very expensive. * Not supplying dimensions returns quotes that are correct and equal to what is entered * even with dimensions on the UPS site (ie. weight must be the correct factor). */ $shipmentDimensions = $this->GetCombinedShipDimensions(); if($shipmentDimensions['width']+$shipmentDimensions['height']+$shipmentDimensions['length'] > 0) { $dimensions = $package->addChild('Dimensions'); $dimensions->addChild('UnitOfMeasurement')->addChild('Code', $dimensionsCode); $dimensions->addChild('Length', number_format(ConvertLength($shipmentDimensions['length'], $dimensionsCode),2, '.', '')); $dimensions->addChild('Width', number_format(ConvertLength($shipmentDimensions['width'], $dimensionsCode),2, '.', '')); $dimensions->addChild('Height', number_format(ConvertLength($shipmentDimensions['height'], $dimensionsCode),2, '.', '')); } $combinedXML = $accessRequest.$xml->asXML(); return $combinedXML; }
/** * Adds calculated rate details to the shipping details * * @param SimpleXMLElement $shippingDetails * @param ISC_ADMIN_EBAY_TEMPLATE $template * @return SimpleXMLElement */ private static function addCalculatedDetails(&$shippingDetails, $template) { $calculatedRate = $shippingDetails->addChild('CalculatedShippingRate'); $calculatedRate->addChild('MeasurementUnit', 'English'); $calculatedRate->addChild('OriginatingPostalCode', $template->getItemLocationZip()); // add dimensions - whole inches only $depth = round(ConvertLength($template->getItemDepth(), 'in')); $length = round(ConvertLength($template->getItemLength(), 'in')); $width = round(ConvertLength($template->getItemWidth(), 'in')); $depthXML = $calculatedRate->addChild('PackageDepth', $depth); $depthXML->addAttribute('measurementSystem', 'English'); $depthXML->addAttribute('unit', 'in'); $lengthXML = $calculatedRate->addChild('PackageLength', $length); $lengthXML->addAttribute('measurementSystem', 'English'); $lengthXML->addAttribute('unit', 'in'); $widthXML = $calculatedRate->addChild('PackageWidth', $width); $widthXML->addAttribute('measurementSystem', 'English'); $widthXML->addAttribute('unit', 'in'); //add weight in pounds and ounces $weightTotal = ConvertWeight($template->getItemWeight(), 'lbs'); $weightMajor = floor($weightTotal); $weightMinor = ConvertWeight($weightTotal - $weightMajor, 'ounces', 'lbs'); if ($weightMinor < 1) { $weightMinor = 1; } $calculatedRate->addChild('WeightMajor', $weightMajor); $calculatedRate->addChild('WeightMinor', $weightMinor); return $calculatedRate; }