2

I am beginner on a magento rest api, I cannot see in the API files or docs on how to retrieve order details of customer from customer id.

2

3 Answers 3

3

In this link you have all the information:

https://devdocs.magento.com/swagger/#/salesOrderRepositoryV1/salesOrderRepositoryV1GetListGet

This is an example working on Postman, if you need any help to make it work in php let me know ;)

enter image description here

http://yoursite.com/index.php/rest/V1/orders?searchCriteria[filterGroups][0][filters][0][field]=customer_id&searchCriteria[filterGroups][0][filters][0][value]={customer_id}&searchCriteria[filterGroups][0][filters][0][condition_type]==

4
  • According to screenshot url order count wrong. It show all order count not customer vise plz check
    – Gagan
    Jul 2, 2020 at 15:40
  • Ups....Sorry, just updated the screenshot, my mistake. On the red square you have to put your customer id ;) This should work ! yoursite.com/index.php/rest/V1/…
    – Joao71
    Jul 2, 2020 at 16:03
  • Please if this solved your problem mark as answer :)
    – Joao71
    Jul 3, 2020 at 21:31
  • Don't mean to nag you but please, if this solved your issue mark it as answer. Thanks !
    – Joao71
    Jul 22, 2020 at 8:13
2

Please find a script that is standolone and can be placed anywhere within your magento files, on my environment it is in the folder

<magento-root>/app/code/Mbs/OrderRepositoryExtension/shell/getlistordersbycustomerid.php 



<?php
    
    $path = __DIR__ . '/../';
    
    while (!file_exists($path. '/vendor/autoload.php') && $i++ < 15) {
        $path .= '../';
    }
    require ($path. '/vendor/autoload.php');
    
    $path = __DIR__ . '/../';
    $zendLibrary = 'vendor/zendframework/zend-http/src/';
    $i = 0;
    
    while (!file_exists($path. $zendLibrary . 'Headers.php') && $i++ < 15) {
        $path .= '../';
    }
    
    require_once $zendLibrary . 'Headers.php';
    require_once $zendLibrary . 'Request.php';
    require_once $zendLibrary . 'Response.php';
    
    
    error_reporting(E_ALL);
    ini_set('display_errors', 1);
    
    // \Magento\Webapi\Model\ServiceMetadata::getServicesConfig to debug the available webapi services
    $params = ['customer_id' => null];
    foreach ($argv as $arg) {
        if (preg_match("%^--(.*?)=(.*?)$%", $arg, $m)) {
            $params[$m[1]] = $m[2];
        }
    }
    
    if (!$params['customer_id'])
        exit("Specify customer id (as --customer_id=_ID_ parameter)\n");
    
    $customer_id = $params['customer_id'];
    
    $token = 'or7ozb3e97x19nk97zylmhspul7niqi3';
    $httpHeaders = new \Zend\Http\Headers();
    $httpHeaders->addHeaders([
        'Authorization' => 'Bearer ' . $token,
        'Accept' => 'application/json',
        'Content-Type' => 'application/json'
    ]);
    
    $request = new \Zend\Http\Request();
    $request->setHeaders($httpHeaders);
    $request->setUri('http://magecertif.test/index.php/rest/V1/orders');
    $request->setMethod(\Zend\Http\Request::METHOD_GET);
    
    //searchCriteria[filterGroups][0][filters][0][field]=created_at&searchCriteria[filterGroups][0][filters][0][value]=2020-06-28&searchCriteria[filterGroups][0][filters][0][conditionType]=gt&searchCriteria[filterGroups][1][filters][0][field]=created_at&searchCriteria[filterGroups][1][filters][0][value]=2020-06-29&searchCriteria[filterGroups][1][filters][0][conditionType]=lt
    
    $params = new \Zend\Stdlib\Parameters([
        'searchCriteria' => [
            'filterGroups' => [
                0 => [
                    'filters' => [
                        0 => [
                            'field' => 'customer_id',
                            'value' => $customer_id,
                            'condition_type' => 'eq'
                        ]
                    ]
                ]
            ],
            'current_page' => 1,
            'page_size' => 10
        ],
    ]);
    
    $request->setQuery($params);
    
    $client = new \Zend\Http\Client();
    $options = [
        'adapter'   => 'Zend\Http\Client\Adapter\Curl',
        'curloptions' => [CURLOPT_FOLLOWLOCATION => true],
        'maxredirects' => 0,
        'timeout' => 30
    ];
    
    $client->setOptions($options);
    
    $response = $client->send($request);
    
    echo $response->getBody();

