0

I have created an observer to capture the order after placing it for event checkout_onepage_controller_success_action as follows:

<?php
namespace Magento\SamplePaymentGateway\Observer;

use Magento\Framework\Event\Observer;
use Magento\Framework\Event\ObserverInterface;
use Magento\Store\Model\StoreManagerInterface;

class ProcessGatewayRedirect implements ObserverInterface
{
    private $storeManager;
    protected $_checkoutSession;

    public function __construct(
        StoreManagerInterface $storeManager,
        \Magento\Checkout\Model\Session $checkoutSession   
    ) {
        $this->storeManager = $storeManager;
        $this->_checkoutSession = $checkoutSession;
    }

    public function execute(\Magento\Framework\Event\Observer $observer)
    { 
        $orderId = $observer->getEvent()->getOrderIds();
        $base_url = $this->storeManager->getStore()->getBaseUrl();
        $objectManager = \Magento\Framework\App\ObjectManager::getInstance();
        $order = $objectManager->create('\Magento\Sales\Model\Order') ->load($orderId[0]);
        $payment = $order->getPayment();


        $method = $payment->getMethodInstance();
        $methodTitle = $method->getTitle();

        $order_data= $order->getData();
        $status = $this->_checkoutSession->getLastOrderStatus();

        $increment_id = $order_data['increment_id'];
        $redirect = $objectManager->get('\Magento\Framework\App\Response\Http');
        $redirect->setRedirect($base_url.'custompayment/index/redirect/id/'.$increment_id.'');
        echo 'oid' ;var_dump($orderId);
        var_dump($base_url);
        echo 'method' ;var_dump($method);
        echo 'mettitle' ;var_dump($methodTitle);
        echo 'status' ;var_dump($status);
        return;

    }
}

I'm getting all the real data except order id. For example, orderId dumped by this code is 31 whereas the order id as seen in backend is 45. I ran the test for second time and orderId dumped is 32 and in the backend it is 46. What is happening here? How to get the actual order id?

  • Two time order is created right? – Jeeva Chezhiyan Dec 6 '17 at 6:02
  • No problem is not two order created at once. – Purushotam Sangroula Dec 6 '17 at 6:11
  • You dumped order id , but the new order id is created in backend right? – Jeeva Chezhiyan Dec 6 '17 at 6:19
  • Yes, I dumped order id, but the id shown at backend is greater than the order id displayed by this code. – Purushotam Sangroula Dec 6 '17 at 6:29
  • For this two times that observer will call so order will create two times. So you need to load the old quote in below you see that response.php file i loaded old quote and changed the status to processing. After that in observer i checked whether the status is processing means it will redirect to success page. Pending means it will create order i handled in observer check that – Jeeva Chezhiyan Dec 6 '17 at 6:33
1

This is Response controller after the payment success it will come to this controller load the success page.

<?php
/**
 * Copyright © 2015 Pay.nl All rights reserved.
 */

namespace Jed\Custompayment\Controller\Index;

use Magento\Payment\Helper\Data as PaymentHelper;
use Magento\Quote\Model\QuoteRepository;
use Magento\Sales\Model\OrderRepository;
use Paynl\Error\Error;

/**
 * Description of Redirect
 *
 * @author Andy Pieters <andy@pay.nl>
 */
class Response extends \Magento\Framework\App\Action\Action
{
    /**
     * @var \Paynl\Payment\Model\Config
     */
    private $config;

    /**
     * @var \Magento\Checkout\Model\Session
     */
    private $checkoutSession;

    /**
     * @var \Psr\Log\LoggerInterface
     */
    private $_logger;

    /**
     * @var PaymentHelper
     */
    private $paymentHelper;

    /**
     * @var QuoteRepository
     */
    private $quoteRepository;


    /**
     * @var OrderRepository
     */
    private $orderRepository;

    /**
     * @param \Magento\Framework\App\Action\Context $context
     * @param \Paynl\Payment\Model\Config $config
     * @param \Magento\Framework\Message\ManagerInterface $messageManager
     */
    public function __construct(
        \Magento\Framework\App\Action\Context $context,

        \Magento\Checkout\Model\Session $checkoutSession,
        \Psr\Log\LoggerInterface $logger,
        PaymentHelper $paymentHelper,
        QuoteRepository $quoteRepository,
        OrderRepository $orderRepository,\Magento\Quote\Model\QuoteManagement $quoteManagement,\Magento\Quote\Model\QuoteFactory $quoteFactory
    )
    {
        //$this->config          = $config; // Pay.nl config helper
        $this->checkoutSession = $checkoutSession;
        $this->_logger         = $logger;
        $this->paymentHelper   = $paymentHelper;
        $this->quoteRepository = $quoteRepository;
        $this->orderRepository = $orderRepository;
        $this->quoteManagement = $quoteManagement;
        $this->quoteFactory = $quoteFactory;

        parent::__construct($context);
    }

