You are here

class SermepaForm in Commerce sermepa 8.2

Provides the Sermepa/Redsýs class for the payment form.

Hierarchy

Expanded class hierarchy of SermepaForm

File

src/PluginForm/OffsiteRedirect/SermepaForm.php, line 22

Namespace

Drupal\commerce_sermepa\PluginForm\OffsiteRedirect
View source
class SermepaForm extends BasePaymentOffsiteForm implements ContainerInjectionInterface {
  use StringTranslationTrait;

  /**
   * The entity type manager.
   *
   * @var \Drupal\Core\Entity\EntityTypeManagerInterface
   */
  protected $entityTypeManager;

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

  /**
   * The time service.
   *
   * @var \Drupal\Component\Datetime\TimeInterface
   */
  protected $time;

  /**
   * Constructs a new SermepaForm object.
   *
   * @param \Drupal\Core\Messenger\MessengerInterface $messenger
   *   The messenger service.
   * @param \Drupal\Component\Datetime\TimeInterface $time
   *   The time service.
   * @param \Drupal\Core\Entity\EntityTypeManagerInterface $entity_type_manager
   *   The entity type manager.
   */
  public function __construct(MessengerInterface $messenger, TimeInterface $time, EntityTypeManagerInterface $entity_type_manager) {
    $this->entityTypeManager = $entity_type_manager;
    $this->messenger = $messenger;
    $this->time = $time;
  }

  /**
   * {@inheritdoc}
   */
  public static function create(ContainerInterface $container) {
    return new static($container
      ->get('messenger'), $container
      ->get('datetime.time'), $container
      ->get('entity_type.manager'));
  }

  /**
   * {@inheritdoc}
   */
  public function buildConfigurationForm(array $form, FormStateInterface $form_state) {

    /** @var \Drupal\commerce_payment\Entity\PaymentInterface $payment */
    $payment = $this->entity;
    $order = $payment
      ->getOrder();

    /** @var \Drupal\commerce_payment\Plugin\Commerce\PaymentGateway\OffsitePaymentGatewayInterface $payment_gateway_plugin */
    $payment_gateway_plugin = $payment
      ->getPaymentGateway()
      ->getPlugin();

    // Get the gateway settings.
    $gateway_settings = $payment_gateway_plugin
      ->getConfiguration();
    $merchant_consumer_language = $payment_gateway_plugin
      ->getUnknowFallbackLanguage();

    // Create a new instance of the Sermepa library and initialize it.
    try {
      $gateway = new SermepaApi($gateway_settings['merchant_name'], $gateway_settings['merchant_code'], $gateway_settings['merchant_terminal'], $gateway_settings['merchant_password'], $payment_gateway_plugin
        ->getMode());

      // Configure the gateway transaction.
      $date = DrupalDateTime::createFromTimestamp($this->time
        ->getRequestTime());
      $parameters = FALSE;

      // Check if the payment currency code and the payment method settings are
      // the same.
      $currency_code = $payment
        ->getAmount()
        ->getCurrencyCode();

      /** @var \Drupal\commerce_price\Entity\CurrencyInterface $currency */
      $currency = $this->entityTypeManager
        ->getStorage('commerce_currency')
        ->load($currency_code);
      if ($currency
        ->getNumericCode() == $gateway_settings['currency']) {

        // Prepare the amount converting 120.00 or 120 to 12000.
        $amount = $payment
          ->getAmount()
          ->multiply(100)
          ->getNumber();
        $gateway
          ->setAmount($amount)
          ->setCurrency($gateway_settings['currency'])
          ->setOrder(substr($date
          ->format('ymdHis') . 'Id' . $order
          ->id(), -12, 12))
          ->setMerchantMerchantGroup($gateway_settings['merchant_group'])
          ->setPaymentMethod($gateway_settings['merchant_paymethods'])
          ->setConsumerLanguage($merchant_consumer_language)
          ->setMerchantData($order
          ->id())
          ->setTransactionType($gateway_settings['transaction_type'])
          ->setMerchantURL($payment_gateway_plugin
          ->getNotifyUrl()
          ->toString())
          ->setUrlKO($form['#cancel_url'])
          ->setUrlOK($form['#return_url']);

        // Get the transaction fields for the sermepa form.
        $parameters = $gateway
          ->composeMerchantParameters();
      }
    } catch (\Exception $exception) {
      watchdog_exception('commerce_sermepa', $exception);
    }
    if (empty($parameters)) {
      $this->messenger
        ->addError($this
        ->t('An error has been occurred trying of process the payment data, please contact with us.'));
      return $this
        ->redirectToPaymentInformationPane($order);
    }
    $data = [
      'Ds_SignatureVersion' => $gateway
        ->getSignatureVersion(),
      'Ds_MerchantParameters' => $parameters,
      'Ds_Signature' => $gateway
        ->composeMerchantSignature(),
    ];
    return $this
      ->buildRedirectForm($form, $form_state, $gateway
      ->getEnvironment(), $data, BasePaymentOffsiteForm::REDIRECT_POST);
  }