to call this script: open a terminal and at the root of your magento install, hit php <script_location>/getlistordersbycustomerid.php --customer_id=1

on my environment: php app/code/Mbs/OrderRepositoryExtension/shell/getlistordersbycustomerid.php --customer_id=1

4
  • @ Herve Tribouilloy plz suggest name file saved in my root folder
    – Gagan
    Jul 2, 2020 at 11:31
  • please share rest api url for get customer order details from customer id
    – Gagan
    Jul 2, 2020 at 12:00
  • please share api url to get order details from customer id
    – Gagan
    Jul 2, 2020 at 12:01
  • answer is updated Jul 2, 2020 at 12:08
1

You can try with the below code. You need to pass customer id in API

Below are the module details with file.

Step-1: Create registration file Pushpendra/CustomerOrder/registration.php

<?php
    \Magento\Framework\Component\ComponentRegistrar::register(
        \Magento\Framework\Component\ComponentRegistrar::MODULE,
        'Pushpendra_CustomerOrder',
        __DIR__
    );

Step-2: Create a module file Pushpendra/CustomerOrder/etc/module.xml

<?xml version="1.0"?>
    <config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:Module/etc/module.xsd">
        <module name="Pushpendra_CustomerOrder" setup_version="1.0.0" />
    </config>

Step-3: Create a webapi.xml file like below path Pushpendra/CustomerOrder/etc/webapi.xml

<?xml version="1.0"?>
<routes xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:module:Magento_Webapi:etc/webapi.xsd">
    <route url="/V1/customer/order/:id" method="GET">
        <service class="Pushpendra\CustomerOrder\Api\CustomerOrderInterface" method="getList"/>
        <resources>
            <resource ref="self"/>
        </resources>
    </route>
</routes>

Step-4: Create a file for API Pushpendra/CustomerOrder/Api/CustomerOrderInterface.php

<?php
namespace  Pushpendra\CustomerOrder\Api;


interface CustomerOrderInterface
{
    /**
     * Returns orders data to user
     *
     * @api
     * @param  string $id customer id.
     * @return return order array collection.
     */
    public function getList($id);
}

Step-5: Create a file CustomerOrder.php like below path Pushpendra/CustomerOrder/Model/CustomerOrder.php

<?php
    namespace  Pushpendra\CustomerOrder\Model;    
    
    
    use Pushpendra\CustomerOrder\Api\CustomerOrderInterface;
    use Magento\Sales\Model\Order;
    
    class CustomerOrder implements CustomerOrderInterface
    {
        private $order;
        /**
         * CustomerOrder constructor.
         *
         * @param Order $order
         */
        public function __construct(
            Order $order
        ) {
            $this->order = $order;
        }
    
        /**
         * Returns orders data to user
         *
         * @api
         * @param  string $id customer id.
         * @return return order array collection.
         */
        public function getList($id)
        {
            $order = $this->order->getCollection()->addAttributeToFilter('customer_id', $id);
            $data=[];
            $i=0;
            foreach ($order as $orderDetails) {
                $data[$i]['increment_id']=$orderDetails->getIncrementId();
                $data[$i]['created_at']=$orderDetails->getCreatedAt();
                $data[$i]['ship_to']=$this->getShipTo($orderDetails->getId());
                $data[$i]['grand_total']=$orderDetails->getGrandTotal();
                $data[$i]['status']=$orderDetails->getStatus();
                $data[$i]['id']=$orderDetails->getId();
                $i++;
            }
            return $data;
        }
    
       
    }

You need to call API by below example magentourl/V1/customer/order/customerId

8
  • please share proper module creation steps. I am beginner in Magento 2
    – Gagan
    Jul 2, 2020 at 12:04
  • @Gagan, Check updated answer Jul 2, 2020 at 12:18
  • thanks for help. I follow all steps of module but show error when hit url 127.0.0.1/jodhpur/rest/V1/customer/order/723 Response show html code - Fatal error: Uncaught Error: Cannot instantiate interface Vendor\Module\CustomerOrder\Api\CustomerOrderInterface in C:\wamp64\www\jodhpur\vendor\magento\framework\ObjectManager\Factory\Dynamic\Developer.php on line 50
    – Gagan
    Jul 2, 2020 at 13:34
  • It was working. Let me check it again Jul 2, 2020 at 17:06
  • Yes please check again. If possible please share screenshot
    – Gagan
    Jul 2, 2020 at 17:10

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.