You are here

abstract class OnsiteBase in Commerce Authorize.Net 8

Provides the Authorize.net payment gateway base class.

Hierarchy

Expanded class hierarchy of OnsiteBase

File

src/Plugin/Commerce/PaymentGateway/OnsiteBase.php, line 42

Namespace

Drupal\commerce_authnet\Plugin\Commerce\PaymentGateway
View source
abstract class OnsiteBase extends OnsitePaymentGatewayBase implements OnsitePaymentGatewayInterface, SupportsAuthorizationsInterface {

  /**
   * The adjustment transformer.
   *
   * @var \Drupal\commerce_order\AdjustmentTransformerInterface
   */
  protected $adjustmentTransformer;

  /**
   * The Authorize.net API configuration.
   *
   * @var \CommerceGuys\AuthNet\Configuration
   */
  protected $authnetConfiguration;

  /**
   * The HTTP client.
   *
   * @var \GuzzleHttp\Client
   */
  protected $httpClient;

  /**
   * The logger.
   *
   * @var \Psr\Log\LoggerInterface
   */
  protected $logger;

  /**
   * The private temp store factory.
   *
   * @var \Drupal\Core\TempStore\PrivateTempStoreFactory
   */
  protected $privateTempStore;

  /**
   * The messenger service.
   *
   * @var \Drupal\Core\Messenger\MessengerInterface
   */
  protected $messenger;

  /**
   * {@inheritdoc}
   */
  public function __construct(array $configuration, $plugin_id, $plugin_definition, EntityTypeManagerInterface $entity_type_manager, PaymentTypeManager $payment_type_manager, PaymentMethodTypeManager $payment_method_type_manager, TimeInterface $time, MinorUnitsConverterInterface $minor_units_converter, ClientInterface $client, LoggerInterface $logger, PrivateTempStoreFactory $private_tempstore, AdjustmentTransformerInterface $adjustment_transformer, MessengerInterface $messenger) {
    parent::__construct($configuration, $plugin_id, $plugin_definition, $entity_type_manager, $payment_type_manager, $payment_method_type_manager, $time, $minor_units_converter);
    $this->httpClient = $client;
    $this->logger = $logger;
    $this->authnetConfiguration = new Configuration([
      'sandbox' => $this
        ->getMode() == 'test',
      'api_login' => $this->configuration['api_login'],
      'transaction_key' => $this->configuration['transaction_key'],
      'client_key' => $this->configuration['client_key'],
    ]);
    $this->privateTempStore = $private_tempstore;
    $this->adjustmentTransformer = $adjustment_transformer;
    $this->messenger = $messenger;
  }

  /**
   * {@inheritdoc}
   */
  public static function create(ContainerInterface $container, array $configuration, $plugin_id, $plugin_definition) {
    return new static($configuration, $plugin_id, $plugin_definition, $container
      ->get('entity_type.manager'), $container
      ->get('plugin.manager.commerce_payment_type'), $container
      ->get('plugin.manager.commerce_payment_method_type'), $container
      ->get('datetime.time'), $container
      ->get('commerce_price.minor_units_converter'), $container
      ->get('http_client'), $container
      ->get('commerce_authnet.logger'), $container
      ->get('tempstore.private'), $container
      ->get('commerce_order.adjustment_transformer'), $container
      ->get('messenger'));
  }

  /**
   * {@inheritdoc}
   */
  public function defaultConfiguration() {
    return [
      'api_login' => '',
      'transaction_key' => '',
      'client_key' => '',
    ] + parent::defaultConfiguration();
  }

