Magento – Get Saved Credit/Debit Card Details in Magento2

checkoutcredit-cardmagento2orderspayment-methods

How can I get already saved credit/debit card details to use in my custom module from checkout page before place order.

Best Answer

I was able to load a customer's saved card info from their customerId by using the following:

<?php
namespace Company\Mondule\Controller\Adminhtml\Order;

use Magento\Framework\App\Action\Action;
use Magento\Framework\App\Action\Context;
use Magento\Customer\Api\CustomerRepositoryInterface;
use Magento\Vault\Api\PaymentTokenManagementInterface;

class Connector extends Action
{
  protected $customerRepositoryFactory;
  protected $paymentTokenManagement;

  public function __construct(
    Context $context,
    PageFactory $pageFactory,
    CustomerRepositoryInterface $customerRepositoryInterface,
    PaymentTokenManagementInterface $paymentTokenManagement,
    array $data = []
  ) {
    $this->customerRepositoryInterface = $customerRepositoryInterface;
    $this->paymentTokenManagement = $paymentTokenManagement;
    parent::__construct($context, $data);
  }

  public function execute()
  {
    // CUSTOMER
    $customerId = '1';
    $customer = $this->customerRepositoryInterface->getById($customerId);

    // Get Saved CC
    $cardList = $this->paymentTokenManagement->getListByCustomerId($customerId);

    foreach($cardList as $card) {
      if ($card->getIsActive()) {
        echo $card->getData();
      }
    }
  }
}

I should note that this is just a snippet from our implementation. Without seeing any of your code, you may need to alter it some depending on your application.

Related Topic