如何在Magento 2下订单

时间:2019-07-03 14:50:56

标签: magento

我创建了一种自定义付款方式, 但是,我似乎无法弄清楚下订单代码。

我在html文件中注意到data-bind = Click:placeorder。 当我添加我在网上找到的代码时,订单不会被放置, 我没有重定向到成功页面。

如果有人可以指导我走哪条路线很棒,这对magento 2来说是新手。

我是在我的Model类中还是在模块的javascript文件中执行的? 我使用的代码来自链接-https://magento.stackexchange.com/questions/171786/how-to-programmatically-place-order-with-custom-options-in-magento-2

公共函数placeOrder($ data)     {

    $customer = $this->_registry->registry('auth_customer');
    if (!$customer) {
        throw new Exception($this->__('User not authorized'));
    }

    $data = json_decode(json_encode($data), True);

    // $items = $this->getCartItems();
    $items = $data['products'];

    $customerAddressModel = $this->_objectManager->create('Magento\Customer\Model\Address');
    $shippingID =  $customer->getDefaultShipping();
    $address = $customerAddressModel->load($shippingID);

    $orderData = [
        'currency_id' => 'USD',
        'email' => $customer->getData('email'), //buyer email id
        'shipping_address' => [
            'firstname' => $customer->getData('firstname'),
            'lastname' => $customer->getData('lastname'),
            'street' => $address->getData('street'),
            'city' => $address->getData('city'),
            'country_id' => $address->getData('country_id'),
            'region' => $address->getData('region'),
            'postcode' => $address->getData('postcode'),
            'telephone' => $address->getData('telephone'),
            'fax' => $address->getData('fax'),
            'save_in_address_book' => 1
        ],
        'items' => $items
    ];

    return $this->createOrder($orderData, $data);
}
public function createOrder($orderData, $data)
{
    $response=array();
    $response['success']=FALSE;

    if(!count($orderData['items'])) {
        $response['error_msg'] = 'Cart is Empty';
    } else {
        $this->cartManagementInterface = $this->_objectManager->get('\Magento\Quote\Api\CartManagementInterface');

        //init the store id and website id
        $store = $this->_storeManager->getStore($data['store_id']);
        $websiteId = $this->_storeManager->getStore()->getWebsiteId();

        //init the customer
        $customer = $this->_customerFactory->create();
        $customer->setWebsiteId($websiteId);
        $customer->loadByEmail($orderData['email']);// load customer by email address

        //check the customer
        if (!$customer->getEntityId()) {

            //If not available then create this customer
            $customer->setWebsiteId($websiteId)
                ->setStore($store)
                ->setFirstname($orderData['shipping_address']['firstname'])
                ->setLastname($orderData['shipping_address']['lastname'])
                ->setEmail($orderData['email'])
                ->setPassword($orderData['email']);

            $customer->save();
        }

        //init the quote
        $cart_id = $this->cartManagementInterface->createEmptyCart();
        $cart = $this->_cartRepositoryInterface->get($cart_id);

        $cart->setStore($store);

        // if you have already buyer id then you can load customer directly
        $customer = $this->_customerRepository->getById($customer->getEntityId());
        $cart->setCurrency();
        $cart->assignCustomer($customer); //Assign quote to customer

        $_productModel = $this->_productFactory->create();
        //add items in quote
        foreach ($orderData['items'] as $item) {
            $product = $_productModel->load($item['product_id']);

            try {
                // print_r($item); die();
                $params = array('product' => $item['product_id'], 'qty' => $item['qty']);
                if (array_key_exists('options', $item) && $item['options']) {
                    $params['options'] = json_decode(json_encode($item['options']), True);
                }
                if ($product->getTypeId() == 'configurable') {
                    $params['super_attribute'] = $item['super_attribute'];
                } elseif ($product->getTypeId() == 'bundle') {
                    $params['bundle_option'] = $item['bundle_option'];
                    $params['bundle_option_qty'] = $item['bundle_option_qty'];
                } elseif ($product->getTypeId() == 'grouped') {
                    $params['super_group'] = $item['super_group'];
                }

                $objParam = new \Magento\Framework\DataObject();
                $objParam->setData($params);
                // print_r($objParam); die();
                $cart->addProduct($product, $objParam);

            } catch (Exception $e) {
                $response[$item['product_id']]= $e->getMessage();
            }
        }

        //Set Address to quote
        $cart->getBillingAddress()->addData($orderData['shipping_address']);
        $cart->getShippingAddress()->addData($orderData['shipping_address']);

        // Collect Rates and Set Shipping & Payment Method
        $this->_shippingRate
            ->setCode($data['shipping_method'])
            ->getPrice(1);

        $shippingAddress = $cart->getShippingAddress();

        $shippingAddress->setCollectShippingRates(true)
            ->collectShippingRates()
            ->setShippingMethod($data['shipping_method']); //shipping method
        $cart->getShippingAddress()->addShippingRate($this->_shippingRate);

        $cart->setPaymentMethod($data['payment_method']); //payment method

        $cart->setInventoryProcessed(false);

        // Set sales order payment
        $cart->getPayment()->importData(['method' => 'checkmo']);

        // Collect total and saeve
        $cart->collectTotals();

        // Submit the quote and create the order
        $cart->save();
        $cart = $this->_cartRepositoryInterface->get($cart->getId());
        try{
            $order_id = $this->cartManagementInterface->placeOrder($cart->getId());
            if(isset($order_id) && !empty($order_id)) {
                $order = $this->orderRepository->get($order_id);
                $this->deleteQuoteItems(); //Delete cart items
                $response['success'] = TRUE;
                $response['success_data']['increment_id'] = $order->getIncrementId();
            }
        } catch (Exception $e) {
            $response['error_msg']=$e->getMessage();
        }
    }
    return $response;   
}

0 个答案:

没有答案