0

I tried to create order programmatically with flat rate shipping method with the help of below code. Here, order created successfully but shipping method and rates not apply to order.

use Magento\Framework\App\Bootstrap;
require __DIR__ . '/../app/bootstrap.php';
$params = $_SERVER;
$bootstrap = Bootstrap::create(BP, $params);
$objectManager = $bootstrap->getObjectManager();
$state = $objectManager->get('Magento\Framework\App\State');
$state->setAreaCode('frontend');


$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
$storeManager = $objectManager->get('\Magento\Store\Model\StoreManagerInterface');
$store = $storeManager->getStore(5);
$storeCode = $store->getCode();
$storeManager->setCurrentStore($storeCode);

$coreSession = $objectManager->create('\Magento\Framework\Session\SessionManagerInterface');
$coreSession->setIsFailOrder('YES');    //  Biggest patch because we have to create order with archive status and also follow PCI compliance.

$orderData=[
    'currency_id'  => 'USD',
    'email'        => 'helloworld@mageplaza.com', //buyer email id
    'shipping_address' =>[
        'firstname'    => 'John', //address Details
        'lastname'     => 'Doe',
        'street' => '123 Demo',
        'city' => 'Mageplaza',
        'country_id' => 'US',
        'region' => 43, //'xxx',
        'postcode' => '10019',
        'telephone' => '0123456789',
        'fax' => '32423',
        'save_in_address_book' => 1
    ],
   'items'=> [ //array of product which order you want to create
        ['product_id' => '5', 'qty'=> 2]
    ]
];


$store = $storeManager->getStore();
$websiteId = $storeManager->getStore()->getWebsiteId();
$customer = $objectManager->create('Magento\Customer\Model\Customer');
$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();
}

$quote = $objectManager->create('Magento\Quote\Model\Quote');
$quote->setStore($store); //set store for which you create quote
// if you have allready buyer id then you can load customer directly 
$customerRepository = $objectManager->create('Magento\Customer\Api\CustomerRepositoryInterface');
$customer = $customerRepository->getById($customer->getEntityId());
$quote->assignCustomer($customer); //Assign quote to customer

