You are here

public function AvataxLib::transactionsCreate in Drupal Commerce Connector for AvaTax 8

Creates a new transaction (/api/v2/transactions/create).

Parameters

\Drupal\commerce_order\Entity\OrderInterface $order: The order.

string $type: The transactions type (e.g SalesOrder|SalesInvoice).

Return value

array The response array.

Overrides AvataxLibInterface::transactionsCreate

File

src/AvataxLib.php, line 119

Class

AvataxLib
The AvaTax integration library.

Namespace

Drupal\commerce_avatax

Code

public function transactionsCreate(OrderInterface $order, $type = 'SalesOrder') {
  $request_body = $this
    ->prepareTransactionsCreate($order, $type);

  // Do not go further unless there have been lines added.
  if (empty($request_body['lines'])) {
    return [];
  }
  $cid = 'transactions_create:' . $order
    ->id();

  // Check if the response was cached, and return it in case the request
  // about to be performed is different than the one in cache.
  if ($cached = $this->cache
    ->get($cid)) {
    $cached_data = $cached->data;
    if (!empty($cached_data['response']) && isset($cached_data['request'])) {

      // The comparison would always fail if we wouldn't artificially override
      // the date here.
      $cached_data['request']['date'] = $request_body['date'];
      if ($cached_data['request'] == $request_body) {
        return $cached_data['response'];
      }
    }
  }
  $response_body = $this
    ->doRequest('POST', 'api/v2/transactions/create', [
    'json' => $request_body,
  ]);
  if (!empty($response_body)) {
    $this->moduleHandler
      ->alter('commerce_avatax_order_response', $response_body, $order);

    // Cache the request + the response for 24 hours.
    $expire = time() + 60 * 60 * 24;
    $this->cache
      ->set($cid, [
      'request' => $request_body,
      'response' => $response_body,
    ], $expire);
  }
  return $response_body;
}