0

I am creating a Payment Gateway and I use SetOrder to load into our api,

$orderIncrementId = $this->_checkoutSession->getLastRealOrder()->getIncrementId();
$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
$order = $this->_orderFactory->create()->loadByIncrementId($orderIncrementId);
api = $objectManager->create('Magento\MyModule\Model\Api\Transact')->setConfig($this->getConfig());
        $api->setOrderId()
            ->setCurrencyCode($order->getBaseCurrencyCode())
            ->setOrder($order)
            ->setConfig($this->_scopeConfig->getValue('payment/mymodule_gateway'))
            ->setReturnUrl($this->_urlBuilder->getUrl('mymodule/checkout/response'));

Because of this I am getting the previous order not the order that is currently in the cart.

I want the current order. How to get the current order?

Update:

<?php

namespace Magento\mymodulePG\Model;

use Magento\mymodulePG\Model\Api\Transact as TransactAPI;
use Magento\mymodulePG\Model\Api\Request as RequestAPI;
use Magento\mymodulePG\Model\Api\Update as UpdateAPI;
use Magento\mymodulePG\Model\Api\Check as CheckAPI;
use \Magento\mymodulePG\Helper\Checksum;

class Transact extends \Magento\Payment\Model\Method\AbstractMethod {

    const CODE = 'mymodule_gateway';

    /* protected $_canAuthorize            = true; */
    protected $_code                    = self::CODE;
    protected $_canCapture              = true;
    protected $_isInitializeNeeded      = true;
    protected $_canUseInternal          = false;
    protected $_canUseForMultishipping  = false;
    protected $_canVoid                 = true;
    protected $_canRefund               = true;


    protected $_scopeConfig;

    protected $_exception;

    protected $_checkoutSession;
    protected $_transactionRepository;
    protected $_orderFactory;

    protected $_transactionBuilder;
    protected $_payment;


    protected $_urlBuilder;
    protected $_order;


    protected $_storeManager;
    protected $_cacheFrontendPool;
    protected $_cacheTypeList;

    public function __construct(
      \Magento\Framework\UrlInterface $urlBuilder,
      \Magento\Framework\Exception\LocalizedExceptionFactory $exception,
      \Magento\Sales\Api\TransactionRepositoryInterface $transactionRepository,
      \Magento\Sales\Model\Order\Payment\Transaction\BuilderInterface $transactionBuilder,
      \Magento\Sales\Model\OrderFactory $orderFactory,
      \Magento\Store\Model\StoreManagerInterface $storeManager,
      \Magento\Framework\Model\Context $context,
      \Magento\Framework\Registry $registry,
      \Magento\Framework\Api\ExtensionAttributesFactory $extensionFactory,
      \Magento\Framework\Api\AttributeValueFactory $customAttributeFactory,
      \Magento\Payment\Helper\Data $paymentData,
      \Magento\Framework\App\Config\ScopeConfigInterface $scopeConfig,
      \Magento\Payment\Model\Method\Logger $logger, 
      \Magento\Checkout\Model\Session $checkoutSession,
      \Magento\Framework\App\Cache\TypeListInterface $cacheTypeList,
      \Magento\Framework\App\Cache\Frontend\Pool $cacheFrontendPool,
      \Magento\Framework\Model\ResourceModel\AbstractResource $resource = null,
      \Magento\Framework\Data\Collection\AbstractDb $resourceCollection = null,
      array $data = []
    ) {
      $this->_urlBuilder = $urlBuilder;
      $this->_exception = $exception;
      $this->_transactionRepository = $transactionRepository;
      $this->_transactionBuilder = $transactionBuilder;
      $this->_orderFactory = $orderFactory;
      $this->_storeManager = $storeManager;
      $this->_checkoutSession = $checkoutSession;
      $this->_scopeConfig = $scopeConfig;

      parent::__construct(
          $context,
          $registry,
          $extensionFactory,
          $customAttributeFactory,
          $paymentData,
          $scopeConfig,
          $logger,
          $resource,
          $resourceCollection,
          $data
      );
    }

    /**
     * Url to which the post form will be submitted
     * and the user will be redirected
     * @param String Url
     */


