You are here

class PurchaseOrderGateway in Commerce Purchase Order 8

Provides the On-site payment gateway.

Plugin annotation


@CommercePaymentGateway(
  id = "purchase_order_gateway",
  label = "Purchase Orders",
  display_label = "Purchase Orders",
   forms = {
    "receive-payment" =
  "Drupal\commerce_payment\PluginForm\PaymentReceiveForm",
    "add-payment-method" =
  "Drupal\commerce_purchase_order\PluginForm\PurchaseOrder\PaymentMethodAddForm",
  },
  payment_method_types = {"purchase_order"},
  payment_type = "payment_purchase_order"
)

Hierarchy

Expanded class hierarchy of PurchaseOrderGateway

File

src/Plugin/Commerce/PaymentGateway/PurchaseOrderGateway.php, line 34

Namespace

Drupal\commerce_purchase_order\Plugin\Commerce\PaymentGateway
View source
class PurchaseOrderGateway extends PaymentGatewayBase implements OnsitePaymentGatewayInterface, HasPaymentInstructionsInterface, SupportsVoidsInterface, SupportsRefundsInterface, ContainerFactoryPluginInterface {

  /**
   * {@inheritdoc}
   */
  public function getCreditCardTypes() {
    return [];
  }

  /**
   * {@inheritdoc}
   */
  public function defaultConfiguration() {
    return [
      'instructions' => [
        'value' => '',
        'format' => 'plain_text',
      ],
      'limit_open' => 1.0,
      'user_approval' => TRUE,
      'payment_method_types' => [
        'purchase_order',
      ],
    ] + parent::defaultConfiguration();
  }

  /**
   * {@inheritdoc}
   */
  public function buildConfigurationForm(array $form, FormStateInterface $form_state) {
    $form = parent::buildConfigurationForm($form, $form_state);
    $form['limit_open'] = [
      '#type' => 'number',
      '#title' => $this
        ->t('Limit maximum open purchase orders'),
      '#default_value' => $this->configuration['limit_open'],
      '#description' => $this
        ->t('During the authorization state at checkout, the transaction is denied if the number of unpaid payments exceeds this number.'),
      '#min' => 1,
      '#step' => 1.0,
      '#size' => 3,
    ];
    $form['user_approval'] = [
      '#type' => 'checkbox',
      '#title' => $this
        ->t('Purchase order users require approval in the user account settings.'),
      '#default_value' => $this->configuration['user_approval'],
    ];
    $form['instructions'] = [
      '#type' => 'text_format',
      '#title' => $this
        ->t('Payment instructions'),
      '#description' => $this
        ->t('Shown the end of checkout, after the customer has placed their order.'),
      '#default_value' => $this->configuration['instructions']['value'],
      '#format' => $this->configuration['instructions']['format'],
    ];
    return $form;
  }

  /**
   * {@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['instructions'] = $values['instructions'];
      $this->configuration['limit_open'] = (int) $values['limit_open'];
      $this->configuration['user_approval'] = (bool) $values['user_approval'];
    }
  }

  /**
   * {@inheritdoc}
   */
  public function buildPaymentOperations(PaymentInterface $payment) {
    $payment_state = $payment
      ->getState()->value;
    $operations = [];
    $operations['receive'] = [
      'title' => $this
        ->t('Receive'),
      'page_title' => $this
        ->t('Receive payment'),
      'plugin_form' => 'receive-payment',
      'weight' => -99,
      'access' => $payment_state == 'completed',
    ];
    $operations['void'] = [
      'title' => $this
        ->t('Void'),
      'page_title' => $this
        ->t('Void payment'),
      'plugin_form' => 'void-payment',
      'access' => $payment_state == 'completed',
      'weight' => 90,
    ];
    $operations['refund'] = [
      'title' => $this
        ->t('Refund'),
      'page_title' => $this
        ->t('Refund payment'),
      'plugin_form' => 'refund-payment',
      'access' => in_array($payment_state, [
        'completed',
        'partially_refunded',
      ]),
    ];
    return $operations;
  }

  /**
   * {@inheritdoc}
   */
  public function buildPaymentInstructions(PaymentInterface $payment) {
    $instructions = [];
    if (!empty($this->configuration['instructions']['value'])) {
      $instructions = [
        '#type' => 'processed_text',
        '#text' => $this->configuration['instructions']['value'],
        '#format' => $this->configuration['instructions']['format'],
      ];
    }
    return $instructions;
  }

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

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

