How to Programmatically Trigger Credit Card Payment in Magento 2

magento2paymentquote

I need to build an api method which should receive customer's payment information (credit card info) along with product details and place an order with it further processing.

Right now I faced that braintree payment facade requires credit card tokenization which is made via javascript during checkout process, as well as authorize.net method is connecting to transact.dll endpoint.

Is this actually possible, to trigger order processing only in backend ?

Can I refer somewhere in existing magento2 code to see how it is made, maybe in some adminhtml area ?

The code i use to create an order:

    // prepare adresses, products in quote, shipping method - skipped
    $quote->setPaymentMethod('authorizenet_directpost');
    $quote->setInventoryProcessed(false);
    // Set Sales Order Payment

    $quote->getPayment()->importData(
        [
            'method'      => 'authorizenet_directpost',
            'card_type'   => $payment->cardType,
            'cvv'         => $payment->cvv,
            'expire_year' => $payment->expireYear
        ]
    );

    $customer = $this->customerRepository->get($contact->email);
   // prepare customer
    $quote->setCustomer($customer);

    // Collect Totals & Save Quote
    $quote->collectTotals()->save();
    $order = $this->quoteManagement->submit($quote);

Best Answer

You first need to find the customer saved cards list (vault), then you can use one of the cards in the order placement as you described:

use Magento\Vault\Api\PaymentTokenManagementInterface;
use Magento\Customer\Model\Session;

... 

// Get the customer id (currently logged in user)
$customerId = $this->session->getCustomer()->getId();

// Card list
$cardList = $this->paymentTokenManagement->getListByCustomerId($customerId);

You can use the following methods to get the details of a card. Example on the first card object of the list above:

$cardList[0]->getEntityId();
$cardList[0]->getCustomerId();
$cardList[0]->getPublicHash();
$cardList[0]->getPaymentMethodCode();
$cardList[0]->getType();
$cardList[0]->getCreatedAt();
$cardList[0]->getExpiresAt();
$cardList[0]->getGatewayToken();
$cardList[0]->getDetails();
$cardList[0]->getisActive();
$cardList[0]->getIsVisible();

Note: The getListByCustomerId($customerId) function will give you all stored cards for a single customer, whether the cards are active or not. If you only want the list of active cards, use getVisibleAvailableTokens($customerId) instead.

Related Topic