Site icon MageComp Blog

How to Get Customer Order History using REST API in Magento 2

How to Get Customer Order History using REST API in Magento 2

Hello Magento Friends,

Today I am here with the solution for How to Get Customer Order History using REST API in Magento 2.

Magento handles many entities like products, customers, orders and more. There are different ways to get this entity data. Check the below links to get entity data using REST API.

When you want data of customer order history using REST API, use the below steps.

Steps to Get Customer Order History using REST API in Magento 2:

Step 1: Create the getOrderHistory.php script file inside your Magento root folder and add the below code

<?php
$userData = array("username" => "admin", "password" => "adminPassword");
$baseUrl = "http://127.0.0.1/magento24/"; // your magento base url
$ch = curl_init($baseUrl."/rest/V1/integration/admin/token");
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($userData));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, array("Content-Type: application/json", "Content-Lenght: " . strlen(json_encode($userData))));

$token = curl_exec($ch);

$ch = curl_init($baseUrl."/rest/V1/orders?searchCriteria[filterGroups][0][filters][0][field]=customer_id&searchCriteria[filterGroups][0][filters][0][value]=your customer id&searchCriteria[filterGroups][0][filters][0][conditionType]=eq");
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "GET");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, array("Content-Type: application/json", "Authorization: Bearer " . json_decode($token)));

$result = curl_exec($ch);

$result = json_decode($result, 1);
echo '<pre>';
print_r($result);
echo '</pre>';
?>

Note – You can use this code wherever you want in your Magento file system. E.g: You can also use it in your custom module.

Conclusion:

This way you can Get Customer Order History using REST API in Magento 2. If you address any complications, just leave a comment here. Share the article with your other developer friends and remain in touch with us!

Happy Coding!

Exit mobile version