Magento 2 - Programatically Add Credit Card into Vault (BrainTree)

Viewed 1851

I need to Add Credit Card details in to Vault Programmatically (BrainTree) in Magento 2.1.5

Basically what i want is After LoginIn there will be a separate section for Saved Cards . In that Customer is used to Add/edit/delete All his Credit card details.

the Below Code is used to list all the Credit Card saved by the Customer

 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);

Now what i want is how to Add the Card Details to the Vault ?

Below is the Code to Add card in core php

 $result = Braintree_Customer::create(array(
            'firstName' => 'first name',
            'lastName' => 'last name',
            'company' => 'company',
            'email' => 'xxxx@gmail.com',
            'phone' => '1234567890',
            'creditCard' => array(
                'cardholderName' => 'xxx xxx',
                'number' => '4000 0000 0000 0002 ',
                'expirationMonth' => '10',
                'expirationYear' => 2020,
                'cvv' => '123',
                'billingAddress' => array(
                    'firstName' => 'My First name',
                    'lastName' => 'My Last name'
                )
            )
        ));

But how can i do this same process in magento 2.

Thanks for the help

2 Answers

First, you have to create a payment token from the card data:

use Magento\Vault\Model\CreditCardTokenFactory;
...

$paymentToken = $this->creditCardTokenFactory->create();
$paymentToken->setExpiresAt('Y-m-d 00:00:00');
$paymentToken->setGatewayToken('card_112371K7-28BB-4O3X-CCG9-1034JHK27D88');
$paymentToken->setTokenDetails([
  'type'              => 'Visa',
  'maskedCC'          => '1111',
  'expirationDate'    => '06/2019'
]);
$paymentToken->setIsActive(true);
$paymentToken->setIsVisible(true);
$paymentToken->setPaymentMethodCode('your_payment_method_code');
$paymentToken->setCustomerId($customerId);
$paymentToken->setPublicHash($this->generatePublicHash($paymentToken));

Then you can save the payment token:

use Magento\Vault\Api\PaymentTokenRepositoryInterface;
...

$this->paymentTokenRepository->save($paymentToken);

This is just an example you can start with. In a real world situation, you would also want to check that the token doesn't already exist, an also try a payment authorisation on the card to make sure it's actually usable and valid.

In order to check if a payment token exists or not, you can use this:

use Magento\Vault\Api\PaymentTokenManagementInterface;
...
$this->paymentTokenManagement->getByPublicHash( $paymentToken->getPublicHash(), $paymentToken->getCustomerId() );

You can have a look at the core Magento 2 classes mentioned here to know more about the functions available for payment token handling. Good luck!

Replace objectManager when use in projects

<?php

use Magento\Framework\Encryption\EncryptorInterface;
use Magento\TestFramework\Helper\Bootstrap;
use Magento\Vault\Model\AccountPaymentTokenFactory;
use Magento\Vault\Model\PaymentToken;
use Magento\Vault\Model\PaymentTokenRepository;

/** @var EncryptorInterface $encryptor */
$encryptor = $objectManager->get(EncryptorInterface::class);

/** @var PaymentToken $paymentToken */
$paymentToken = $objectManager->create(PaymentToken::class);
$paymentToken
    ->setCustomerId($customer->getId())
    ->setPaymentMethodCode('payflowpro')
    ->setType(AccountPaymentTokenFactory::TOKEN_TYPE_ACCOUNT)
    ->setGatewayToken('mx29vk')
    ->setPublicHash($encryptor->hash($customer->getId()))
    ->setTokenDetails(json_encode(['payerEmail' => 'john.doe@example.com']))
    ->setIsActive(true)
    ->setIsVisible(true)
    ->setExpiresAt(date('Y-m-d H:i:s', strtotime('+1 year')));

/** @var PaymentTokenRepository $tokenRepository */
$tokenRepository = $objectManager->create(PaymentTokenRepository::class);
$tokenRepository->save($paymentToken);
Related