    public function getPostForm() {

        $fields = self::getCheckoutFormFields();
        $form = '<form id="mymodule_checkout" method="POST" action="' . self::getmymoduleTransactAction() . '">';
        foreach($fields as $key => $value) {
            if ($key == 'returnUrl') {
        $form .= '<input type="hidden" name="'.$key.'" value="'.\Magento\mymodulePG\Helper\Checksum::sanitizedURL($value).'" />'."\n";
      } else {
        $form .= '<input type="hidden" name="'.$key.'" value="'.\Magento\mymodulePG\Helper\Checksum::sanitizedParam($value).'" />'."\n";
      }
        }
        $form .= '</form>';
        $html = '<html><body>';
        //$html .= $this->__('You will be redirected to the mymodule website in a few seconds.');
        $html .= $form;
        $html.= '<script type="text/javascript">document.getElementById("mymodule_checkout").submit();</script>';
        $html.= '</body></html>';
        return $html;

    }
    public function getmymoduleTransactAction() 
    {
        return 'url';
    }



    /**
     * Url for calling the update api
     * @param String Url
     */
    public function getmymoduleUpdateApiUrl() 
    {
        return 'url';
    }

    /**
     * Instantiate state and set it to state object
     * @param string $paymentAction
     * @param \Magento\Framework\DataObject
     */
    public function initialize($paymentAction, $stateObject)
    {
        $state = Order::STATE_PENDING_PAYMENT;
        $stateObject->setState($state);
        $stateObject->setStatus('pending_payment');
        $stateObject->setIsNotified(false);
    }

    /**
     * Method to get the form fields with the relevant fields filled in
     * @return Array of form fields in the name=>value form 
     */
    public function getCheckoutFormFields()
    {   

        $orderIncrementId = $this->_checkoutSession->getLastRealOrder()->getIncrementId();
        $objectManager = \Magento\Framework\App\ObjectManager::getInstance();
        $order = $this->_orderFactory->create()->loadByIncrementId($orderIncrementId);
        // var_dump($orderIncrementId->getCurrentValue()); die();
        $this->_checkoutSession->setOrderId($orderIncrementId);
        $api = $objectManager->create('Magento\mymodulePG\Model\Api\Transact')->setConfig($this->getConfig());

        //$corder = $this->orderDetails(\Magento\Payment\Model\InfoInterface $payment);
        $api->setOrderId()
            ->setCurrencyCode($order->getBaseCurrencyCode())
            ->setOrder($order)
            ->setConfig($this->_scopeConfig->getValue('payment/mymodule_gateway'))
            ->setReturnUrl($this->_urlBuilder->getUrl('mymodulepg/checkout/response'));
        // export address
        var_dump($this->orderDetails(\Magento\Payment\Model\InfoInterface $payment)->getData()); die();
        $isOrderVirtual = $order->getIsVirtual();
        //var_dump( $this->_checkoutSession->getLastRealOrder()->getIncrementId()); die();
        $api->setBillingAddress($order->getBillingAddress());
        if ($isOrderVirtual) {
            $api->setNoShipping(true);
        } elseif ($order->getShippingAddress()) {
            $api->setShippingAddress($order->getShippingAddress());
        }
        // add cart totals and line items
        $result = $api->getRequestFields();


        $this->_checkoutSession->setmymoduleChecksum($api->getmymoduleChecksum());
        return $result;
    }  

    public function mymoduleSuccessOrderState() 
    {
        $order_status = $this->_scopeConfig->getValue('payment/mymodule_gateway/order_status');
        switch ($order_status) {
        case "processing":
            $state = \Magento\Sales\Model\Order::STATE_PROCESSING;
            break;
        case "complete":
            $state = \Magento\Sales\Model\Order::STATE_COMPLETE;
            break;
        case "closed":
            $state = \Magento\Sales\Model\Order::STATE_CLOSED;
            break;
        case "canceled":
            $state = \Magento\Sales\Model\Order::STATE_CANCELED;
            break;
        case "holded":
            $state = \Magento\Sales\Model\Order::STATE_HOLDED;
            break;
        case "pending":
    case "success":             $state = \Magento\Sales\Model\Order::STATE_COMPLETE;
    break;
        default:
            $state = \Magento\Sales\Model\Order::STATE_PENDING_PAYMENT;
        }
        return $state;
    }