  /**
   * Redirects to the payment information pane on error.
   *
   * @param \Drupal\commerce_order\Entity\OrderInterface $order
   *   The order.
   *
   * @see \Drupal\commerce_payment\Plugin\Commerce\CheckoutPane\PaymentProcess::getErrorStepId()
   *
   * @throws \Drupal\commerce\Response\NeedsRedirectException
   */
  protected function redirectToPaymentInformationPane(OrderInterface $order) {
    try {

      /** @var \Drupal\commerce_checkout\Plugin\Commerce\CheckoutFlow\CheckoutFlowWithPanesInterface $checkout_flow */
      $checkout_flow = $order
        ->get('checkout_flow')
        ->first()
        ->get('entity')
        ->getTarget()
        ->getValue()
        ->getPlugin();
      $step_id = $checkout_flow
        ->getPane('payment_information')
        ->getStepId();
      if ($step_id == '_disabled') {

        // Can't redirect to the _disabled step. This could mean that
        // isVisible() was overridden to allow PaymentProcess to be used without
        // a payment_information pane, but this method was not modified.
        throw new \RuntimeException('Cannot get the step ID for the payment_information pane. The pane is disabled.');
      }
      $checkout_flow
        ->redirectToStep($step_id);
    } catch (\Exception $exception) {
      $redirect_url = Url::fromRoute('<front>', [
        'absolute' => TRUE,
      ])
        ->toString();
      throw new NeedsRedirectException($redirect_url);
    }
  }

}

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.
DependencySerializationTrait::__sleep public function 1
DependencySerializationTrait::__wakeup public function 2
PaymentGatewayFormBase::$entity protected property The form entity.
PaymentGatewayFormBase::getEntity public function Gets the form entity. Overrides PaymentGatewayFormInterface::getEntity
PaymentGatewayFormBase::getErrorElement public function Gets the form element to which errors should be assigned. Overrides PaymentGatewayFormInterface::getErrorElement 1
PaymentGatewayFormBase::setEntity public function Sets the form entity. Overrides PaymentGatewayFormInterface::setEntity
PaymentOffsiteForm::buildRedirectForm protected function Builds the redirect form.
PaymentOffsiteForm::processRedirectForm public static function Prepares the complete form for a POST redirect.
PaymentOffsiteForm::REDIRECT_GET constant
PaymentOffsiteForm::REDIRECT_POST constant
PaymentOffsiteForm::submitConfigurationForm public function Form submission handler. Overrides PluginFormInterface::submitConfigurationForm
PluginFormBase::$plugin protected property The plugin this form is for. 3
PluginFormBase::setPlugin public function Sets the plugin for this object. Overrides PluginAwareInterface::setPlugin 1
PluginFormBase::validateConfigurationForm public function Form validation handler. Overrides PluginFormInterface::validateConfigurationForm 2
SermepaForm::$entityTypeManager protected property The entity type manager.
SermepaForm::$messenger protected property The messenger service.
SermepaForm::$time protected property The time service.
SermepaForm::buildConfigurationForm public function Form constructor. Overrides PaymentOffsiteForm::buildConfigurationForm
SermepaForm::create public static function Instantiates a new instance of this class. Overrides ContainerInjectionInterface::create
SermepaForm::redirectToPaymentInformationPane protected function Redirects to the payment information pane on error.
SermepaForm::__construct public function Constructs a new SermepaForm object.
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.