  /**
   * {@inheritdoc}
   */
  public function buildConfigurationForm(array $form, FormStateInterface $form_state) {
    $form = parent::buildConfigurationForm($form, $form_state);
    $form['api_login'] = [
      '#type' => 'textfield',
      '#title' => $this
        ->t('Login ID'),
      '#default_value' => $this->configuration['api_login'],
      '#required' => TRUE,
    ];
    $form['transaction_key'] = [
      '#type' => 'textfield',
      '#title' => $this
        ->t('Transaction Key'),
      '#default_value' => $this->configuration['transaction_key'],
      '#required' => TRUE,
    ];
    $form['client_key'] = [
      '#type' => 'textfield',
      '#title' => $this
        ->t('Client Key'),
      '#description' => $this
        ->t('Follow the instructions <a href="https://developer.authorize.net/api/reference/features/acceptjs.html#Obtaining_a_Public_Client_Key">here</a> to get a client key.'),
      '#default_value' => $this->configuration['client_key'],
      '#required' => TRUE,
    ];
    try {
      $url = Url::fromRoute('entity.commerce_checkout_flow.collection');
      $form['transaction_type'] = [
        '#markup' => $this
          ->t('<p>To configure the transaction settings, modify the <em>Payment process</em> pane in your checkout flow. From there you can choose authorization only or authorization and capture. You can manage your checkout flows here: <a href=":url">:url</a></p>', [
          ':url' => $url
            ->toString(),
        ]) . $this
          ->t('<p>For Echeck to work Transaction Details API needs to be enabled in your merchant account ("Account" => "Transaction Details API").</p>'),
      ];
    } catch (\Exception $e) {

      // Route was malformed, such as checkout not being enabled. So do nothing.
    }
    return $form;
  }

  /**
   * {@inheritdoc}
   */
  public function validateConfigurationForm(array &$form, FormStateInterface $form_state) {
    parent::validateConfigurationForm($form, $form_state);
    $values = $form_state
      ->getValue($form['#parents']);
    if (!empty($values['api_login']) && !empty($values['transaction_key'])) {
      $request = new XmlRequest(new Configuration([
        'sandbox' => $values['mode'] == 'test',
        'api_login' => $values['api_login'],
        'transaction_key' => $values['transaction_key'],
      ]), $this->httpClient, 'authenticateTestRequest');
      $request
        ->addDataType(new MerchantAuthentication([
        'name' => $values['api_login'],
        'transactionKey' => $values['transaction_key'],
      ]));
      $response = $request
        ->sendRequest();
      if ($response
        ->getResultCode() != 'Ok') {
        $this
          ->logResponse($response);
        $this->messenger
          ->addError($this
          ->describeResponse($response));
      }
    }
  }

  /**
   * {@inheritdoc}
   */
  public function submitConfigurationForm(array &$form, FormStateInterface $form_state) {
    parent::submitConfigurationForm($form, $form_state);
    if (!$form_state
      ->getErrors()) {
      $values = $form_state
        ->getValue($form['#parents']);
      $this->configuration['api_login'] = $values['api_login'];
      $this->configuration['transaction_key'] = $values['transaction_key'];
      $this->configuration['client_key'] = $values['client_key'];
    }
  }

  /**
   * {@inheritdoc}
   */
  public function capturePayment(PaymentInterface $payment, Price $amount = NULL) {
    $this
      ->assertPaymentState($payment, [
      'authorization',
    ]);

    // If not specified, capture the entire amount.
    $amount = $amount ?: $payment
      ->getAmount();
    $request = new CreateTransactionRequest($this->authnetConfiguration, $this->httpClient);
    $request
      ->setTransactionRequest(new TransactionRequest([
      'transactionType' => TransactionRequest::PRIOR_AUTH_CAPTURE,
      'amount' => $amount
        ->getNumber(),
      'refTransId' => $payment
        ->getRemoteId(),
    ]));
    $response = $request
      ->execute();
    if ($response
      ->getResultCode() != 'Ok') {
      $this
        ->logResponse($response);
      $message = $response
        ->getMessages()[0];
      throw new PaymentGatewayException($message
        ->getText());
    }
    $payment
      ->setState('completed');
    $payment
      ->setAmount($amount);
    $payment
      ->save();
  }

