function commerce_usps_rate_v4_request in Commerce USPS 7.2
Builds a domestics USPS rate request.
Parameters
object $order: The commerce order object.
object $shipping_address: The commerce_customer_address array of the shipping profile.
Return value
array An array of shipping rates.
1 call to commerce_usps_rate_v4_request()
- commerce_usps_rate in ./
commerce_usps.module - Returns a base price array for a shipping service calculated for the order.
File
- includes/
commerce_usps.xml.inc, line 19 - Handles rate request/response related stuff for the Commerce USPS module.
Code
function commerce_usps_rate_v4_request($order, $shipping_address) {
$rates = array();
$usps_services = commerce_usps_service_list('domestic');
$weight = commerce_usps_get_order_weight($order);
$request = new SimpleXMLElement('<RateV4Request/>');
$request
->addAttribute('USERID', variable_get('commerce_usps_user', ''));
$request
->addChild('Revision', 2);
// @TODO: Support multiple packages based on physical attributes.
// Add a package to the request for each enabled service.
$i = 1;
foreach (variable_get('commerce_usps_services', array()) as $machine_name => $service) {
if (!empty($service)) {
$package = $request
->addChild('Package');
$package
->addAttribute('ID', $i);
$package
->addChild('Service', $usps_services[$machine_name]['request_name']);
$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', $weight['pounds']);
$package
->addChild('Ounces', $weight['ounces']);
$package
->addChild('Container', 'VARIABLE');
$package
->addChild('Size', 'REGULAR');
$package
->addChild('Machinable', 'TRUE');
$i++;
}
}
drupal_alter('commerce_usps_rate_v4_request', $request);
// Submit the rate request to USPS.
$response = commerce_usps_api_request('API=RateV4&XML=' . $request
->asXML());
if (!empty($response->Package)) {
// Loop through each of the package results to build the rate array.
foreach ($response->Package as $package) {
if (empty($package->Error)) {
// Load the shipping service's class id from the package response.
$id = (string) $package->Postage
->attributes()->{'CLASSID'};
// Look up the shipping service by it's class id.
$usps_service = commerce_usps_service_by_id($id, 'domestic');
// Make sure that the package service is registered.
if (!empty($usps_service['machine_name'])) {
$rates[$usps_service['machine_name']] = array(
'amount' => commerce_currency_decimal_to_amount((string) $package->Postage->Rate, commerce_default_currency()),
'currency_code' => commerce_default_currency(),
'data' => array(),
);
}
}
}
}
return $rates;
}