You are here

public function Square::createPaymentMethod in Commerce Square Connect 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/Square.php, line 317

Class

Square
Provides the Square payment gateway.

Namespace

Drupal\commerce_square\Plugin\Commerce\PaymentGateway

Code

public function createPaymentMethod(PaymentMethodInterface $payment_method, array $payment_details) {
  $required_keys = [
    'payment_method_nonce',
    'card_type',
    'last4',
  ];
  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));
    }
  }

  // @todo Make payment methods reusable. Currently they represent 24hr nonce.
  // @see https://docs.connect.squareup.com/articles/processing-recurring-payments-ruby
  // Meet specific requirements for reusable, permanent methods.
  $payment_method
    ->setReusable(FALSE);
  $payment_method->card_type = $this
    ->mapCreditCardType($payment_details['card_type']);
  $payment_method->card_number = $payment_details['last4'];
  $payment_method->card_exp_month = $payment_details['exp_month'];
  $payment_method->card_exp_year = $payment_details['exp_year'];
  $remote_id = $payment_details['payment_method_nonce'];
  $payment_method
    ->setRemoteId($remote_id);

  // Nonces expire after 24h. We reduce that time by 5s to account for the
  // time it took to do the server request after the JS tokenization.
  $expires = $this->time
    ->getRequestTime() + 3600 * 24 - 5;
  $payment_method
    ->setExpiresTime($expires);
  $payment_method
    ->save();
}