  /**
   * {@inheritdoc}
   */
  public function voidPayment(PaymentInterface $payment) {
    $this
      ->assertPaymentState($payment, [
      'authorization',
    ]);
    $request = new CreateTransactionRequest($this->authnetConfiguration, $this->httpClient);
    $request
      ->setTransactionRequest(new TransactionRequest([
      'transactionType' => TransactionRequest::VOID,
      'amount' => $payment
        ->getAmount()
        ->getNumber(),
      'refTransId' => $payment
        ->getRemoteId(),
    ]));
    $response = $request
      ->execute();
    if ($response
      ->getResultCode() != 'Ok') {
      $this
        ->logResponse($response);
      $message = $response
        ->getMessages()[0];
      throw new PaymentGatewayException($message
        ->getText());
    }
    $payment
      ->setState('authorization_voided');
    $payment
      ->save();
  }

  /**
   * {@inheritdoc}
   *
   * @todo Needs kernel test
   */
  public function deletePaymentMethod(PaymentMethodInterface $payment_method) {
    $owner = $payment_method
      ->getOwner();
    $customer_id = $this
      ->getRemoteCustomerId($owner);
    if (empty($customer_id)) {
      $customer_id = $this
        ->getPaymentMethodCustomerId($payment_method);
    }
    $request = new DeleteCustomerPaymentProfileRequest($this->authnetConfiguration, $this->httpClient);
    $request
      ->setCustomerProfileId($customer_id);
    $request
      ->setCustomerPaymentProfileId($this
      ->getRemoteProfileId($payment_method));
    $response = $request
      ->execute();
    if ($response
      ->getResultCode() != 'Ok') {
      $this
        ->logResponse($response);
      $message = $response
        ->getMessages()[0];

      // If the error is not "record not found" throw an error.
      if ($message
        ->getCode() != 'E00040') {
        throw new InvalidResponseException("Unable to delete payment method");
      }
    }
    $payment_method
      ->delete();
  }

  /**
   * Writes an API response to the log for debugging.
   *
   * @param \CommerceGuys\AuthNet\Response\ResponseInterface $response
   *   The API response object.
   */
  protected function logResponse(ResponseInterface $response) {
    $message = $this
      ->describeResponse($response);
    $level = $response
      ->getResultCode() === 'Error' ? 'error' : 'info';
    $this->logger
      ->log($level, $message);
  }

  /**
   * Returns the customer identifier from a payment method's remote id.
   *
   * @param \Drupal\commerce_payment\Entity\PaymentMethodInterface $payment_method
   *   The payment method.
   * @return mixed
   *   The remote customer id or FALSE if it cannot be resolved.
   */
  public function getPaymentMethodCustomerId(PaymentMethodInterface $payment_method) {
    $remote_id = $payment_method
      ->getRemoteId();
    if (strstr($remote_id, '|')) {
      $ids = explode('|', $remote_id);
      return reset($ids);
    }
    return FALSE;
  }

  /**
   * Returns the payment method remote identifier ensuring customer identifier is removed.
   *
   * @param \Drupal\commerce_payment\Entity\PaymentMethodInterface $payment_method
   *   The payment method.
   * @return string
   *   The remote id.
   */
  public function getRemoteProfileId(PaymentMethodInterface $payment_method) {
    $remote_id = $payment_method
      ->getRemoteId();
    $ids = explode('|', $remote_id);
    return end($ids);
  }

  /**
   * Formats an API response as a string.
   *
   * @param \CommerceGuys\AuthNet\Response\ResponseInterface $response
   *   The API response object.
   *
   * @return string
   *   The message.
   */
  protected function describeResponse(ResponseInterface $response) {
    $messages = [];
    foreach ($response
      ->getMessages() as $message) {
      $messages[] = $message
        ->getCode() . ': ' . $message
        ->getText();
    }
    return $this
      ->t('Received response with code %code from Authorize.net: @messages', [
      '%code' => $response
        ->getResultCode(),
      '@messages' => implode("\n", $messages),
    ]);
  }