//add items in quote
$product = $objectManager->create('Magento\Catalog\Model\Product');
foreach($orderData['items'] as $item){
    $product = $product->load($item['product_id']);
    $product->setPrice($product->getPrice());
    $quote->addProduct(
        $product,
        intval($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
$shippingRate = $objectManager->get('Magento\Quote\Model\Quote\Address\Rate');
$shippingRate->setCode('flatrate_flatrate')->getPrice(0);

$shippingAddress = $quote->getShippingAddress();
$shippingAddress->setCollectShippingRates(true)
                ->collectShippingRates()
                ->setShippingMethod('flatrate_flatrate'); //shipping method
$quote->getShippingAddress()->addShippingRate($shippingRate);


$shoppingCartPriceRule = $objectManager->create('Magento\SalesRule\Model\Rule');
$rule = $shoppingCartPriceRule->load(9);
$rule->setDiscountAmount('7')->save();
$quote->setCouponCode('amazoncode');

$quote->setPaymentMethod('cashondelivery'); //payment method
$quote->setInventoryProcessed(false); //not effetc inventory
$quote->save(); //Now Save quote and your quote is ready

// Set Sales Order Payment
$quote->getPayment()->importData(['method' => 'cashondelivery']);

// Collect Totals & Save Quote
$quote->collectTotals()->save();

// Create Order From Quote
$quoteManagement = $objectManager->create('Magento\Quote\Model\QuoteManagement');
$order = $quoteManagement->submit($quote);
$order->setEmailSent(0);

$payment = $order->getPayment();
$payment->setMethod('authorizenet_acceptjs'); // Assuming 'test' is updated payment method
$payment->save();
$order->setState('new');
$order->setStatus('archive');
$order->setEmailSent(0);
$order->save();
$incrementId = $order->getRealOrderId();
$custoemrName = $order->getCustomerName();
$coreSession->unsIsFailOrder();
echo $incrementId;exit;

enter image description here

Please help me how to assign shipping method and rates to order?

Regards Hiren Shah

  • uspsstandard_uspsstandard shipping method available is your store? – Jigs Parmar Sep 3 at 6:25
  • Yes we created custom shipping method but now you can see updated question which create order with flatrate shipping method but still not working. – Hiren Shah Sep 3 at 6:26
2

please use below code it working fine in my store

https://meetanshi.d.pr/GAWATQ

ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
ini_set('memory_limit', '5G');
error_reporting(E_ALL);

use Magento\Framework\App\Bootstrap;

require 'app/bootstrap.php';
$bootstrap = Bootstrap::create(BP, $_SERVER);
$objectManager = $bootstrap->getObjectManager();
$state = $objectManager->get('Magento\Framework\App\State');
$state->setAreaCode('frontend');

$fileFactory = $objectManager->create('Magento\Framework\App\Response\Http\FileFactory');


$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
$storeManager = $objectManager->get('\Magento\Store\Model\StoreManagerInterface');
$store = $storeManager->getStore(1);
$storeCode = $store->getCode();
$storeManager->setCurrentStore($storeCode);

$coreSession = $objectManager->create('\Magento\Framework\Session\SessionManagerInterface');
$coreSession->setIsFailOrder('YES');    //  Biggest patch because we have to create order with archive status and also follow PCI compliance.

$orderData = [
    'currency_id' => 'INR',
    'email' => 'helloworld@mageplaza.com', //buyer email id
    'shipping_address' => [
        'firstname' => 'John', //address Details
        'lastname' => 'Doe',
        'street' => '123 Demo',
        'city' => 'Mageplaza',
        'country_id' => 'IN',
        'region' => 544, //'xxx',
        'postcode' => '10019',
        'telephone' => '0123456789',
        'fax' => '32423',
        'save_in_address_book' => 1
    ],
    'items' => [ //array of product which order you want to create
        ['product_id' => '1', 'qty' => 2]
    ]
];

try {


    $store = $storeManager->getStore();
    $websiteId = $storeManager->getStore()->getWebsiteId();
    $customer = $objectManager->create('Magento\Customer\Model\Customer');
    $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();
    }

    $quote = $objectManager->create('Magento\Quote\Model\Quote');
    $quote->setStore($store); //set store for which you create quote
// if you have allready buyer id then you can load customer directly
    $customerRepository = $objectManager->create('Magento\Customer\Api\CustomerRepositoryInterface');
    $customer = $customerRepository->getById($customer->getEntityId());
    $quote->assignCustomer($customer); //Assign quote to customer

//add items in quote
    $product = $objectManager->create('Magento\Catalog\Model\Product');
    foreach ($orderData['items'] as $item) {
        $product = $product->load($item['product_id']);
        $product->setPrice($product->getPrice());
        $quote->addProduct(
            $product,
            intval($item['qty'])
        );
    }

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

    $shippingAddress = $quote->getShippingAddress();
    $shippingAddress->setCollectShippingRates(true)->collectShippingRates()->setShippingMethod('freeshipping_freeshipping ');
    $quote->setPaymentMethod('cashondelivery');
    $quote->setInventoryProcessed(false);
    $quote->save();

// Set Sales Order Payment
    $quote->getPayment()->importData(['method' => 'cashondelivery']);

// Collect Totals & Save Quote
    $quote->collectTotals()->save();

// Create Order From Quote
    $quoteManagement = $objectManager->create('Magento\Quote\Model\QuoteManagement');
    $order = $quoteManagement->submit($quote);
    $order->setEmailSent(0);

    $payment = $order->getPayment();
    $payment->setMethod('authorizenet_acceptjs'); // Assuming 'test' is updated payment method
    $payment->save();
    $order->setState('new');
    $order->setStatus('archive');
    $order->setEmailSent(0);
    $order->save();
    $incrementId = $order->getRealOrderId();
    $custoemrName = $order->getCustomerName();
    $coreSession->unsIsFailOrder();
    echo $incrementId;
} catch (\Exception $e) {
    echo 'error:-  ' . $e->getMessage();
}
  • Thanks for the given me whole code with changes. I try to run your code but it will gives me error. error:- The shipping method is missing. Select the shipping method and try again. I have checked the store configuration and flatrate shipping method enable for all stores. – Hiren Shah Sep 3 at 6:48
  • please clear cache and check , – Jigs Parmar Sep 3 at 6:50
  • and check that in frontend flatrate shipping method is show or not? , ill also update the shipping address to INDIA you can also change that and check – Jigs Parmar Sep 3 at 6:50
  • my store is in INR so i set the INR and country as INDIA and state set , you need to change that as per your need – Jigs Parmar Sep 3 at 7:02
  • Yes flatrate shipping method display in frontend side. – Hiren Shah Sep 3 at 7:03
0

Below code works perfectly.

<?php
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
ini_set('memory_limit', '5G');
error_reporting(E_ALL);

use Magento\Framework\App\Bootstrap;

require __DIR__ . '/../app/bootstrap.php';
$params = $_SERVER;
$bootstrap = Bootstrap::create(BP, $params);
$objectManager = $bootstrap->getObjectManager();
$state = $objectManager->get('Magento\Framework\App\State');
$state->setAreaCode('frontend');

$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
$storeManager = $objectManager->get('\Magento\Store\Model\StoreManagerInterface');
$store = $storeManager->getStore(5);    //  Set particular store if multi-store available
$storeCode = $store->getCode();
$storeManager->setCurrentStore($storeCode);

$orderData = [
    'currency_id' => 'USD',
    'email' => 'helloworld@mageplaza.com', //buyer email id
    'shipping_address' => [
        'firstname' => 'John', //address Details
        'lastname' => 'Doe',
        'street' => '123 Demo',
        'city' => 'New York',
        'country_id' => 'US',
        'region' => 43, //'xxx',
        'postcode' => '10001',
        'telephone' => '0123456789',
        'fax' => '32423',
        'save_in_address_book' => 1
    ],
    'items' => [ //array of product which order you want to create
        ['product_id' => '1', 'qty' => 2]
    ]
];

try {

    $store = $storeManager->getStore();
    $websiteId = $storeManager->getStore()->getWebsiteId();
    $customer = $objectManager->create('Magento\Customer\Model\Customer');
    $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();
    }

    $quote = $objectManager->create('Magento\Quote\Model\Quote');
    $quote->setStore($store); //set store for which you create quote
    $quote->setStoreId($store->getId());

    $customerRepository = $objectManager->create('Magento\Customer\Api\CustomerRepositoryInterface');
    $customer = $customerRepository->getById($customer->getEntityId());
    $quote->assignCustomer($customer); //Assign quote to customer

    $product = $objectManager->create('Magento\Catalog\Model\Product');
    foreach ($orderData['items'] as $item) {
        $product = $product->load($item['product_id']);
        $product->setPrice($product->getPrice());
        $quote->addProduct(
            $product,
            intval($item['qty'])
        );
    }

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

    //Collect shipping rates on quote
    $shippingAddressData->setCollectShippingRates(true)->collectShippingRates();

    $shoppingCartPriceRule = $objectManager->create('Magento\SalesRule\Model\Rule');
    $rule = $shoppingCartPriceRule->load(9);
    $discountamt = 10;  //($discount > 0)?$discount:0;
    $rule->setDiscountAmount($discountamt)->save();
    $quote->setCouponCode('amazoncode');

    $shippingAddressData->setCollectShippingRates(true);
    $shippingAddressData->setShippingMethod('uspsstandard_uspsstandard')->setPaymentMethod('cashondelivery');   //  Custom shipping method same like faltrate_flatrate
    $quote->setInventoryProcessed(false);
    $quote->save();

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

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

    $quoteManagement = $objectManager->create('Magento\Quote\Model\QuoteManagement');
    $order = $quoteManagement->submit($quote);
    $order->setEmailSent(0);

    $payment = $order->getPayment();
    $payment->setMethod('authorizenet_acceptjs'); // Assuming 'test' is updated payment method
    $payment->save();
    $order->setState('new');
    $order->setStatus('archive');
    $order->setEmailSent(0);
    $order->save();
    $incrementId = $order->getRealOrderId();
    $custoemrName = $order->getCustomerName();
    echo $incrementId;
} catch (\Exception $e) {
    echo 'error:-  ' . $e->getMessage();
}

?>

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.