You are here

class VisaCheckout in Commerce Authorize.Net 8

Provides the Authorize.net payment gateway.

Plugin annotation


@CommercePaymentGateway(
  id = "authorizenet_visa_checkout",
  label = "Authorize.net (Visa Checkout)",
  display_label = "Authorize.net (Visa Checkout)",
  forms = {
    "offsite-payment" = "Drupal\commerce_authnet\PluginForm\VisaCheckoutForm",
  },
  payment_method_types = {"credit_card"},
  credit_card_types = {
    "amex", "discover", "mastercard", "visa",
  },
  requires_billing_information = FALSE,
)

Hierarchy

Expanded class hierarchy of VisaCheckout

File

src/Plugin/Commerce/PaymentGateway/VisaCheckout.php, line 46

Namespace

Drupal\commerce_authnet\Plugin\Commerce\PaymentGateway
View source
class VisaCheckout extends OffsitePaymentGatewayBase {

  /**
   * 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 messenger sevice.
   *
   * @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, ClientInterface $client, LoggerInterface $logger, MessengerInterface $messenger) {
    parent::__construct($configuration, $plugin_id, $plugin_definition, $entity_type_manager, $payment_type_manager, $payment_method_type_manager, $time);
    $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->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('http_client'), $container
      ->get('commerce_authnet.logger'), $container
      ->get('messenger'));
  }

  /**
   * {@inheritdoc}
   */
  public function defaultConfiguration() {
    return [
      'api_login' => '',
      'transaction_key' => '',
      'client_key' => '',
      'visa_checkout_api_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,
    ];
    $form['visa_checkout_api_key'] = [
      '#type' => 'textfield',
      '#title' => $this
        ->t('Visa Checkout API Key'),
      '#description' => $this
        ->t('Follow the instructions <a href="https://developer.authorize.net/api/reference/features/visa_checkout.html#Enrolling_in_Visa_Checkout">here</a> to get an Visa Checkout API key.'),
      '#default_value' => $this->configuration['visa_checkout_api_key'],
      '#required' => TRUE,
    ];
    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['visa_checkout_api_key'] = $values['visa_checkout_api_key'];
      $this->configuration['api_login'] = $values['api_login'];
      $this->configuration['transaction_key'] = $values['transaction_key'];
      $this->configuration['client_key'] = $values['client_key'];
    }
  }

  /**
   * {@inheritdoc}
   */
  public function onReturn(OrderInterface $order, Request $request) {
    if ($request->request
      ->has('error')) {
      $error = $request->request
        ->get('error');
      return;
    }

    /** @var \Drupal\commerce_payment\Entity\PaymentInterface $payment */
    $payment = $request->request
      ->get('payment');
    $opaque_data_values = [
      'dataDescriptor' => OpaqueData::VISA_CHECKOUT,
      'dataValue' => $payment['encPaymentData'],
      'dataKey' => $payment['encKey'],
    ];
    $opaque_data = new OpaqueData($opaque_data_values);
    $decrypt_payment_data_request = new DecryptPaymentDataRequest($this->authnetConfiguration, $this->httpClient, $opaque_data, '', $payment['callid']);
    $response = $decrypt_payment_data_request
      ->execute();
    if ($response
      ->getResultCode() == 'Ok') {

      /** @var \Drupal\commerce_checkout\Entity\CheckoutFlowInterface $checkout_flow */
      $checkout_flow = $order
        ->get('checkout_flow')->entity;
      $capture = $checkout_flow
        ->getPlugin()
        ->getConfiguration()['panes']['payment_process']['capture'];
      $values = [
        'transactionType' => $capture ? 'authCaptureTransaction' : 'authOnlyTransaction',
        'amount' => $response
          ->contents()->paymentDetails->amount,
        'callId' => $payment['callid'],
      ];
      $transaction_request = new TransactionRequest($values);
      $payment_data = [
        'opaqueData' => $opaque_data_values,
      ];
      $transaction_request
        ->addData('payment', $payment_data);
      $retail = [
        'marketType' => 0,
        'deviceType' => 5,
      ];
      $transaction_request
        ->addData('retail', $retail);
      $create_transaction_request = new CreateTransactionRequest($this->authnetConfiguration, $this->httpClient);
      $create_transaction_request
        ->setTransactionRequest($transaction_request);
      $create_transaction_response = $create_transaction_request
        ->execute();
      if ($create_transaction_response
        ->getResultCode() != 'Ok') {
        $this
          ->logResponse($create_transaction_response);
        $message = $create_transaction_response
          ->getMessages()[0];
        throw new PaymentGatewayException($message
          ->getText());
      }
      if (!empty($create_transaction_response
        ->getErrors())) {
        $message = $create_transaction_response
          ->getErrors()[0];
        throw new HardDeclineException($message
          ->getText());
      }
      $payment_storage = $this->entityTypeManager
        ->getStorage('commerce_payment');
      $payment = $payment_storage
        ->create([
        'state' => $capture ? 'completed' : 'authorization',
        'amount' => new Price($response
          ->contents()->paymentDetails->amount, $response
          ->contents()->paymentDetails->currency),
        'payment_gateway' => $this->entityId,
        'order_id' => $order
          ->id(),
        'test' => $this
          ->getMode() == 'test',
        'remote_id' => $create_transaction_response
          ->contents()->transactionResponse->transId,
        'remote_state' => $create_transaction_response
          ->contents()->messages->message->text,
        'authorized' => $this->time
          ->getRequestTime(),
      ]);
      $payment
        ->save();
    }
  }

  /**
   * 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);
  }

  /**
   * 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),
    ]);
  }

}

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.
OffsitePaymentGatewayBase::getNotifyUrl public function Gets the URL to the "notify" page. Overrides OffsitePaymentGatewayInterface::getNotifyUrl
OffsitePaymentGatewayBase::onCancel public function Processes the "cancel" request. Overrides OffsitePaymentGatewayInterface::onCancel
OffsitePaymentGatewayBase::onNotify public function Processes the notification request. Overrides SupportsNotificationsInterface::onNotify
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::getDefaultForms protected function Gets the default payment gateway forms. 1
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.
VisaCheckout::$authnetConfiguration protected property The Authorize.net API configuration.
VisaCheckout::$httpClient protected property The HTTP client.
VisaCheckout::$logger protected property The logger.
VisaCheckout::$messenger protected property The messenger sevice. Overrides MessengerTrait::$messenger
VisaCheckout::buildConfigurationForm public function Form constructor. Overrides PaymentGatewayBase::buildConfigurationForm
VisaCheckout::create public static function Creates an instance of the plugin. Overrides PaymentGatewayBase::create
VisaCheckout::defaultConfiguration public function Gets default configuration for this plugin. Overrides PaymentGatewayBase::defaultConfiguration
VisaCheckout::describeResponse protected function Formats an API response as a string.
VisaCheckout::logResponse protected function Writes an API response to the log for debugging.
VisaCheckout::onReturn public function Processes the "return" request. Overrides OffsitePaymentGatewayBase::onReturn
VisaCheckout::submitConfigurationForm public function Form submission handler. Overrides PaymentGatewayBase::submitConfigurationForm
VisaCheckout::validateConfigurationForm public function Form validation handler. Overrides PaymentGatewayBase::validateConfigurationForm
VisaCheckout::__construct public function Constructs a new PaymentGatewayBase object. Overrides PaymentGatewayBase::__construct