You are here

public function Checkout::createPaymentMethod in Commerce PayPal 8

Creates a payment method with the given payment details.

Parameters

\Drupal\commerce_payment\Entity\PaymentMethodInterface $payment_method: The payment method.

array $payment_details: The gateway-specific payment details provided by the payment method form for on-site gateways, or the incoming request for off-site gateways.

Throws

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

Overrides SupportsCreatingPaymentMethodsInterface::createPaymentMethod

File

src/Plugin/Commerce/PaymentGateway/Checkout.php, line 699

Class

Checkout
Provides the PayPal Checkout payment gateway.

Namespace

Drupal\commerce_paypal\Plugin\Commerce\PaymentGateway

Code

public function createPaymentMethod(PaymentMethodInterface $payment_method, array $payment_details) {
  if (empty($payment_details['paypal_remote_id'])) {
    throw new PaymentGatewayException('Cannot create the payment method without the PayPal order ID.');
  }
  try {
    $sdk = $this->checkoutSdkFactory
      ->get($this->configuration);
    $request = $sdk
      ->getOrder($payment_details['paypal_remote_id']);
    $paypal_order = Json::decode($request
      ->getBody());
  } catch (BadResponseException $exception) {
    throw new PaymentGatewayException($exception
      ->getResponse()
      ->getBody()
      ->getContents());
  }

  // Check if we have information about the card used.
  if (isset($paypal_order['payment_source']['card'])) {
    $payment_source = $paypal_order['payment_source']['card'];

    // Remove any character that isn't A-Z, a-z or 0-9.
    $payment_source['brand'] = strtolower(preg_replace("/[^A-Za-z0-9]/", '', $payment_source['brand']));

    // We should in theory map the credit card type we get from PayPal to one
    // expected by us, but the credit card types are not correctly documented.
    // For example, ("Mastercard" is sent as "MASTER_CARD" but documented
    // as "MASTERCARD").
    $card_types = CreditCard::getTypes();
    if (!isset($card_types[$payment_source['brand']])) {
      throw new HardDeclineException(sprintf('Unsupported credit card type "%s".', $paypal_order['payment_source']['card']));
    }
    $payment_method
      ->set('card_type', $payment_source['brand']);
    $payment_method
      ->set('card_number', $payment_source['last_digits']);
  }
  $payment_method
    ->setRemoteId($paypal_order['id']);
  $payment_method
    ->setReusable(FALSE);
  $payment_method
    ->save();
}