Many payment gateways offer a vault feature that allows you to save your customers card details for future transactions.
When a customer opts to save their card information, it is securely stored for subsequent use.
However, if an order is canceled for any reason, the stored payment data might inadvertently be included when generating a credit memo, which could pose security concerns.
You can remove that vault information programmatically from the Magento 2 credit memo.
Here is the solution.
Solution: Remove Vault Information from Magento 2 Credit Memos
Start with creating an events.xml file at the Vendor/Extension/etc directory:
<?xml version="1.0"?> <config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:Event/etc/events.xsd"> <event name="sales_order_creditmemo_save_after"> <observer name="remove_vault_info_on_creditmemo" instance="Vendor\Extension\Observer\RemoveVaultInfo"/> </event> </config>
Now, create a RemoveVaultInfo.php file inside Vendor/Extension/Observer directory:
<?php namespace Vendor\Extension\Observer; use Magento\Framework\Event\Observer; use Magento\Framework\Event\ObserverInterface; use Magento\Vault\Api\PaymentTokenManagementInterface; use Magento\Vault\Api\PaymentTokenRepositoryInterface; use Magento\Sales\Model\Order\Creditmemo; class RemoveVaultInfo implements ObserverInterface { protected $paymentTokenManagement; protected $paymentTokenRepository; public function __construct( PaymentTokenManagementInterface $paymentTokenManagement, PaymentTokenRepositoryInterface $paymentTokenRepository ) { $this->paymentTokenManagement = $paymentTokenManagement; $this->paymentTokenRepository = $paymentTokenRepository; } public function execute(Observer $observer) { $creditmemo = $observer->getEvent()->getCreditmemo(); if ($creditmemo instanceof Creditmemo) { $order = $creditmemo->getOrder(); $payment = $order->getPayment(); $customerId = $order->getCustomerId(); $paymentMethod = $payment->getMethod(); // Retrieve the payment token $paymentToken = $this->paymentTokenManagement->getByGatewayToken( $payment->getAdditionalInformation('token'), $paymentMethod, $customerId ); if ($paymentToken) { // Delete the payment token $this->paymentTokenRepository->delete($paymentToken); } } } }
Using the simple code, you can remove any associated stored payment tokens or vault information from the credit memo.
That’s it!
Try this code yourself and remove the vault information using this solution.