Exemple #1
0
	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;
	}
		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;
		}
Exemple #3
0
 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;
     }
 }
 /**
  * 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.

			$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()
 {
     $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;
 }
Exemple #7
0
	/**
	 * 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;
	}