Webkul
Services
Technologies Bagisto QloApps
iOS Android SAP BigCommerce Wix
Trusted by
Samsung Intel Toyota Walmart Disney Nokia Nestlé Decathlon
See all customers
Back to Top
DEV

Create Order Programmatically According To Store Currency Magento 2

Create Order Programmatically According To Store Currency Magento 2 : when we create order Programmatically it is created according to base currency. but sometime we need to create order according to specific store currency.
So here i am explaining how you can do it.

 <?php   
    public function __construct(
        \Magento\Framework\App\Action\Context $context,
        \Magento\Store\Model\StoreManagerInterface $storeManager,
        \Magento\Directory\Model\CurrencyFactory $currencyFactory,
        \Magento\Catalog\Model\ProductFactory $productFactory,
        \Magento\CatalogInventory\Api\StockRegistryInterface $stockRegistry,
        \Magento\Customer\Model\CustomerFactory $customerFactory,
        \Magento\Customer\Api\CustomerRepositoryInterface $customerRepository,
        \Magento\Backend\Model\Session $backendSession,
        \Magento\Quote\Api\CartRepositoryInterface $cartRepositoryInterface,
        \Magento\Quote\Api\CartManagementInterface $cartManagementInterface,
        \Magento\Quote\Model\Quote\Address\Rate $shippingRate,
        \Magento\Sales\Model\Order $order,
    ) {
        $this->storeManager = $storeManager;
        $this->productFactory = $productFactory;
        $this->stockRegistry = $stockRegistry;
        $this->customerFactory = $customerFactory;
        $this->customerRepository = $customerRepository;
        $this->backendSession = $backendSession;
        $this->cartRepositoryInterface = $cartRepositoryInterface;
        $this->cartManagementInterface = $cartManagementInterface;
        $this->shippingRate = $shippingRate;
        $this->order = $order;
        $this->currencyFactory = $currencyFactory;
        parent::__construct($context);
    }
     /**
     * Execute
     *
     * @return void
     */
     public function execute(){
        $orderData =[
            'currency_id'  => 'USD',
            'email'        => '[email protected]', //customer email id
            'shipping_address' =>[
                'firstname'    => 'demo',
                'lastname'     => 'demo',
                'prefix' => '',
                'suffix' => '',
                'street' => 'B1 Abcd street',
                'city' => 'Los Angeles',
                'country_id' => 'US',
                'region' => 'California',
                'region_id' => '12', // State region id
                'postcode' => '45454',
                'telephone' => '1234512345',
                'fax' => '12345',
                'save_in_address_book' => 1
            ],
            'items'=>
                [
                    ['product_id'=>'50','qty'=>1]
                ]
        ];
        $this->createOrderAtMage($orderData);
    }
    /**
     * Create order on magento
     * 
     * @param  array $orderData
     * @return array
     */
    public function createOrderAtMage($orderData)
    {
        $store = $this->storeManager->getStore();
        $storeId = $store->getStoreId();
        $websiteId = $this->storeManager->getStore($storeId)->getWebsiteId();
        $customer = $this->customerFactory->create();
        $customer->setWebsiteId($websiteId);
        $customer->loadByEmail($orderData['email']);
        if (!$customer->getEntityId()) {
            $customer->setWebsiteId($websiteId)
                    ->setStore($store)
                    ->setFirstname($orderData['shipping_address']['firstname'])
                    ->setLastname($orderData['shipping_address']['lastname'])
                    ->setEmail($orderData['email'])
                    ->setPassword($orderData['email']);
            $customer->save();
        }
        $cartId = $this->cartManagementInterface->createEmptyCart();
        $quote = $this->cartRepositoryInterface->get($cartId);
        $quote->setStore($store);
        // make change here.
        $currencyCode = 'USD';
        // make change here.
        $currency =  $this->currencyFactory->create()->load($currencyCode);
        $this->storeManager->getStore($storeId)->setCurrentCurrency($currency);
        $customer = $this->customerRepository->getById($customer->getEntityId());
        
        $quote->setCurrency();
        $quote->assignCustomer($customer);
        foreach ($orderData['items'] as $item) {
            $product = $this->productFactory->create()->load($item['product_id']);
            $quote->addProduct(
                $product,
                (int)$item['qty']
            );
        }
        
        //Set Address to quote
        $quote->getBillingAddress()->addData($orderData['shipping_address']);
        $quote->getShippingAddress()->addData($orderData['shipping_address']);
        // Collect Rates and Set Shipping & Payment Method
        $shipmethod = "flatrate_flatrate"; //change according to your need
        // Collect Rates and Set Shipping & Payment Method
        $this->shippingRate
            ->setCode($shipmethod)
            ->getPrice(1);
        //store shipping data in session
        $shippingAddress = $quote->getShippingAddress();
        $shippingAddress->setCollectShippingRates(true)
                        ->collectShippingRates()
                        ->setShippingMethod($shipmethod);
        $quote->getShippingAddress()->addShippingRate($this->shippingRate);
        $quote->setPaymentMethod(/** payment method code */);
        $quote->setInventoryProcessed(false);
        $paymentCode = "checkmo"; //change according to your need

        // Set Sales Order Payment
        $quote->getPayment()->importData(['method' => $paymentCode]);
        $quote->save();
        // Collect Totals & Save Quote
        $quote->collectTotals();
        // Create Order From Quote
        $quote = $this->cartRepositoryInterface->get($quote->getId());
        $orderId = $this->cartManagementInterface->placeOrder($quote->getId());
        echo $orderId;die;
    }

Hope so it will help.

. . .

Leave a Comment

Your email address will not be published. Required fields are marked*


Be the first to comment.

Back to Top

Message Sent!

If you have more details or questions, you can reply to the received confirmation email.

Back to Home