Magento 2 Get Vault Payment Token from Order

If Magento 2 website has a feature to save credit cards for future use, then in reality, full credit card data is never saved to Magento database, but each payment gateway generates one token for the credit card and Magento saves that payment token.

Sometimes merchant wants to fetch that saved payment token with an order and pass that payment token to some ERP or somewhere else then you can get that payment token using order data.

How to get saved payment tokens of order in Magento 2

First, you have to load the order and then using the order object you can get the vault token using the below script.

$orderExtensionAttributes = $_order->getPayment()->getExtensionAttributes();
$vaultPaymentToken = $orderExtensionAttributes->getVaultPaymentToken()->getGatewayToken();

Note: This code will only work if the payment token is saved to Magento Vault.