Magento 2 How To Programmatically Capture / Authorise PayPal Payment

In this blog, we will see how to capture / authorise PayPal payment and as a part of the requirement we have 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.

In the JDA integration with Magento 2, we were getting order status data back from JDA and capturing payment programmatically. We thought to share the following model class which we have created to capture PayPal payment with implementation:

<?php
 
/**
 * @var \Magento\Paypal\Model\Adminhtml\ExpressFactory
 */
protected $_authorisationFactory;
 
/**
* @var \Magento\Sales\Api\OrderRepositoryInterface
*/
protected $_orderRepository;
 
/**
* @param \Magento\Paypal\Model\Adminhtml\ExpressFactory $authorisationFactory
* @param \Magento\Sales\Api\OrderRepositoryInterface $orderRepository
*/
public function __construct(
        \Magento\Paypal\Model\Adminhtml\ExpressFactory $authorisationFactory,
        \Magento\Sales\Api\OrderRepositoryInterface $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 \Magento\Framework\Exception\LocalizedException(
            __($e->getMessage())
        );
    }
}

Note: In Magento 2, there are two main functions isOrderAuthorizationAllowed and authorizeOrder of \Magento\Paypal\Model\Adminhtml\Express class which helps to capture Paypal payment.

Leave a Reply