  /**
   * Gets the line items from order.
   *
   * @param \Drupal\commerce_order\Entity\OrderInterface $order
   *   The order.
   *
   * @return \CommerceGuys\AuthNet\DataTypes\LineItem[]
   *   An array of line items.
   */
  protected function getLineItems(OrderInterface $order) {
    $line_items = [];
    foreach ($order
      ->getItems() as $order_item) {
      $name = $order_item
        ->label();
      $name = strlen($name) > 31 ? substr($name, 0, 28) . '...' : $name;
      $line_items[] = new LineItem([
        'itemId' => $order_item
          ->id(),
        'name' => $name,
        'quantity' => $order_item
          ->getQuantity(),
        'unitPrice' => $order_item
          ->getUnitPrice()
          ->getNumber(),
      ]);
    }
    return $line_items;
  }

  /**
   * Gets the tax from order.
   *
   * @param \Drupal\commerce_order\Entity\OrderInterface $order
   *   The order.
   *
   * @return \CommerceGuys\AuthNet\DataTypes\Tax
   *   The total tax.
   */
  protected function getTax(OrderInterface $order) {
    $amount = '0';
    $labels = [];
    $adjustments = $order
      ->collectAdjustments();
    if ($adjustments) {
      $adjustments = $this->adjustmentTransformer
        ->combineAdjustments($adjustments);
      $adjustments = $this->adjustmentTransformer
        ->roundAdjustments($adjustments);
      foreach ($adjustments as $adjustment) {
        if ($adjustment
          ->getType() !== 'tax') {
          continue;
        }
        $amount = Calculator::add($amount, $adjustment
          ->getAmount()
          ->getNumber());
        $labels[] = $adjustment
          ->getLabel();
      }
    }

    // Determine whether multiple tax types are present.
    $labels = array_unique($labels);
    if (empty($labels)) {
      $name = '';
      $description = '';
    }
    elseif (count($labels) > 1) {
      $name = 'Multiple Tax Types';
      $description = implode(', ', $labels);
    }
    else {
      $name = $labels[0];
      $description = $labels[0];
    }

    // Limit name, description fields to 32, 255 characters.
    $name = strlen($name) > 31 ? substr($name, 0, 28) . '...' : $name;
    $description = strlen($description) > 255 ? substr($description, 0, 252) . '...' : $description;

    // If amount is negative, do not transmit any information.
    if ($amount < 0) {
      $amount = 0;
      $name = '';
      $description = '';
    }
    return new Tax([
      'amount' => $amount,
      'name' => $name,
      'description' => $description,
    ]);
  }

  /**
   * Gets the shipping from order.
   *
   * @param \Drupal\commerce_order\Entity\OrderInterface $order
   *   The order.
   *
   * @return \CommerceGuys\AuthNet\DataTypes\Shipping
   *   The total shipping.
   */
  protected function getShipping(OrderInterface $order) {

    // Return empty if there is no shipments field.
    if (!$order
      ->hasField('shipments')) {
      return new Shipping([
        'amount' => 0,
        'name' => '',
        'description' => '',
      ]);
    }
    $amount = '0';
    $labels = [];

    /** @var \Drupal\commerce_shipping\Entity\ShipmentInterface[] $shipments */
    $shipments = $order
      ->get('shipments')
      ->referencedEntities();
    if ($shipments) {
      foreach ($shipments as $shipment) {

        // Shipments without an amount are incomplete / unrated.
        if ($shipment_amount = $shipment
          ->getAmount()) {
          $amount = Calculator::add($amount, $shipment_amount
            ->getNumber());
          $labels[] = $shipment
            ->label();
        }
      }
    }

    // Determine whether multiple tax types are present.
    $labels = array_unique($labels);
    if (empty($labels)) {
      $name = '';
      $description = '';
    }
    elseif (count($labels) > 1) {
      $name = 'Multiple shipments';
      $description = implode(', ', $labels);
    }
    else {
      $name = $labels[0];
      $description = $labels[0];
    }

    // Limit name, description fields to 32, 255 characters.
    $name = strlen($name) > 31 ? substr($name, 0, 28) . '...' : $name;
    $description = strlen($description) > 255 ? substr($description, 0, 252) . '...' : $description;
    return new Shipping([
      'amount' => $amount,
      'name' => $name,
      'description' => $description,
    ]);
  }

}

Members