    public function capture(\Magento\Payment\Model\InfoInterface $payment, $amount) 
    {
        $order = $payment->getOrder();
        $objectManager = \Magento\Framework\App\ObjectManager::getInstance();
        $api = $objectManager->create('Magento\mymodulePG\Model\Api\Update');
        $api->send($order->getIncrementId(), UpdateAPI::$STATUS_SETTLED, 'payment captured');        
        if ($api->getResponseCode() == 196) {
            // Mage::throwException('Online Capture failed. mymodule Update Api responded Response Code: '.$api->getResponseCode() . ' Message: ' . $api->getResponseDescription());
            // Mage::log('mymodule update api failure: orderId: '.$order->getIncrementId() . ', responseCode: ' . $api->getResponseCode(). ', responseDescription: ' . $api->getResponseDescription());
        }
    }

    public function cancel(\Magento\Payment\Model\InfoInterface $payment) 
    {
        $order = $payment->getOrder();
        $objectManager = \Magento\Framework\App\ObjectManager::getInstance();
        $api = $objectManager->create('Magento\mymodulePG\Model\Api\Update');
        $api->send($order->getIncrementId(), UpdateAPI::$STATUS_CANCELLED, 'order cancelled');
    //*****************************************************//
    $order_check = $payment->getOrder();
        $api_check = $objectManager->create('Magento\mymodulePG\Model\Api\Check');
        $api_check->check($order_check->getIncrementId());
    $response_code = $api_check->getResponseCode();
    if(!$response_code == 213 ) // transaction already cancelled by merchant
    {
       if( !in_array($api->getResponseCode(), array(243,230)))
    {
            // Mage::throwException('Request could not be completed since mymodule Update Api responded with update failure. Response Code: '.$api->getResponseCode());
            // Mage::log('mymodule update api failure: orderId: '.$order->getIncrementId() . ', responseCode: ' . $api->getResponseCode(). ', responseDescription: ' . $api->getResponseDescription());
        }}
    }

    public function void(\Magento\Payment\Model\InfoInterface $payment) {
        $order = $payment->getOrder();
        $objectManager = \Magento\Framework\App\ObjectManager::getInstance();
        $api = $objectManager->create('Magento\mymodulePG\Model\Api\Update');
        $api->send($order->getIncrementId(), UpdateAPI::$STATUS_CANCELLED, 'order void');        
        if (!in_array($api->getResponseCode(), array(226, 198, 213,243))) {
            // Mage::throwException('Request could not be completed since mymodule Update Api responded with update failure. Response Code: '.$api->getResponseCode());
            // Mage::log('mymodule update api failure: orderId: '.$order->getIncrementId() . ', responseCode: ' . $api->getResponseCode(). ', responseDescription: ' . $api->getResponseDescription());
        }
    }

    // refund cannot be consumed as there is no api to capture funds
    public function refund(\Magento\Payment\Model\InfoInterface $payment, $amount) 
    {
        // Mage::log('refund is getting called');
    }

    // call the check transaction api to show the current status
    public function checkStatus(\Magento\Payment\Model\InfoInterface $payment) 
    {
        $order = $payment->getOrder();
        $objectManager = \Magento\Framework\App\ObjectManager::getInstance();
        $api = $objectManager->create('Magento\mymodulePG\Model\Api\Check');
        $api->check($order->getIncrementId());
        $status = $api->getResponseDescription();
        return $status;
    }

    protected function orderDetails(\Magento\Payment\Model\InfoInterface $payment) 
    {
      $order = $payment->getOrder();
      return $order;
    }
}
1

Ideally in Payment.php you can get order details from Magento\Payment\Model\InfoInterface by getOrder() method

 public function getPostForm(\Magento\Payment\Model\InfoInterface    $payment) {

    $fields = self::getCheckoutFormFields($payment);
}


public function getCheckoutFormFields(\Magento\Payment\Model\InfoInterface    $payment)
{
     $order = $payment->getOrder(); 
} 

Please try with this , Also not required to add (\Magento\Payment\Model\InfoInterface) in constructor.

  • I am getting this syntax error, unexpected '$payment' (T_VARIABLE), expecting ',' or ')' – Chetandeep Singh Nov 8 '17 at 7:14
  • Please post full code include file location so i can get more idea. – Yogesh Nov 8 '17 at 7:18
  • edited the question to add the full code – Chetandeep Singh Nov 8 '17 at 7:25
  • hi now getting Uncaught TypeError: Argument 1 passed to Magento\mymodule\Model\Transact::getCheckoutFormFields() must be an instance of Magento\Payment\Model\InfoInterface, none given, – Chetandeep Singh Nov 8 '17 at 11:44
  • Updated answer, Please try again and let me know issue. – Yogesh Nov 8 '17 at 11:55

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.