How to get transaction id of order in Magento 2?
3 Answers
Edit:
Try to inject Magento\Sales\Api\Data\TransactionSearchResultInterfaceFactory
into your constructor:
protected $transactions;
public function __constructor(
\Magento\Sales\Api\Data\TransactionSearchResultInterfaceFactory $transactions,
......
)
{
$this->transactions = $transactions;
}
In your method:
$transactions = $this->transactions->create()->addOrderIdFilter($orderId);
$transactions->getItems();
If Magento\Sales\Api\Data\TransactionSearchResultInterfaceFactory
doesn't work, try to use \Magento\Sales\Model\ResourceModel\Order\Payment\Transaction\CollectionFactory
. I'm not test yet both of them.
This will work.
class MyClass
{
/**
* @var \Magento\Sales\Api\TransactionRepositoryInterface
*/
private $repository;
/**
* @var \Magento\Framework\Api\SearchCriteriaBuilder
*/
private $searchCriteriaBuilder;
/**
* MyClass constructor.
*
* @param \Magento\Sales\Api\TransactionRepositoryInterface $repository
* @param \Magento\Framework\Api\SearchCriteriaBuilder $searchCriteriaBuilder
*/
public function __construct(
\Magento\Sales\Api\TransactionRepositoryInterface $repository,
\Magento\Framework\Api\SearchCriteriaBuilder $searchCriteriaBuilder
) {
$this->repository = $repository;
$this->searchCriteriaBuilder = $searchCriteriaBuilder;
}
/**
* @param int $id
*
* @return \Magento\Sales\Api\Data\TransactionInterface[]
*/
public function getTransactionByOrderId($id)
{
$this->searchCriteriaBuilder->addFilter('order_id', $id);
$list = $this->repository->getList(
$this->searchCriteriaBuilder->create()
);
return $list->getItems();
}
}
You can use \Magento\Sales\Api\Data\TransactionSearchResultInterface for transaction Id.
$transaction = $objectManager->create('\Magento\Sales\Api\Data\TransactionSearchResultInterfaceFactory')->create()->addOrderIdFilter($block->getOrderId())->getFirstItem();
$transactionId = $transaction->getData('txn_id');
The $transactionId is your required transaction Id.
$transactionFactory = $objectManager->get('\Magento\Sales\Model\ResourceModel\Order\Payment\Transaction\CollectionFactory'); $transactions = $transactionFactory->create()->addOrderIdFilter($_order->getId()); print_r($transactions->getItems());
but this is not working