You are here

function commerce_ups_api_request in Commerce UPS 7.2

Same name and namespace in other branches
  1. 7 commerce_ups.xml.inc \commerce_ups_api_request()

Submits an API request to the Progistics XML Processor.

Parameters

$method: A string value of the API method that is used to look up the endpoint.

$xml: An XML string to submit to the Progistics XML Processor.

$message: Optional log message to use for logged API requests.

Return value

mixed False if failed, SimpleXMLElement object if successful.

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

File

includes/commerce_ups.xml.inc, line 174
Handles XML-related stuff for Commerce UPS module.

Code

function commerce_ups_api_request($method, $xml, $message = '') {

  // Log the API request if specified.
  if (in_array('request', variable_get('commerce_ups_log', array()))) {
    if (empty($message)) {
      $message = t('Submitting API request to the UPS');
    }
    watchdog('ups', '@message:<pre>@xml</pre>', array(
      '@message' => $message,
      '@xml' => $xml,
    ));
  }

  // Determine the API endpoint for the method.
  $endpoint = commerce_ups_api_endpoint($method);

  // A valid endpoint is required to continue.
  if (empty($endpoint)) {
    watchdog('ups', 'Undefined endpoint for : @method', array(
      '@method' => $method,
    ), WATCHDOG_ERROR);
    return FALSE;
  }
  $ch = curl_init($endpoint);
  curl_setopt($ch, CURLOPT_HEADER, 0);
  curl_setopt($ch, CURLOPT_POST, 1);
  curl_setopt($ch, CURLOPT_TIMEOUT, 60);
  curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
  curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
  curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
  curl_setopt($ch, CURLOPT_POSTFIELDS, $xml);
  $result = curl_exec($ch);

  // Log any errors to the watchdog.
  if ($error = curl_error($ch)) {
    watchdog('ups', 'cURL error: @error', array(
      '@error' => $error,
    ), WATCHDOG_ERROR);
    return FALSE;
  }
  curl_close($ch);

  // If we received data back from the server...
  if (!empty($result)) {

    // Extract the result into an XML response object.
    try {
      $response = new SimpleXMLElement($result);
    } catch (Exception $ex) {
      watchdog('ups', 'Unable to parse response from UPS as XML: Response <pre>@response</pre>', array(
        '@response' => print_r($result, TRUE),
      ), WATCHDOG_WARNING);
      return FALSE;
    }

    // Log the API request if specified.
    if (in_array('response', variable_get('commerce_ups_log', array()))) {
      watchdog('ups', 'API response received:<pre>@xml</pre>', array(
        '@xml' => $response
          ->asXML(),
      ));
    }
    return $response;
  }
  else {
    return FALSE;
  }
}