Commit 04e35b26 authored by Vadym Abramchuk's avatar Vadym Abramchuk
Browse files

Issue #3270758 by abramm: Fix possible issue with adding new card to the customer account

parent ec8fa305
Loading
Loading
Loading
Loading
+34 −4
Original line number Diff line number Diff line
@@ -458,6 +458,10 @@ class Omise extends OnsitePaymentGatewayBase implements OmiseInterface {
    if ($customer_id) {
      // If the customer id already exists
      // use the Omise form token to create the new card.
      // Retrieve card ID by token. It will be later used to identify the newly
      // created card in the customer's cards list.
      $cardByToken = $this->retrieveCardIdByToken($payment_details['omise_token']);

      $customer = \OmiseCustomer::retrieve(
        $customer_id,
        $this->configuration['public_key'],
@@ -466,8 +470,6 @@ class Omise extends OnsitePaymentGatewayBase implements OmiseInterface {
      // Create a payment method for an existing customer.
      $customer->update(['card' => $payment_details['omise_token']]);

      // Unfortunately, there's no way to fetch the card we've just created so
      // the best we can do here is to extract the newest one.
      // Retrieve the list of cards, starting with the newest first.
      $cards = \OmiseCustomer::retrieve(
        $customer['id'],
@@ -476,9 +478,15 @@ class Omise extends OnsitePaymentGatewayBase implements OmiseInterface {
      )
        ->cards(['order' => 'reverse_chronological']);

      foreach ($cards['data'] as $card) {
        return $card;
      // Verify card was successfully added to the customer's account.
      $newlyCreatedCards = array_filter($cards['data'], function ($card) use ($cardByToken) {
        return $card['id'] === $cardByToken;
      });
      if (count($newlyCreatedCards) !== 1) {
        throw new \RuntimeException('Could not retrieve newly created Omise card.');
      }

      return reset($newlyCreatedCards);
    }
    elseif ($owner && $owner->isAuthenticated()) {
      // Create both the customer and the payment method.
@@ -575,4 +583,26 @@ class Omise extends OnsitePaymentGatewayBase implements OmiseInterface {
    throw new \LogicException('Omise payment gateway does not support Notify method');
  }

  /**
   * Retrieves card ID by token.
   *
   * @param string $token
   *   The token string.
   *
   * @return string
   *   The card ID.
   */
  protected function retrieveCardIdByToken($token) {
    $cardByToken = \OmiseToken::retrieve(
      $token,
      $this->configuration['public_key'],
      $this->configuration['secret_key']
    );
    if (empty($cardByToken['card']['id'])) {
      throw new \RuntimeException('Could not retrieve card ID using token.');
    }

    return $cardByToken['card']['id'];
  }

}