    // If not specified, use the entire amount.
    $amount = $amount ?: $payment
      ->getAmount();
    $payment->state = 'paid';
    $payment
      ->setAmount($amount);
    $payment
      ->save();
  }

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

  /**
   * {@inheritdoc}
   */
  public function createPaymentMethod(PaymentMethodInterface $payment_method, array $payment_details) {
    $required_keys = [
      'number',
    ];
    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));
      }
    }

    // Not re-usable because we will store the PO number in the method.
    $payment_method
      ->setReusable(FALSE);
    $payment_method->po_number = $payment_details['number'];
    $payment_method
      ->setExpiresTime(strtotime("+60 day"));
    $payment_method
      ->save();
  }

  /**
   * {@inheritdoc}
   */
  public function deletePaymentMethod(PaymentMethodInterface $payment_method) {

    // There is no remote system.  These are only stored locally.
    $payment_method
      ->delete();
  }

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

    // If not specified, refund the entire amount.
    $amount = $amount ?: $payment
      ->getAmount();
    $this
      ->assertRefundAmount($payment, $amount);
    $old_refunded_amount = $payment
      ->getRefundedAmount();
    $new_refunded_amount = $old_refunded_amount
      ->add($amount);
    if ($new_refunded_amount
      ->lessThan($payment
      ->getAmount())) {
      $payment->state = 'partially_refunded';
    }
    else {
      $payment->state = 'refunded';
    }
    $payment
      ->setRefundedAmount($new_refunded_amount);
    $payment
      ->save();
  }

  /**
   * Authorizes payment based on settings in the gateway configuration.
   *
   * @param \Drupal\commerce_payment\Entity\PaymentInterface $payment
   *   The payment to authorize.
   */
  protected function authorizePayment(PaymentInterface $payment) {
    $customer = $payment
      ->getOrder()
      ->getCustomer();
    if ($this->configuration['user_approval']) {
      $user_approved = $customer
        ->hasField('field_purchase_orders_authorized') && !$customer
        ->get('field_purchase_orders_authorized')
        ->isEmpty() && $customer
        ->get('field_purchase_orders_authorized')
        ->first()->value;
    }
    else {

      // There is no user approval.
      $user_approved = TRUE;
    }
    if (!$user_approved) {
      $this
        ->messenger()
        ->addWarning($this
        ->t('Please contact us about using purchase orders for checkout.'));
    }
    $user_po_methods = $this->entityTypeManager
      ->getStorage('commerce_payment_method')
      ->loadByProperties([
      'uid' => $customer
        ->id(),
      'type' => 'purchase_order',
    ]);
    if (!empty($user_po_methods)) {
      $user_po_method_ids = [];
      foreach ($user_po_methods as $method) {
        $user_po_method_ids[] = $method
          ->id();
      }
      $payment_query = $this->entityTypeManager
        ->getStorage('commerce_payment')
        ->getQuery();
      $payment_query
        ->condition('payment_method', $user_po_method_ids, 'IN')
        ->condition('state', 'completed')
        ->count();
      $open_po_count = $payment_query
        ->execute();
    }
    else {
      $open_po_count = 0;
    }
    if ($user_approved && $open_po_count < $this->configuration['limit_open']) {
      $payment
        ->setState('authorized');
      $payment
        ->setAuthorizedTime($this->time
        ->getRequestTime());
    }
  }

  /**
   * Asserts that the payment successfully authorized.
   *
   * @param \Drupal\commerce_payment\Entity\PaymentInterface $payment
   *   The payment.
   *
   * @throws \Drupal\commerce_payment\Exception\HardDeclineException
   *   Thrown when the payment method did not authorize.
   */
  protected function assertAuthorized(PaymentInterface $payment) {
    if ($payment
      ->getState()->value != 'authorized') {
      throw new HardDeclineException('The purchase order failed to authorized.  Please contact a site administrator.');
    }
  }

}

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 protected property The messenger. 29
MessengerTrait::messenger public function Gets the messenger. 29
MessengerTrait::setMessenger public function Sets the messenger.
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::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::create public static function Creates an instance of the plugin. Overrides ContainerFactoryPluginInterface::create 2
PaymentGatewayBase::getConfiguration public function Gets this plugin's configuration. Overrides ConfigurableInterface::getConfiguration
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::validateConfigurationForm public function Form validation handler. Overrides PluginFormInterface::validateConfigurationForm
PaymentGatewayBase::__construct public function Constructs a new PaymentGatewayBase object. Overrides PluginBase::__construct 3
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
PurchaseOrderGateway::assertAuthorized protected function Asserts that the payment successfully authorized.
PurchaseOrderGateway::authorizePayment protected function Authorizes payment based on settings in the gateway configuration.
PurchaseOrderGateway::buildConfigurationForm public function Form constructor. Overrides PaymentGatewayBase::buildConfigurationForm
PurchaseOrderGateway::buildPaymentInstructions public function Builds the payment instructions. Overrides HasPaymentInstructionsInterface::buildPaymentInstructions
PurchaseOrderGateway::buildPaymentOperations public function Builds the available operations for the given payment. Overrides PaymentGatewayBase::buildPaymentOperations
PurchaseOrderGateway::createPayment public function Creates a payment. Overrides SupportsStoredPaymentMethodsInterface::createPayment
PurchaseOrderGateway::createPaymentMethod public function Creates a payment method with the given payment details. Overrides SupportsCreatingPaymentMethodsInterface::createPaymentMethod
PurchaseOrderGateway::defaultConfiguration public function Gets default configuration for this plugin. Overrides PaymentGatewayBase::defaultConfiguration
PurchaseOrderGateway::deletePaymentMethod public function Deletes the given payment method. Overrides SupportsStoredPaymentMethodsInterface::deletePaymentMethod
PurchaseOrderGateway::getCreditCardTypes public function Gets the credit card types handled by the gateway. Overrides PaymentGatewayBase::getCreditCardTypes
PurchaseOrderGateway::receivePayment public function
PurchaseOrderGateway::refundPayment public function Refunds the given payment. Overrides SupportsRefundsInterface::refundPayment
PurchaseOrderGateway::submitConfigurationForm public function Form submission handler. Overrides PaymentGatewayBase::submitConfigurationForm
PurchaseOrderGateway::voidPayment public function Voids the given payment. Overrides SupportsVoidsInterface::voidPayment
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.