Namesort descending Modifiers Type Description Overrides
DependencySerializationTrait::$_entityStorages protected property An array of entity type IDs keyed by the property name of their storages.
DependencySerializationTrait::$_serviceIds protected property An array of service IDs keyed by property name used for serialization.
MessengerTrait::messenger public function Gets the messenger. 29
MessengerTrait::setMessenger public function Sets the messenger.
OnsiteBase::$adjustmentTransformer protected property The adjustment transformer.
OnsiteBase::$authnetConfiguration protected property The Authorize.net API configuration.
OnsiteBase::$httpClient protected property The HTTP client.
OnsiteBase::$logger protected property The logger.
OnsiteBase::$messenger protected property The messenger service. Overrides MessengerTrait::$messenger
OnsiteBase::$privateTempStore protected property The private temp store factory.
OnsiteBase::buildConfigurationForm public function Form constructor. Overrides OnsitePaymentGatewayBase::buildConfigurationForm 1
OnsiteBase::capturePayment public function Captures the given authorized payment. Overrides SupportsAuthorizationsInterface::capturePayment 1
OnsiteBase::create public static function Creates an instance of the plugin. Overrides PaymentGatewayBase::create
OnsiteBase::defaultConfiguration public function Gets default configuration for this plugin. Overrides PaymentGatewayBase::defaultConfiguration 1
OnsiteBase::deletePaymentMethod public function @todo Needs kernel test Overrides SupportsStoredPaymentMethodsInterface::deletePaymentMethod
OnsiteBase::describeResponse protected function Formats an API response as a string.
OnsiteBase::getLineItems protected function Gets the line items from order. 1
OnsiteBase::getPaymentMethodCustomerId public function Returns the customer identifier from a payment method's remote id.
OnsiteBase::getRemoteProfileId public function Returns the payment method remote identifier ensuring customer identifier is removed.
OnsiteBase::getShipping protected function Gets the shipping from order.
OnsiteBase::getTax protected function Gets the tax from order.
OnsiteBase::logResponse protected function Writes an API response to the log for debugging.
OnsiteBase::submitConfigurationForm public function Form submission handler. Overrides PaymentGatewayBase::submitConfigurationForm 1
OnsiteBase::validateConfigurationForm public function Form validation handler. Overrides PaymentGatewayBase::validateConfigurationForm
OnsiteBase::voidPayment public function Voids the given payment. Overrides SupportsVoidsInterface::voidPayment 1
OnsiteBase::__construct public function Constructs a new PaymentGatewayBase object. Overrides PaymentGatewayBase::__construct
OnsitePaymentGatewayBase::getDefaultForms protected function Gets the default payment gateway forms. Overrides PaymentGatewayBase::getDefaultForms
PaymentGatewayBase::$entityId Deprecated protected property The ID of the parent config entity.
PaymentGatewayBase::$entityTypeManager protected property The entity type manager.
PaymentGatewayBase::$minorUnitsConverter protected property The minor units converter.
PaymentGatewayBase::$parentEntity protected property The parent config entity.
PaymentGatewayBase::$paymentMethodTypes protected property The payment method types handled by the gateway.
PaymentGatewayBase::$paymentType protected property The payment type used by the gateway.
PaymentGatewayBase::$time protected property The time.
PaymentGatewayBase::assertPaymentMethod protected function Asserts that the payment method is neither empty nor expired.
PaymentGatewayBase::assertPaymentState protected function Asserts that the payment state matches one of the allowed states.
PaymentGatewayBase::assertRefundAmount protected function Asserts that the refund amount is valid.
PaymentGatewayBase::buildAvsResponseCodeLabel public function Builds a label for the given AVS response code and card type. Overrides PaymentGatewayInterface::buildAvsResponseCodeLabel 2
PaymentGatewayBase::buildPaymentOperations public function Builds the available operations for the given payment. Overrides PaymentGatewayInterface::buildPaymentOperations 1
PaymentGatewayBase::calculateDependencies public function Calculates dependencies for the configured plugin. Overrides DependentPluginInterface::calculateDependencies
PaymentGatewayBase::canCapturePayment public function
PaymentGatewayBase::canRefundPayment public function
PaymentGatewayBase::canVoidPayment public function
PaymentGatewayBase::collectsBillingInformation public function Gets whether the payment gateway collects billing information. Overrides PaymentGatewayInterface::collectsBillingInformation
PaymentGatewayBase::getConfiguration public function Gets this plugin's configuration. Overrides ConfigurableInterface::getConfiguration
PaymentGatewayBase::getCreditCardTypes public function Gets the credit card types handled by the gateway. Overrides PaymentGatewayInterface::getCreditCardTypes
PaymentGatewayBase::getDefaultPaymentMethodType public function Gets the default payment method type. Overrides PaymentGatewayInterface::getDefaultPaymentMethodType
PaymentGatewayBase::getDisplayLabel public function Gets the payment gateway display label. Overrides PaymentGatewayInterface::getDisplayLabel
PaymentGatewayBase::getJsLibrary public function Gets the JS library ID. Overrides PaymentGatewayInterface::getJsLibrary
PaymentGatewayBase::getLabel public function Gets the payment gateway label. Overrides PaymentGatewayInterface::getLabel
PaymentGatewayBase::getMode public function Gets the mode in which the payment gateway is operating. Overrides PaymentGatewayInterface::getMode
PaymentGatewayBase::getPaymentMethodTypes public function Gets the payment method types handled by the payment gateway. Overrides PaymentGatewayInterface::getPaymentMethodTypes
PaymentGatewayBase::getPaymentType public function Gets the payment type used by the payment gateway. Overrides PaymentGatewayInterface::getPaymentType
PaymentGatewayBase::getRemoteCustomerId protected function Gets the remote customer ID for the given user.
PaymentGatewayBase::getSupportedModes public function Gets the supported modes. Overrides PaymentGatewayInterface::getSupportedModes
PaymentGatewayBase::setConfiguration public function Sets the configuration for this plugin instance. Overrides ConfigurableInterface::setConfiguration
PaymentGatewayBase::setRemoteCustomerId protected function Sets the remote customer ID for the given user.
PaymentGatewayBase::toMinorUnits public function Converts the given amount to its minor units. Overrides PaymentGatewayInterface::toMinorUnits
PaymentGatewayBase::__sleep public function Overrides DependencySerializationTrait::__sleep
PaymentGatewayBase::__wakeup public function Overrides DependencySerializationTrait::__wakeup
PluginBase::$configuration protected property Configuration information passed into the plugin. 1
PluginBase::$pluginDefinition protected property The plugin implementation definition. 1
PluginBase::$pluginId protected property The plugin_id.
PluginBase::DERIVATIVE_SEPARATOR constant A string which is used to separate base plugin IDs from the derivative ID.
PluginBase::getBaseId public function Gets the base_plugin_id of the plugin instance. Overrides DerivativeInspectionInterface::getBaseId
PluginBase::getDerivativeId public function Gets the derivative_id of the plugin instance. Overrides DerivativeInspectionInterface::getDerivativeId
PluginBase::getPluginDefinition public function Gets the definition of the plugin implementation. Overrides PluginInspectionInterface::getPluginDefinition 3
PluginBase::getPluginId public function Gets the plugin_id of the plugin instance. Overrides PluginInspectionInterface::getPluginId
PluginBase::isConfigurable public function Determines if the plugin is configurable.
PluginWithFormsTrait::getFormClass public function
PluginWithFormsTrait::hasFormClass public function
StringTranslationTrait::$stringTranslation protected property The string translation service. 1
StringTranslationTrait::formatPlural protected function Formats a string containing a count of items.
StringTranslationTrait::getNumberOfPlurals protected function Returns the number of plurals supported by a given language.
StringTranslationTrait::getStringTranslation protected function Gets the string translation service.
StringTranslationTrait::setStringTranslation public function Sets the string translation service to use. 2
StringTranslationTrait::t protected function Translates a string to the current language or to a given language.
SupportsCreatingPaymentMethodsInterface::createPaymentMethod public function Creates a payment method with the given payment details. 1
SupportsStoredPaymentMethodsInterface::createPayment public function Creates a payment. 2