1

Can anyone let me know if we can Reorder in Magento2 using REST webapi? Actually i have made one api and used same code as magento default reorder does, here is my code in API function using order_id as parameter:

public function reOrder($orderId)
    {
        $order = $this->orderApiRepository->get($orderId);
        $cart = $this->cart;
        $items = $order->getItemsCollection();
        foreach ($items as $item) {
            try {
                $cart->addOrderItem($item);
            } catch (\Exception $e) {
                throw new \Magento\Framework\Exception\LocalizedException(__($e->getMessage()), $e);
            }
        }
    }

The issue is when i am checking response in postman, it returns null instead cart data, please let me know if anyone has done same type of things. please check below screenshot of POSTMAN api:

POSTMAN API

6
  • Got any solution ? Jan 2, 2019 at 10:43
  • have you got solution for this Feb 19, 2019 at 11:51
  • Nope didn't get any solution on it Feb 19, 2019 at 13:06
  • Have you got any solution for this?
    – amesh
    Nov 13, 2019 at 8:53
  • @bhargavshastri Have you got any solution for reorder rest API ? Nov 28, 2019 at 12:06

2 Answers 2

2

Use below code for Reorder api

Create YourNameSpace/Module/etc/webapi.xml

<route url="/V1/reorder/:orderId" method="POST">
    <service class="YourNameSpace\Module\Api\ReorderInterface" method="createReorder"/>
    <resources>
        <resource ref="self" />
    </resources>
    <data>
        <parameter name="cartId" force="true">%cart_id%</parameter>
    </data>
</route>

Create YourNameSpace/Module/Api/ReorderInterface.php

    <?php

namespace YourNameSpace\Module\Api;

interface ReorderInterface
{
    /**
     * 
     *
     * @api
     * @param int $cartId
     * @param int $orderId
     * @return boolean
     */
    public function createReorder($cartId,$orderId);

}

Create YourNameSpace\Module\Model\Reorder.php

<?php

namespace YourNameSpace\Module\Sales\Model;

use YourNameSpace\Module\Api\ReorderInterface;
use Magento\Framework\Exception\NoSuchEntityException;
use Magento\Quote\Api\CartRepositoryInterface;
use Magento\Sales\Model\OrderRepository;
use Magento\Quote\Model\Quote;
use Magento\Catalog\Api\ProductRepositoryInterface;
use Magento\Quote\Api\Data\CartItemInterface;
use Magento\Quote\Api\CartItemRepositoryInterface;

class Reorder implements ReorderInterface
{
    protected $quoteRepository;

    protected $orderRepository;

    protected $quote;

    protected $productRepository;

    protected $cartItemInterface;

    protected $cartItemRepository;

    public function __construct(
        CartRepositoryInterface $quoteRepository,
        OrderRepository $orderRepository,
        Quote $quote,
        ProductRepositoryInterface $productRepository,
        CartItemInterface $cartItemInterface,
        CartItemRepositoryInterface $cartItemRepository
    )
    {
        $this->quoteRepository = $quoteRepository;
        $this->orderRepository = $orderRepository;
        $this->quote = $quote;
        $this->productRepository = $productRepository;
        $this->cartItemInterface = $cartItemInterface;
        $this->cartItemRepository = $cartItemRepository;
    }


    /**
     * @param $cartId
     * @param $orderId
     * @return bool
     */
    public function createReorder($cartId,$orderId)
    {
       // $quoteRepo = $this->quoteRepository->getActive($cartId);
        $order = $this->orderRepository->get($orderId);

        $items = $order->getItemsCollection();
        foreach ($items as $item) {

            try {
              $this->addOrderItem($item, $cartId);
            } catch (\Magento\Framework\Exception\LocalizedException $e) {
                return false;

            } catch (\Exception $e) {
                return false;
            }
        }

        return true;
    }

    public function addOrderItem($orderItem,$quoteId)
    {
        /* @var $orderItem \Magento\Sales\Model\Order\Item */
        if ($orderItem->getParentItem() === null) {
            //$storeId = $this->_storeManager->getStore()->getId();
            try {
                /**
                 * We need to reload product in this place, because products
                 * with the same id may have different sets of order attributes.
                 */
                $product = $this->productRepository->getById($orderItem->getProductId());

            } catch (NoSuchEntityException $e) {
                return $this;
            }

            $this->cartItemInterface->setQuoteId($quoteId);
            $this->cartItemInterface->setSku($product->getSku());
            $this->cartItemInterface->setQty($orderItem->getQtyOrdered());

            $this->cartItemRepository->save($this->cartItemInterface);

        }
    }

}

