You are here

class Echeck in Commerce Authorize.Net 8

Provides the Authorize.net echeck payment gateway.

Plugin annotation


@CommercePaymentGateway(
  id = "authorizenet_echeck",
  label = "Authorize.net (Echeck)",
  display_label = "Authorize.net Echeck",
  forms = {
    "add-payment-method" = "Drupal\commerce_authnet\PluginForm\EcheckAddForm",
  },
  payment_type = "payment_manual",
  payment_method_types = {"authnet_echeck"},
  requires_billing_information = FALSE,
)

Hierarchy

Expanded class hierarchy of Echeck

1 file declares its use of Echeck
EcheckTransactionVerifier.php in src/EcheckTransactionVerifier.php
1 string reference to 'Echeck'
commerce_authnet_post_update_echeck in ./commerce_authnet.post_update.php
Separate echeck payment gateways from accept.js and update all affected payment_methods and payments.

File

src/Plugin/Commerce/PaymentGateway/Echeck.php, line 33

Namespace

Drupal\commerce_authnet\Plugin\Commerce\PaymentGateway
View source
class Echeck extends OnsiteBase implements EcheckInterface {

  /**
   * {@inheritdoc}
   */
  public function createPayment(PaymentInterface $payment, $capture = TRUE) {
    $this
      ->assertPaymentState($payment, [
      'new',
    ]);
    $payment_method = $payment
      ->getPaymentMethod();
    $this
      ->assertPaymentMethod($payment_method);
    $order = $payment
      ->getOrder();

    // Transaction request.
    // eChecks have a pseudo "authorized" state, so just do AUTH_CAPTURE.
    $transaction_request = new TransactionRequest([
      'transactionType' => TransactionRequest::AUTH_CAPTURE,
      'amount' => $payment
        ->getAmount()
        ->getNumber(),
    ]);
    list($data_descriptor, $data_value) = explode('|', $payment_method
      ->getRemoteId());
    $payment_data = [
      'opaqueData' => [
        'dataDescriptor' => $data_descriptor,
        'dataValue' => $data_value,
      ],
    ];
    $transaction_request
      ->addData('payment', $payment_data);
    if ($billing_profile = $payment_method
      ->getBillingProfile()) {

      /** @var \Drupal\address\AddressInterface $address */
      $address = $billing_profile
        ->get('address')
        ->first();
      $bill_to = [
        // @todo how to allow customizing this.
        'firstName' => $address
          ->getGivenName(),
        'lastName' => $address
          ->getFamilyName(),
        'company' => $address
          ->getOrganization(),
        'address' => substr($address
          ->getAddressLine1() . ' ' . $address
          ->getAddressLine2(), 0, 60),
        'country' => $address
          ->getCountryCode(),
        'city' => $address
          ->getLocality(),
        'state' => $address
          ->getAdministrativeArea(),
        'zip' => $address
          ->getPostalCode(),
      ];
      $transaction_request
        ->addDataType(new BillTo(array_filter($bill_to)));
    }
    $profiles = $order
      ->collectProfiles();
    if (isset($profiles['shipping']) && !$profiles['shipping']
      ->get('address')
      ->isEmpty()) {

      /** @var \Drupal\address\Plugin\Field\FieldType\AddressItem $shipping_address */
      $shipping_address = $profiles['shipping']
        ->get('address')
        ->first();
      $ship_data = [
        // @todo how to allow customizing this.
        'firstName' => $shipping_address
          ->getGivenName(),
        'lastName' => $shipping_address
          ->getFamilyName(),
        'address' => substr($shipping_address
          ->getAddressLine1() . ' ' . $shipping_address
          ->getAddressLine2(), 0, 60),
        'country' => $shipping_address
          ->getCountryCode(),
        'company' => $shipping_address
          ->getOrganization(),
        'city' => $shipping_address
          ->getLocality(),
        'state' => $shipping_address
          ->getAdministrativeArea(),
        'zip' => $shipping_address
          ->getPostalCode(),
      ];
      $transaction_request
        ->addDataType(new ShipTo(array_filter($ship_data)));
    }

    // Adding order information to the transaction.
    $transaction_request
      ->addOrder(new OrderDataType([
      'invoiceNumber' => $order
        ->getOrderNumber() ?: $order
        ->id(),
    ]));
    $transaction_request
      ->addData('customerIP', $order
      ->getIpAddress());

    // Adding line items.
    $line_items = $this
      ->getLineItems($order);
    foreach ($line_items as $line_item) {
      $transaction_request
        ->addLineItem($line_item);
    }

    // Adding tax information to the transaction.
    $transaction_request
      ->addData('tax', $this
      ->getTax($order)
      ->toArray());
    $transaction_request
      ->addData('shipping', $this
      ->getShipping($order)
      ->toArray());
    $request = new CreateTransactionRequest($this->authnetConfiguration, $this->httpClient);
    $request
      ->setTransactionRequest($transaction_request);
    $response = $request
      ->execute();
    if ($response
      ->getResultCode() != 'Ok') {
      $this
        ->logResponse($response);
      $message = $response
        ->getMessages()[0];
      switch ($message
        ->getCode()) {
        case 'E00040':
          $payment_method
            ->delete();
          throw new PaymentGatewayException('The provided payment method is no longer valid');
        default:
          throw new PaymentGatewayException($message
            ->getText());
      }
    }
    if (!empty($response
      ->getErrors())) {
      $message = $response
        ->getErrors()[0];
      throw new HardDeclineException($message
        ->getText());
    }

    // Mark the payment as pending as we await for transaction details from
    // Authorize.net.
    $payment
      ->setState('pending');
    $payment
      ->setRemoteId($response->transactionResponse->transId);
    $payment
      ->save();
  }

