Magento 2 : How to programmatically capture / authorise PayPal payment?

authorise paypal payments

Our team has been busy doing integration with JDA (formerly RedPrairie) from last few months. You might know it is quite popular warehouse management system (WMS) which allows you to sync catalog and transaction data between both Magento 2 and JDA systems.

As part of the requirement we had to implement solution which could handle payment on dispatch. In Magento 2, we were using PayPal payment action as Order which allows to authorise payment but the money can be taken within 29 days from date of authorisation.

As part of the JDA integration, we were fetching order status data back from JDA and capturing payment in Magento 2 programatically. We were trying to find how to do this but couldn’t find anything online so we thought it would be good to share this with our community members.

Let’s crack on with the implementation, here is the Model class which we created to capture PayPal payment -:

<?php /** * @var MagentoPaypalModelAdminhtmlExpressFactory */
protected $_authorisationFactory; /**
* @var MagentoSalesApiOrderRepositoryInterface
*/
protected $_orderRepository; /**
* @param MagentoPaypalModelAdminhtmlExpressFactory $authorisationFactory
* @param MagentoSalesApiOrderRepositoryInterface $orderRepository
*/
public function __construct( MagentoPaypalModelAdminhtmlExpressFactory $authorisationFactory, MagentoSalesApiOrderRepositoryInterface $orderRepository ) { $this->_authorisationFactory = $authorisationFactory; $this->_orderRepository = $orderRepository;
} /** * @param int $orderId * @return $this */
public function createPayPalAuthorisation($orderId)
{ try { $order = $this->_orderRepository->get($orderId); if ($order){ $paymentMethod = $order->getPayment()->getMethod(); if ($paymentMethod=='paypal_express'){ $additionalInfo = $order->getPayment()->getAdditionalInformation(); if (isset($additionalInfo['paypal_payment_status'])){ $paymentStatus = $additionalInfo['paypal_payment_status']; if ($paymentStatus=='pending'){ $authorisation = $this->_authorisationFactory->create(); if ($authorisation->isOrderAuthorizationAllowed($order->getPayment())){ $authorisation->authorizeOrder($order); } } } } } } catch (Exception $e) { throw new MagentoFrameworkExceptionLocalizedException( __($e->getMessage()) ); }
}

There are two main functions isOrderAuthorizationAllowed and authorizeOrder of MagentoPaypalModelAdminhtmlExpress class which helps to capture Paypal payment in Magento 2.

That’s it, Hope this article helped you in some way. Please leave us your comment and let us know what do you think? Thanks.

Discover more from WHO WILL CARE eCommerce

Subscribe now to keep reading and get access to the full archive.

Continue reading