【问题标题】:Magento 2 Get Order ID before sending to Payment Gateway in Controller?Magento 2 在发送到控制器中的支付网关之前获取订单 ID?
【发布时间】:2017-03-24 02:17:07
【问题描述】:

我想知道如何在重定向到控制器后获取当前下订单的订单 ID 我需要这个,因为在将浏览器发送到支付网关后,我需要知道要设置哪个订单 ID 来完成

谢谢

【问题讨论】:

    标签: controller magento2


    【解决方案1】:

    首先要做到这一点,你需要做很多工作。没有简单的方法。

    当您在自定义网关付款文件中时,您需要找到:

    app/code/Magento/sample_gateway/view/payment/method-renderer/sample_getway.js

    这个文件是你的 js 脚本,它控制在你的视图中执行的所有事务,甚至是你的 ajax。

    保留这个文件,我们以后会用到它。

    接下来,我们需要在 magento 上为新人创建一个控制器。如果您不知道如何创建控制器,这是创建 php 文件的最简单方法。我建议你访问这个链接 (http://inchoo.net/magento-2/how-to-create-a-basic-module-in-magento-2/) 这个链接是针对一个客户模块的,我真的建议你去做它并从这里控制你所有的外部逻辑。

    你的控制器应该是这样的

        <?php
    namespace your_module\CallBacks\Controller\Payu;
    
    
    use Magento\Sales\Model\Order;
    
    class Success extends \Magento\Framework\App\Action\Action
    {
        protected $_pageFactory;
        protected $_resultJsonFactory;
        protected $_checkoutSession;
        protected $orderRepository;
        protected $customerSession;
    
        public function __construct(
            \Magento\Framework\App\Action\Context $context,
            \Magento\Framework\Controller\Result\JsonFactory $resultJsonFactory,
            \Magento\Framework\View\Result\PageFactory $pageFactory,
            \Magento\Checkout\Model\Session $checkoutSession,
            \Magento\Sales\Api\OrderRepositoryInterface $orderRepository,
            \Magento\Customer\Model\Session $customerSession
        )
        {
            $this->_checkoutSession = $checkoutSession;
            $this->_resultJsonFactory = $resultJsonFactory;
            $this->_pageFactory = $pageFactory;
            $this->orderRepository = $orderRepository;
            $this->customerSession = $customerSession;
            return parent::__construct($context);
        }
    
        public function execute()
        {
    
    
    
            $customerId = $this->customerSession->getCustomer()->getId();
    
            $result = $this->_resultJsonFactory->create();
    
            $order = $this->_checkoutSession->getLastRealOrder();
            //$orderId=$order->getEntityId();
            $order->getIncrementId();
    
            $this->_resources = \Magento\Framework\App\ObjectManager::getInstance()->get('Magento\Framework\App\ResourceConnection');
            $connection= $this->_resources->getConnection();
            $themeTable = $this->_resources->getTableName('z_payu_tx');
            $sql = "INSERT INTO ". $themeTable . 
                    " (orderid, date, state_pol,customer_number) 
                    VALUES 
                    ('".$order->getIncrementId()."', '".date("Y-m-d H:i:s")."','NEW','".$customerId."')";
    
            try{
    
                $connection->query($sql);
    
                $resultData = [
                    'orderId' => $order->getIncrementId(),
                    'msg_status' => true,
                ];
    
            }catch(\Exception $e){
    
                $resultData = [
                    'orderId' => $order->getIncrementId(),
                    'msg_status' => false,
                ];
            }
    
    
            return $result->setData($resultData);
    
    
        }
    
    }
    

    此时,这个控制器可以只获取当前订单的客户id,就可以获取订单号了。如果你的控制器名为 getOrderNumber.php,你可以试试这个(你的站点/CallBacks/Controller/Payu/getOrderNumber)。

    这样你可以在magento 2逻辑中尝试所有代码,它真的很有用。

    这可以通过观察者来完成,但要真正使用,你不能像你自己的 php.ini 那样简单地调试。请记住,如果您想要开发者模组,您需要在命令行中运行 php bin/magento deploy:mode:set developer。

    现在你有了控制器,你需要你的 js 文件在流程的某个点进行 ajax 调用。

    我们之前找到的sample_getway.js,我们要明白这是对magento主文件的覆盖,用于处理订单。现在我们可以使用和覆盖 magento2 的任何函数了。

    {
    
        ....
    
    },
    setOrder: function() {
    
                // this.getOrderId();
                this.placeOrder();
    
    
    
            },
            afterPlaceOrder: function (data, event) {
              if (event) {
                event.preventDefault();
              }
    
    
              this.getOrderId();
    
            },
            getOrderId: function () {
    
    
                  var _url = urlBuilder.build("callbacks/Payu/Success");
                  var merchantId = "508029";
                  var ApiKey = "4Vj8eK4rloUd272L48hsrarnUA";
                  var refCode = "";
                  var amount = this.getTotalAmount();
                  var currency = this.getCurrency();
                  var signatureKey = "";
    
                  var param = 'ajax=1';
                  jQuery.ajax({
                      showLoader: true,
                      url: _url,
                      data: param,
                      type: "POST",
                      dataType: 'json'
                  }).done(function (data) {
                      if(data.msg_status){
                        refCode = data.orderId;
    
                        var unCode = ApiKey+"~"+merchantId+"~"+refCode+"~"+amount+"~"+currency;
                        signatureKey= hex_md5(ApiKey+"~"+merchantId+"~"+refCode+"~"+amount+"~"+currency);
                        document.getElementById("refCodeInput").value = refCode
                        document.getElementById("signatureValue").value = signatureKey;
    
                        document.getElementById("payuForm").submit();
                        return;
                      }else{
    
                        alert("Se ha presentado un error, porfavor intentelo más tarde")
    
                      }
                  }).fail(function (XMLHttpRequest, textStatus, errorThrown) {
                    console.log(textStatus);
    
                    alert(textStatus);
                    alert(JSON.stringify(errorThrown));
                    alert(textStatus);
    
                  });
    
            },
            getResponseUrl: function(){
    
              return urlBuilder.build("checkout/onepage/success");
    
            },
            getconfirmPageUrl: function(){
    
              return urlBuilder.build("callbacks/Payu/confirmPage");
    
            },
    
    
        ....
    
    },
    

    如果你看的话,我们有一些额外的函数和一些覆盖函数,setOrder、afterPlaceOrder、this.placeOrder()。

    setOrder-> 这是与我在 html 中的按钮相关联的函数

    app/code/Magento/sample_gateway/view/frontend/web/template/payment/form.html

    <input type="image" border="0" alt="" src="http://www.payulatam.com/img-secure-2015/boton_pagar_mediano.png" data-bind="click: setOrder"/>
    

    这只是一个点击动作,它是 js 功能。

    this.placeOrder()-> 这是这部分的魔力,这是你让 magento2 创建订单的方式(框架实用程序),现在你需要知道这个过程什么时候结束才能做其他事情,在我的例子中我需要填写一个带有某些值的表格,所以我需要停止自动重定向以保留信息并重定向到支付公司,为此我们有一个很棒的功能

    afterPlaceOrder -> 让您在下订单后执行任何操作,此时您可以做任何您想做的事情,重定向到家,到支付公司等。

    这很棘手redirectAfterPlaceOrder: false, 是让您自动重定向或不自动重定向的变量,在我的情况下,我需要不同的 url,所以我在 getOrderId 中重定向,由 afterPlaceOrder 调用。

    如果你想试试这个,你需要在成功调用后停用一个清洁汽车的功能,只需注释 $session->clearQuote(),你就可以在创建订单后调用控制器进行测试。

        namespace Magento\Checkout\Controller\Onepage;
    
    class Success extends \Magento\Checkout\Controller\Onepage
    {
        /**
         * Order success action
         *
         * @return \Magento\Framework\Controller\ResultInterface
         */
        public function execute()
        {
            $session = $this->getOnepage()->getCheckout();
            if (!$this->_objectManager->get(\Magento\Checkout\Model\Session\SuccessValidator::class)->isValid()) {
                return $this->resultRedirectFactory->create()->setPath('checkout/cart');
            }
            //$session->clearQuote(); //This stop clear the cart.
            //@todo: Refactor it to match CQRS
            $resultPage = $this->resultPageFactory->create();
            $this->_eventManager->dispatch(
                'checkout_onepage_controller_success_action',
                ['order_ids' => [$session->getLastOrderId()]]
            );
            return $resultPage;
        }
    }
    

    希望对您有所帮助!有点晚了,因为很难理解 magento2。

    【讨论】:

    • 请不要执行原始 SQL 语句,也不要在控制器内部使用业务逻辑。而是将其委托给像 PaymentProcessor 这样的特定类,在这里使用 OrderRepositoryInterface 通过 id 获取 Order。
    猜你喜欢
    • 2017-08-16
    • 1970-01-01
    • 2017-01-04
    • 2020-05-15
    • 2013-01-21
    • 1970-01-01
    • 2017-10-10
    • 2016-03-23
    • 1970-01-01
    相关资源
    最近更新 更多