How to get order History of customer in Magento 2 API?

Magento own API does not have an endpoint to fetch orders with customer token, it only has one for integration or admin token.

You can use or look at Deity as they prepared magento extension that provides such endpoint: https://github.com/deity-io/falcon-magento2-module/blob/master/src/etc/webapi.xml#L132

Fur disclosure, I have written that piece of code but I am no longer a developer of that module.

There is an alternative if you are using some middleware layer to talk to Magento2 API of which you have control and can use admin token there. First query customers/me endpoint using customer token to fetch current customer data and then query /orders endpoint with admin token providing received customer id in searchCriteria.


Solution 1

You can make your custom API for the same;

Using filter Builder you can use search criteria

$customerId = $this->userContext->getUserId();

$filter = $this->filterBuilder
               ->setField('customer_id')
               ->setValue($customerId)
               ->setConditionType('eq')
               ->create();
$this->searchCriteriaBuilder->addFilters([$filter]);

$searchCriteria = $this->searchCriteriaBuilder->create();

Solution 2

Magento is using resource Magento_Sales::sales because of this we can't access it using Customer's token so for the same we need to override Specific API with

<resource ref="self" />

And using this we can access all orders of specific customer using customer's Token in Magento API.

<route url="/V1/orders" method="GET">
        <service class="Magento\Sales\Api\OrderRepositoryInterface" method="getList"/>
        <resources>
            <resource ref="self" />
        </resources>
    </route>