    public function execute()
    {
        try {

            if ($_SERVER["REQUEST_METHOD"]=="POST") {               
                $response_code = $_POST['response_code']; 

                if($response_code == 1)
                {
                    $order = $this->_getCheckoutSession()->getLastRealOrder();
                    $this->checkoutSession
                        ->setLastQuoteId($order->getQuoteId())
                        ->setLastSuccessQuoteId($order->getQuoteId())
                        ->clearHelperData();
                    if ($order) {
                        $this->checkoutSession->setLastOrderId($order->getId())
                                       ->setLastRealOrderId($order->getIncrementId())
                                       ->setLastOrderStatus('processing');
                    }            
                return $this->_redirect('checkout/onepage/success');

                }
                else{
                        $e = 'Payment Declined';
                        $this->messageManager->addExceptionMessage($e, __('Something went wrong, please try again later'));
                        $this->_getCheckoutSession()->restoreQuote();
                        $this->_redirect('checkout/cart');

                }

            }

            /*$order = $this->_getCheckoutSession()->getLastRealOrder();
            $this->checkoutSession
                    ->setLastQuoteId($order->getQuoteId())
                    ->setLastSuccessQuoteId($order->getQuoteId())
                    ->clearHelperData();
                if ($order) {
                    $this->checkoutSession->setLastOrderId($order->getId())
                                       ->setLastRealOrderId($order->getIncrementId())
                                       ->setLastOrderStatus('processing');
                }            
                return $this->_redirect('checkout/onepage/success');*/
        } catch (\Exception $e) {
            $this->messageManager->addExceptionMessage($e, __('Something went wrong, please try again later'));
            $this->messageManager->addExceptionMessage($e, $e->getMessage());
            $this->_logger->critical($e);
            $this->_getCheckoutSession()->restoreQuote();
            $this->_redirect('checkout/cart');
        }
    }

    /**
     * Return checkout session object
     *
     * @return \Magento\Checkout\Model\Session
     */
    protected function _getCheckoutSession()
    {
        return $this->checkoutSession;
    }
}

checkout_onepage_controller_success_action observer,

<?php
namespace Jed\Custompayment\Observer;
use Magento\Sales\Model\Order;

class Custompayment implements \Magento\Framework\Event\ObserverInterface
{

    public function __construct(
        \Magento\Framework\Registry $registry, \Magento\Framework\App\Action\Context $context,\Magento\Store\Model\StoreManagerInterface $storeManager, \Magento\Checkout\Model\Session $checkoutSession)
    {

        $this->_storeManager = $storeManager;
        $this->checkoutSession = $checkoutSession;
        $this->registry = $registry;
    }

    public function execute(\Magento\Framework\Event\Observer $observer)
    { 
        $orderId = $observer->getEvent()->getOrderIds();
        $base_url = $this->_storeManager->getStore()->getBaseUrl();
        $objectManager = \Magento\Framework\App\ObjectManager::getInstance();
        $order = $objectManager->create('\Magento\Sales\Model\Order') ->load($orderId[0]);
        $payment = $order->getPayment();


        $method = $payment->getMethodInstance();
        $methodTitle = $method->getTitle();

        $order_data= $order->getData();
        $status = $this->checkoutSession->getLastOrderStatus();

        if($status == 'processing' && $methodTitle == 'Custompayment'){
            $orderState = \Magento\Sales\Model\Order::STATE_PROCESSING;
            $order->setState($orderState)->setStatus(\Magento\Sales\Model\Order::STATE_PROCESSING);
            $order->save();
            return true;
        }
        else if($status == 'pending' && $methodTitle == 'Custompayment'){
          $increment_id = $order_data['increment_id'];
          $redirect = $objectManager->get('\Magento\Framework\App\Response\Http');
          $redirect->setRedirect($base_url.'custompayment/index/redirect/id/'.$increment_id.'');
          return;
        }
        else{
          return true;
        } 
    }
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.