Magento2: Consumer Order Rest API

Created on 26 Feb 2016  路  21Comments  路  Source: magento/magento2

We are using the Magento 2 REST API. We are able to access the the orders using the admin token. But we are unable to access the orders using consumer.
Below is the API which I am using:
Get Orders : /rest/V1/orders/items But I am getting the error that Consumer is not authorized to access %resources even I have passed the consumer key in my header.

Is the customer orders REST api is implemented ?

Ready for Work

Most helpful comment

@choukalos can you reopen this issue? This is real problem with bad REST API design. There is no option to get all customer orders without setting there admin rights. So can you create api call like /V1/orders/me/items ?

@develpr did you solve this?

All 21 comments

I believe the two API's are /rest/V1/orders/:id to get the details one the customer's orders or /rest/V1/orders to get all the orders related to that customer.

If you want to build a quote object and submit that as a customer you should be using the /rest/V1/carts/mine/ series of APIs.

If you have further questions - please ask on our Forums.

Thanks choukalos for quinck reply.
We know these two API's order detail and *_get orders *_ but It works only for admin not for customer. We want to see only specific customer orders. So would you please help us which API for get specific customer orders ?

For specific customer you have to pass customer email parameter in api.

http://www.youdomain.com/rest/V1/orders?searchCriteria[filter_groups][0][filters][0][field]=customer_email&searchCriteria[filter_groups][0][filters][0][value][email protected]

and pass admin Bearer key instead customer Bearer key

In my opinion it seems that the customer authentication should to suffice to return a list of orders for the authenticated Customer.

@choukalos can you reopen this issue? This is real problem with bad REST API design. There is no option to get all customer orders without setting there admin rights. So can you create api call like /V1/orders/me/items ?

@develpr did you solve this?

I have the same problem. If you are working in a Web App Client for Magento2, I do not want to a admin token for security reason. Anybody have some idea/opinion about it and how solve it?

@rujmiak I ended up writing my own endpoint, which was fairly easy overall. But yeah, no official updates that I'm aware of :(

I'm learning about Magento 2. I'm trying create my own endpoint to using this tutorial :) http://www.ipragmatech.com/extend-magento2-rest-api-easy-steps/

@develpr can you share it with others? :)

Sure, let me put something together @rujmiak

Is there any progress on this? Can you share your solution @develpr , please?

I am suffer from this problem. Any body have a solution?

Sorry I never ended up pasting code, the truth is there just isn't that much to it. That said, here are the basic steps:

  1. Create a module (or use one of your existing custom modules)
  2. Create / edit your webapi.xml file to add a new custom endpoint (might not be required but that is what I do, to "namespace" all of our custom web service endpoints). So you might have something like
<route url="/V1/custom-orders" method="GET">
        <service class="MyCustomModule\CustomerApi\Api\OrderRepositoryInterface" method="getCustomerList"/>
        <resources>
            <resource ref="self" />
        </resources>
        <data>
            <parameter name="customerId" force="true">%customer_id%</parameter>
        </data>
    </route>

Then you would of course need an OrderRepositoryInterface at the above path, as well as an implementation of that interface, and of course you'd need to update di.xml to map those two together for injection.

Finally, in the concrete OrderRepository class, assuming you extend the OOTB MagentoOrderRepository, you could simply implement the getCustomerList method with something like this:

method signature:

public function getCustomerList($customerId, \Magento\Framework\Api\SearchCriteria $searchCriteria)

body

        $filterGroups = $searchCriteria->getFilterGroups();
        $customerFilterGroup = new FilterGroup();
        $customerFilter = new Filter();
        $customerFilter->setField('customer_id');
        $customerFilter->setValue($customerId);
        $customerFilterGroup->setFilters([
            $customerFilter
        ]);
        $filterGroups[] = $customerFilterGroup;

        $searchCriteria->setFilterGroups($filterGroups);
        $searchResult = parent::getList($searchCriteria);

        return $searchResult;

Note that this is basically the same code that admin version of the repository does, but I added the customer filter to filter the orders returned by customer ID.

Alternatively, you could implement that method the way that the "normal" FE logic does it, by injecting a CollectionFactoryInterface and doing something like

$orders = $this->collectionFactory->create($customerId)->addFieldToSelect( '*' )->setOrder( 'created_at', 'desc' );

I don't know, that might be "safer" (?) but the first method works well in my (somewhat limited!) testing.

@develpr , Thanks for help, but can you share the full answer files on an organized well. I am new to magento.?
Another question plz, Can I use this API for get only pending or completed or any status?
Thx,

@slimzc , I followed the steps in the link you shared, It is returning all the orders for a specific customer, Ho can I return orders with a specific status(pending, complete) ?

@msliman, I have tried with API filters in parameters or put a "if" in the endpoint implementation (Order.php in the model)?

@slimzc I made some changes and working fine. thank you.

is there any update regarding fetching the orders list of customer via REST API? i am also getting error , consumer Consumer is not authorized to access Magento_Sales::sales

is there any update regarding fetching the orders list of customer via REST API? i am also getting error , consumer Consumer is not authorized to access Magento_Sales::sales.Please tell me solution i have same error.

Why this merge request referenced this issue. I've took a look at it and notting fix this issue in it.

Here is a very small tutorial to make this work (thanks to @develpr for pointing me in the right direction). Create a module with the normal module stuff, let's call it Vendor_MyOrders. Create a directory called Api and within it an interface named OrderInterface.

Code would be :

`
interface OrderInterface
{
/**
* @return \Magento\Sales\Api\Data\OrderSearchResultInterface
*/
public function getOrders();

/**
 * @param string $id
 * @return \Magento\Sales\Api\Data\OrderSearchResultInterface
 */
public function getOrder($id);

}
`

Creat a di.xml with the following line:
<preference for="Vendor\MyOrders\Api\OrderInterface" type="Vendor\MyOrders\Model\Api\Order" />
So it says use the Model\Api\Order file when this OrderInterface is called

next, create the Order file and use the $userContext to get the user (this is a bit saver then using a customerId), here is the code:

`use Vendor\MyOrders\Api\OrderInterface;

class Order implements OrderInterface
{
private $orderCollectionFactory;
private $userContext;

public function __construct(
    \Magento\Sales\Model\ResourceModel\Order\CollectionFactory $orderCollectionFactory,
    \Magento\Authorization\Model\UserContextInterface $userContext
) {
    $this->orderCollectionFactory = $orderCollectionFactory;
    $this->userContext = $userContext;
}

/**
 * { @inheritDoc }
 */
public function getOrders() {
    $customerId = $this->userContext->getUserId();
    $orders = $this->orderCollectionFactory->create()->addFieldToSelect('*')->addFieldToFilter('customer_id', $customerId);

    return $orders;
}

/**
 * { @inheritDoc }
 */
public function getOrder($id) {
    $customerId = $this->userContext->getUserId();
    $order = $this->orderCollectionFactory
        ->create()
        ->addFieldToSelect('*')
        ->addFieldToFilter('customer_id', $customerId)
        ->addFieldToFilter('entity_id', $id);

    return $order;
}

}`

now all we need is a webapi.xml (in the etc directory!) that tells the consumer where to get his/her order:
`

    <service class="Vendor\MyOrders\Api\OrderInterface" method="getOrders"/>

    <resources>

        <resource ref="self"/>

    </resources>

</route>

<route url="/V1/myorders/orders/:id" method="GET">

    <service class="Vendor\MyOrders\Api\OrderInterface" method="getOrders"/>

    <resources>

        <resource ref="self"/>

    </resources>

</route>

`

That is it.

Was this page helpful?
0 / 5 - 0 ratings