You are here

public function Onsite::createPayment in Commerce Core 8.2

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

modules/payment_example/src/Plugin/Commerce/PaymentGateway/Onsite.php, line 90

Class

Onsite
Provides the On-site payment gateway.

Namespace

Drupal\commerce_payment_example\Plugin\Commerce\PaymentGateway

Code

public function createPayment(PaymentInterface $payment, $capture = TRUE) {
  $this
    ->assertPaymentState($payment, [
    'new',
  ]);
  $payment_method = $payment
    ->getPaymentMethod();
  $this
    ->assertPaymentMethod($payment_method);

  // Add a built in test for testing decline exceptions.
  // Note: Since requires_billing_information is FALSE, the payment method
  // is not guaranteed to have a billing profile. Confirm tha
  // $payment_method->getBillingProfile() is not NULL before trying to use it.
  if ($billing_profile = $payment_method
    ->getBillingProfile()) {

    /** @var \Drupal\address\Plugin\Field\FieldType\AddressItem $billing_address */
    $billing_address = $billing_profile
      ->get('address')
      ->first();
    if ($billing_address
      ->getPostalCode() == '53140') {
      throw new HardDeclineException('The payment was declined');
    }
  }

  // Perform the create payment request here, throw an exception if it fails.
  // See \Drupal\commerce_payment\Exception for the available exceptions.
  // Remember to take into account $capture when performing the request.
  $amount = $payment
    ->getAmount();
  $payment_method_token = $payment_method
    ->getRemoteId();

  // The remote ID returned by the request.
  $remote_id = '123456';
  $next_state = $capture ? 'completed' : 'authorization';
  $payment
    ->setState($next_state);
  $payment
    ->setRemoteId($remote_id);
  $payment
    ->setAvsResponseCode('A');
  if (!$payment_method->card_type
    ->isEmpty()) {
    $avs_response_code_label = $this
      ->buildAvsResponseCodeLabel('A', $payment_method->card_type->value);
    $payment
      ->setAvsResponseCodeLabel($avs_response_code_label);
  }
  $payment
    ->save();
}