Place order programatically & redirect to thankyou/success page. (Magento 2)

Modified today

Viewed 3 times

1

I am working on creating a functionality where I have added a “buy now” button on the product page, when the user clicks that button then a popup form appears, entering all necessary details in that form & clicking on order now.

I post data to the controller where currently I have added static code to create order programmatically.

Order gets created successfully, but I need to redirect the customer too on the thank you/success page once the order is created. But I am facing issues & not sure how to manage sessions to redirect users to the success/thank you page.

here is the controller file code :

namespace Hs\BuyNow\Controller\Cart;
class Now extends \Magento\Framework\App\Action\Action
{
    public function __construct(\Magento\Framework\View\Result\PageFactory $pageFactory, \Magento\Framework\App\Action\Context $context, \Magento\Store\Model\StoreManagerInterface $storeManager, \Magento\Catalog\Model\Product $product, \Magento\Framework\Data\Form\FormKey $formkey, \Magento\Quote\Model\QuoteFactory $quote, \Magento\Quote\Model\QuoteManagement $quoteManagement, \Magento\Customer\Model\CustomerFactory $customerFactory, \Magento\Customer\Api\CustomerRepositoryInterface $customerRepository, \Magento\Sales\Model\Service\OrderService $orderService, \Magento\Framework\App\Request\Http $request,
    \Magento\Framework\Controller\ResultFactory $resultPageFactory,
    \Magento\Checkout\Model\Session $checkoutSession,
    \Magento\Quote\Api\GuestCartManagementInterface $guestcartManagement
    )
    {
        $this->storeManager = $storeManager;
        $this->product = $product;
        $this->formkey = $formkey;
        $this->quote = $quote;
        $this->quoteManagement = $quoteManagement;
        $this->customerFactory = $customerFactory;
        $this->customerRepository = $customerRepository;
        $this->orderService = $orderService;
        $this->_pageFactory = $pageFactory;
        $this->request = $request;
        $this->resultRedirect = $context->getResultFactory();
        $this->_checkoutSession = $checkoutSession;
        $this->guestcartManagement = $guestcartManagement;
        parent::__construct($context);
    }
    public function createOrder($order)
    {
        $store = $this->storeManager->getStore();
        $websiteId = $this->storeManager->getStore()->getWebsiteId();
        $customer = $this->customerFactory->create();
        $customer->setWebsiteId($websiteId);
        $customer->loadByEmail($order['email']); // load customet by email address
        if (!$customer->getEntityId()) {
        //If not avilable then create this customer
        $customer->setWebsiteId($websiteId)->setStore($store)->setFirstname($order['shipping_address']['firstname'])->setLastname($order['shipping_address']['lastname'])->setEmail($order['email'])->setPassword($order['email']);
        $customer->save();
        }
        $quote = $this->quote->create(); // Create Quote Object
        $quote->setStore($store); // Set Store
        $customer = $this->customerRepository->getById($customer->getEntityId());
        $quote->setCurrency();
        $quote->assignCustomer($customer); // Assign quote to Customer
        //add items in quote
        foreach ($order['items'] as $item) {
        $product = $this->product->load($item['product_id']);
        $product->setPrice(59);
        $quote->addProduct($product, intval($item['qty']));
        }
        $quote->getBillingAddress()->addData($order['shipping_address']);
        $quote->getShippingAddress()->addData($order['shipping_address']);
        // Collect Rates and Set Shipping & Payment Method
        $shippingAddress = $quote->getShippingAddress();
        $shippingAddress->setCollectShippingRates(true)->collectShippingRates()->setShippingMethod('freeshipping_freeshipping');
        $quote->setPaymentMethod('cod');
        $quote->setInventoryProcessed(false);
        $quote->save();
        // Set Sales Order Payment
        $quote->getPayment()->importData(['method' => 'checkmo']);
        // Collect Totals & Save Quote
        $quote->collectTotals()->save();
        $orderId = $this->guestCartManagement->placeOrder($quote->getId());
        $orderdata->setEmailSent(0);
        $orderdata = $orderdata->getIncrementId();
    }
    public function execute()
    {
        $order = [
            'currency_id' => 'USD',
            'email' => 'hello@example.com',
            'shipping_address' => ['firstname' => 'John',
            'lastname' => 'Any',
            'street' => 'xxxxxx',
            'city' => 'xxxxxxx',
            'country_id' => 'US',
            'region' => 'xxxxx',
            'postcode' => '85001',
            'telephone' => '52556542',
            'fax' => '3242322556',
            'save_in_address_book' => 1],
            'items' => [
            ['product_id' => '6', 'qty' => 1],
            ]
        ];
        $this->createOrder($order);
        $resultRedirect = $this->resultRedirectFactory->create();
        $resultRedirect->setPath('checkout/onepage/success');
        return $resultRedirect;
    }
}