Question

Hi all, actually i am creating an order programmatically now i trying to set custom shipping amount to order.

@all i tried Magento1.X link there they have implemented using $order->setShippingAmount($shippingAmount); and similar functions we have in Magento 2.X also.

$customerProductDetails = $this->_customerHelper->getCustomerData($refCode);
        $orderData = $this->getOrderDetails($customerProductDetails);
        $store=$this->_storeManager->getStore();
        $websiteId = $this->_storeManager->getStore()->getWebsiteId();
        $customer=$this->customerFactory->create();
        $customer->setWebsiteId($websiteId);
        $customer->loadByEmail($orderData['email']);// load customet by email address
        if(!$customer->getEntityId()){
            //If not avilable 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();
        }
        $activeQuote = $this->quote->create()->getCollection()->addFieldToFilter('customer_id',$customer->getEntityId())->addFieldToFilter('is_active',1);
        $cartId = $activeQuote->getLastItem()->getData('entity_id');
        if(!$cartId):
            $cartId = $this->cartManagementInterface->createEmptyCart(); //Create empty cart
        endif;
        $quote = $this->cartRepositoryInterface->get($cartId); // load empty cart quote

        $quote->setStore($store);

        $customer= $this->customerRepository->getById($customer->getEntityId());
        $quote->setCurrency();
        $quote->assignCustomer($customer); //Assign quote to customer
        //add items in quote
        foreach($orderData['items'] as $item){
            $product = $this->_productFactory->create()->load($item['product_id']);
            $product->setPrice($item['price']);
            $quote->addProduct($product, intval($item['qty']));
            $this->logger->info('discountAmt'.$item['discount']);
            $quote->setDiscountAmount($item['discount']);
        }

        $quote->getBillingAddress()->addData($orderData['shipping_address']);
        $quote->getShippingAddress()->addData($orderData['shipping_address']);


        $shippingMethod = $this->getShippingMethod($refCode);
        $this->logger->info("shippingMethod".json_encode($shippingMethod));

        $shippingAmount = $this->getShippingAmount($refCode);
        $this->logger->info("shippingAmount".json_encode($shippingAmount));


        $shippingAddress=$quote->getShippingAddress();
        $shippingAddress->setCollectShippingRates(true)
                        ->collectShippingRates()
                        ->setShippingMethod($shippingMethod[0]); //shipping method
       // $quote->getShippingAddress()->addShippingRate($this->rate);
        $quote->setPaymentMethod('checkmo'); //payment method
        $quote->setInventoryProcessed(false); //not effect inventory

        $quote->getPayment()->importData(['method' => 'banktransfer']);

        $quote->collectTotals()->save();

        //$quote->save(); //Now Save quote and your quote is ready
        //$this->quoteRepository->save($quote);

        $this->logger->info("ordershippingMethod".json_encode($shippingAmount));


        $this->customerResourceModel->updateQuoteOrderByRefCode($refCode,$quote->getId(),'quote');
        $order = $this->quoteManagement->submit($quote);
        $increment_id = $order->getRealOrderId();
        $grandTotal   = $order->getBaseGrandTotal();
        $currencyCode = $order->getBaseCurrencyCode();
        //$this->makePayment($increment_id,$grandTotal,$currencyCode,$quote->getId());

        if($order->getRealOrderId()){
            //$result['order_id']= $order->getRealOrderId();
            $this->ServiceResourceModel->updateQuoteOrderByRef($refCode,$order->getRealOrderId(),'order');
           return  $this->_redirect("service/service/success", ['id' => $order->getRealOrderId()]);
        }else{
            $this->_messageManager->addErrorMessage(__("Unable to place the order!"));

        }
        // Create Order From Quote
        $quote = $this->cartRepositoryInterface->get($quote->getId());
        $orderId = $this->cartManagementInterface->placeOrder($quote->getId());
        $order = $this->order->load($orderId);
        $order->setShippingAmount($shippingAmount[0]);
        $order->setEmailSent(0);

If anyone has any idea please guide me.Thanks in Advance..!!!

Was it helpful?

Solution

Below code worked for me

   $shippingprice = "your custom shipping amount";
   $order->setShippingAmount($shippingprice);
   $order->setBaseShippingAmount($shippingprice);
   $order->setGrandTotal($order->getGrandTotal() + $shippingprice); //adding shipping price to grand total
   $order->save();
Licensed under: CC-BY-SA with attribution
Not affiliated with magento.stackexchange
scroll top