• Time to read less than 1 minute

When working with sensitive user payment data in Magento 2, the core offers a safe approach for payment card data storage. Here is how to programmatically store payment card details from your application.

You just have to create a payment token from the card data. In order to perform this task, attach the core CreditCardTokenFactory class to your custom class:

<?php

use Magento\Vault\Model\CreditCardTokenFactory;
use Magento\Vault\Api\PaymentTokenRepositoryInterface;

/*
 * Class MyCustomClass
 */
class MyCustomClass
{
    /**
     * @var CreditCardTokenFactory
     */
    public $tokenFactory;

    /**
     * @var PaymentTokenRepositoryInterface
     */
    public $tokenRepository;

    /**
     * MyCustomClass constructor
     */
    public function __construct(
        CreditCardTokenFactory $tokenFactory,
        PaymentTokenRepositoryInterface $tokenRepository
    ) {
        $this->tokenFactory = $tokenFactory;
        $this->tokenRepository = $tokenRepository;
    }

    /**
     * Create a payment token
     */
    public function createPaymentToken() {
        // The payment gateway token
        $gatewayToken = 'card_112371K7-28BB-4O3X-CCG9-1034JHK27D88';

        // The customer ID, retrieved dynamically
        $customerId = 23;

        // The card data
        $cardData = [
            'type'              => 'Visa', 
            'maskedCC'          => '1111',
            'expirationDate'    => '06/2019'
        ];

        // Create the payment token
        $paymentToken = $this->tokenFactory->create();
        $paymentToken->setExpiresAt('Y-m-d 00:00:00');
        $paymentToken->setGatewayToken($gatewayToken);
        $paymentToken->setTokenDetails($cardData);
        $paymentToken->setIsActive(true);
        $paymentToken->setIsVisible(true);
        $paymentToken->setPaymentMethodCode('your_payment_method_code');
        $paymentToken->setCustomerId($customerId); 
        $paymentToken->setPublicHash($this->generatePublicHash($paymentToken));

        // Save the payment token
        $this->paymentTokenManagement->getByPublicHash(
            $paymentToken->getPublicHash(),
            $paymentToken->getCustomerId()
        );
    }
}

This is the standard, safe and recommended way to store payment card details in a Magento 2 application.