You are here

function commerce_usps_build_rate_request in Commerce USPS 7

Builds the USPS rate request.

Parameters

object $order: The commerce order object

Return value

string A USPS Web Tools XML request string

1 call to commerce_usps_build_rate_request()
commerce_usps_rate in ./commerce_usps.module
Shipping service callback: returns a base price array for a shipping service calculated for the given order.

File

./commerce_usps.xml.inc, line 17
Handles rate request/response related stuff for the Commerce USPS module.

Code

function commerce_usps_build_rate_request($order) {
  $order_wrapper = entity_metadata_wrapper('commerce_order', $order);

  // Determine the shipping profile reference field name for the order.
  $field_name = commerce_physical_order_shipping_field_name($order);
  $shipping_profile = $order_wrapper->{$field_name}
    ->value();

  // Prepare the shipping address for use in the request.
  if (!empty($order_wrapper->{$field_name}->commerce_customer_address)) {
    $shipping_address = $order_wrapper->{$field_name}->commerce_customer_address
      ->value();
  }
  else {
    $shipping_address = addressfield_default_values();
  }

  // Get the orders weight and calculate lbs and ozs.
  // @todo: Create multiple packages if over 70 lbs.
  $weight = commerce_physical_order_weight($order, 'lb');

  // If order contains no weight skip sending request to usps.
  if (!is_array($weight) || $weight['weight'] == NULL) {
    return FALSE;
  }
  $ounces = 16 * ($weight['weight'] - floor($weight['weight']));
  $pounds = floor($weight['weight']);

  // Build a USPS request.
  // @todo: Implement additional options for more accurate shipping quotes
  // (see https://www.usps.com/webtools/htm/Rate-Calculators-v1-3.htm).
  $request = new SimpleXMLElement('<RateV4Request/>');
  $request
    ->addAttribute('USERID', variable_get('commerce_usps_user', ''));

  // Add a package to the request for each enabled service.
  $i = 1;
  foreach (variable_get('commerce_usps_services', array()) as $service) {
    if ($service) {
      $package = $request
        ->addChild('Package');
      $package
        ->addAttribute('ID', $i);
      $package
        ->addChild('Service', $service);
      $package
        ->addChild('FirstClassMailType', 'PARCEL');
      $package
        ->addChild('ZipOrigination', substr(variable_get('commerce_usps_postal_code', ''), 0, 5));
      $package
        ->addChild('ZipDestination', substr($shipping_address['postal_code'], 0, 5));
      $package
        ->addChild('Pounds', $pounds);
      $package
        ->addChild('Ounces', $ounces);
      $package
        ->addChild('Container', 'VARIABLE');
      $package
        ->addChild('Size', 'REGULAR');
      $package
        ->addChild('Machinable', 'TRUE');
      ++$i;
    }
  }
  return 'API=RateV4&XML=' . $request
    ->asXML();
}