You are here

public function HostedFields::createPayment in Commerce Braintree 8

Creates a payment.

Parameters

\Drupal\commerce_payment\Entity\PaymentInterface $payment: The payment.

bool $capture: Whether the created payment should be captured (VS authorized only). Allowed to be FALSE only if the plugin supports authorizations.

Throws

\InvalidArgumentException If $capture is FALSE but the plugin does not support authorizations.

\Drupal\commerce_payment\Exception\PaymentGatewayException Thrown when the transaction fails for any reason.

Overrides SupportsStoredPaymentMethodsInterface::createPayment

File

src/Plugin/Commerce/PaymentGateway/HostedFields.php, line 209

Class

HostedFields
Provides the HostedFields payment gateway.

Namespace

Drupal\commerce_braintree\Plugin\Commerce\PaymentGateway

Code

public function createPayment(PaymentInterface $payment, $capture = TRUE) {
  $this
    ->assertPaymentState($payment, [
    'new',
  ]);
  $payment_method = $payment
    ->getPaymentMethod();
  $this
    ->assertPaymentMethod($payment_method);
  $amount = $payment
    ->getAmount();
  $currency_code = $payment
    ->getAmount()
    ->getCurrencyCode();
  if (empty($this->configuration['merchant_account_id'][$currency_code])) {
    throw new InvalidRequestException(sprintf('No merchant account ID configured for currency %s', $currency_code));
  }
  $transaction_data = [
    'channel' => 'CommerceGuys_BT_Vzero',
    'merchantAccountId' => $this->configuration['merchant_account_id'][$currency_code],
    // orderId must be unique.
    'orderId' => $payment
      ->getOrderId() . '-' . $this->time
      ->getCurrentTime(),
    'amount' => $amount
      ->getNumber(),
    'options' => [
      'submitForSettlement' => $capture,
    ],
  ];
  if ($payment_method
    ->isReusable()) {
    $transaction_data['paymentMethodToken'] = $payment_method
      ->getRemoteId();
  }
  else {
    $transaction_data['paymentMethodNonce'] = $payment_method
      ->getRemoteId();
  }

  // Add metadata and extra transaction data where required.
  $event = new TransactionDataEvent($transaction_data, $payment);
  $this->eventDispatcher
    ->dispatch(BraintreeEvents::TRANSACTION_DATA, $event);
  $transaction_data = $event
    ->getTransactionData();
  try {
    $result = $this->api
      ->transaction()
      ->sale($transaction_data);
    ErrorHelper::handleErrors($result);
  } catch (BraintreeException $e) {
    ErrorHelper::handleException($e);
  }
  $next_state = $capture ? 'completed' : 'authorization';
  $payment
    ->setState($next_state);
  $payment
    ->setRemoteId($result->transaction->id);

  // @todo Find out how long an authorization is valid, set its expiration.
  $payment
    ->save();
}