  /**
   * {@inheritdoc}
   */
  public function capturePayment(PaymentInterface $payment, Price $amount = NULL) {

    // If not specified, capture the entire amount.
    $amount = $amount ?: $payment
      ->getAmount();
    $this
      ->assertPaymentState($payment, [
      'pending',
    ]);
    $payment
      ->setState('completed');
    $payment
      ->setAmount($amount);
    $payment
      ->save();
  }

  /**
   * {@inheritdoc}
   */
  public function voidPayment(PaymentInterface $payment) {
    $this
      ->assertPaymentState($payment, [
      'pending',
    ]);
    $payment
      ->setState('voided');
    $payment
      ->save();
  }

  /**
   * {@inheritdoc}
   *
   * @todo Needs kernel test
   */
  public function createPaymentMethod(PaymentMethodInterface $payment_method, array $payment_details) {
    $required_keys = [
      'data_descriptor',
      'data_value',
    ];
    foreach ($required_keys as $required_key) {
      if (empty($payment_details[$required_key])) {
        throw new \InvalidArgumentException(sprintf('$payment_details must contain the %s key.', $required_key));
      }
    }

    // Reusing echecks is not supported at the moment.
    // @see https://community.developer.authorize.net/t5/Integration-and-Testing/Accept-JS-and-ACH/td-p/55874
    $payment_method
      ->setReusable(FALSE);
    $payment_method
      ->setRemoteId($payment_details['data_descriptor'] . '|' . $payment_details['data_value']);

    // OpaqueData expire after 15min. We reduce that time by 5s to account for
    // the time it took to do the server request after the JS tokenization.
    $expires = $this->time
      ->getRequestTime() + 15 * 60 - 5;
    $payment_method
      ->setExpiresTime($expires);
    $payment_method
      ->save();
  }

  /**
   * {@inheritdoc}
   */
  public function getSettledTransactions($from_date, $to_date) {
    $request = new GetSettledBatchListRequest($this->authnetConfiguration, $this->httpClient, FALSE, $from_date, $to_date);
    $batch_response = $request
      ->execute();
    $batch_ids = [];
    if ($batch_response
      ->getResultCode() === 'Ok') {
      if (is_object($batch_response
        ->contents()->batchList->batch)) {
        if ($batch_response
          ->contents()->batchList->batch->paymentMethod === 'eCheck') {
          if ($batch_response
            ->contents()->batchList->batch->settlementState === 'settledSuccessfully') {
            $batch_ids[] = $batch_response
              ->contents()->batchList->batch->batchId;
          }
        }
      }
      else {
        foreach ($batch_response
          ->contents()->batchList->batch as $batch) {
          if ($batch->paymentMethod === 'eCheck') {
            if ($batch->settlementState === 'settledSuccessfully') {
              $batch_ids[] = $batch->batchId;
            }
          }
        }
      }
    }
    $remote_ids = [];
    foreach ($batch_ids as $batch_id) {
      $request = new GetTransactionListRequest($this->authnetConfiguration, $this->httpClient, $batch_id);
      $transaction_list_response = $request
        ->execute();
      if ($transaction_list_response
        ->contents()->totalNumInResultSet == 1) {
        $remote_ids[] = $transaction_list_response
          ->contents()->transactions->transaction->transId;
      }
      else {
        foreach ($transaction_list_response
          ->contents()->transactions->transaction as $transaction) {
          $remote_ids[] = $transaction->transId;
        }
      }
    }
    $payments = [];
    if ($remote_ids) {
      $payment_storage = $this->entityTypeManager
        ->getStorage('commerce_payment');
      $payment_ids = $payment_storage
        ->getQuery()
        ->condition('state', 'pending')
        ->condition('remote_id', $remote_ids)
        ->execute();
      if ($payment_ids) {
        $payments = $payment_storage
          ->loadMultiple($payment_ids);
      }
    }
    return $payments;
  }

}

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.
Echeck::capturePayment public function Captures the given authorized payment. Overrides OnsiteBase::capturePayment
Echeck::createPayment public function Creates a payment. Overrides SupportsStoredPaymentMethodsInterface::createPayment
Echeck::createPaymentMethod public function @todo Needs kernel test Overrides SupportsCreatingPaymentMethodsInterface::createPaymentMethod
Echeck::getSettledTransactions public function Get settled transactions from authorize.net. Overrides EcheckInterface::getSettledTransactions
Echeck::voidPayment public function Voids the given payment. Overrides OnsiteBase::voidPayment
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::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::__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.