Pass order id in your api with customer authentication , so it will add your order items in customer cart and gives you true in return so later on you can get cart items by calling /V1/carts/mine/items api.

Hope it will solve your issue.

1
  • If the product have any option, then this will not working. It shows error like 'You need to choose options for your item.'. Any solution to this?
    – amesh
    Nov 13, 2019 at 6:51
0

After Declaration of Web api the Reorder logic in model file ReOrder.php

<?php
namespace HIT\Customer\Model;
use HIT\Customer\Api\ReorderInterface;
use Magento\Framework\Exception\NoSuchEntityException;
use Magento\Quote\Api\CartRepositoryInterface;
use Magento\Sales\Model\OrderRepository;
use Magento\Quote\Model\Quote;
use Magento\Catalog\Api\ProductRepositoryInterface;
use Magento\Quote\Api\Data\CartItemInterface;
use Magento\Quote\Api\CartItemRepositoryInterface;

class ReOrder implements ReorderInterface
{

    protected $orderRepository;

    protected $productRepository;

    protected $cartItemRepository;

    protected $cartManagementInterface;

    protected $customerRepositoryInterface;

   public function __construct(

        \Magento\Framework\ObjectManagerInterface $objectmanager,
         CartRepositoryInterface $cartRepositoryInterface,
        OrderRepository $orderRepository,
        ProductRepositoryInterface $productRepository,
        \Magento\Store\Model\StoreManagerInterface $storeManager,
        \Magento\Quote\Api\CartManagementInterface $cartManagementInterface,
        \Magento\Customer\Api\CustomerRepositoryInterface $customerRepositoryInterface


    ){

        $this->_objectManager = $objectmanager;
        $this->cartRepositoryInterface = $cartRepositoryInterface;
        $this->orderRepository = $orderRepository;
        $this->productRepository = $productRepository;
         $this->storeManager = $storeManager;
         $this->cartManagementInterface = $cartManagementInterface;
        $this->_customerRepositoryInterface = $customerRepositoryInterface;
    }

    public function reOrder() {

        $data = array();

        $json = file_get_contents('php://input');
        $post = json_decode($json);

        $order = $this->orderRepository->get($post->order_id);

        $items = $order->getItemsCollection();
        foreach ($items as $item) {

            try {
              $this->addOrderItem($item, $post->customer_id);
               $data['status'] = "true";
               $data['msg'] = "Product addedd to your cart Successfully";

            } catch (\Magento\Framework\Exception\LocalizedException $e) {
                   $data['status'] = "false";
                    $data['msg'] = $e->getMessage();

            } catch (\Exception $e) {
                    $data['status'] = "false";
                    $data['msg'] = $e->getMessage();
            }
        }

         echo json_encode($data, JSON_UNESCAPED_SLASHES | JSON_PRETTY_PRINT );
         exit();
    }
    public function addOrderItem($item,$cid)
    {
        if ($item->getParentItem() === null) {
                  $cartId= $this->_objectManager->create('Magento\Quote\Model\Quote')->loadByCustomer($cid)->getId();

                  if(empty($cartId)){
                    $cartId = $this->cartManagementInterface->createEmptyCart(); 
                    $quote = $this->cartRepositoryInterface->get($cartId); // load empty cart quote
                    $quote->setStoreId($this->storeManager->getStore()->getId());
                    $customer= $this->_customerRepositoryInterface->getById($cid);
                    $quote->setCurrency();
                    $quote->assignCustomer($customer);
                    }else{
                         $quote = $this->cartRepositoryInterface->get($cartId); 
                    }

                    $_product = $this->productRepository->getById($item->getProductId());    
                    $quote->addProduct($_product,$item->getQtyOrdered()); 
            try {

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


            } catch (NoSuchEntityException $e) {
                echo $e->getMessage();
                exit();
            }


        }
    }





}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.