How to get orders list by customer id in graphql magento 2?

From Magento 2.4 Out of the box, Magento supports Customer Orders History using GraphQL.

You can check the syntax by clicking Retrieve all the Order list of a customer by GraphQL Query

Given Article is used for the learning of GraphQL Practice with Magento. I have written an article before Magento supports the Sales GraphQL feature in the core code.

How to get a list of orders of a customer using GraphQl Magento 2?

We need to create a simple module for getting all the order lists of Customer using GraphQl. Default Magento 2, We can easily get all the orders of a customer by fetch OrderRepository.

Using Graphql, You can get an order list of a specific registered customer by customer id.

We need to create a Resolver model and add our custom logic for getting all the Customer Order list. We will display all the orders of a customer in the response to the query.

I hope you are aware of What is GraphQl and how GraphQL is used in Magento 2 If You are new to GraphQL check the link for GraphQl in Magento 2.

Now we can start the module using Magento 2 to fetch all orders of a specific customer.

You need to create the first registration.php and module.xml file for defining our module. I have taken the Package name as Rbj and the Module name as CustomerOrder.

Path: app/code/Rbj/CustomerOrder/registration.php

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

Create the module.xml file, Path: app/code/Rbj/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="Rbj_CustomerOrder">
        <sequence>
            <module name="Magento_Sales"/>
            <module name="Magento_GraphQl"/>
        </sequence>
    </module>
</config>

Our Module depends on GraphQL and Sales Module so we have given the dependency on module.xml file for each module.

Every GraphQl Module must contain schema.graphqls file under the etc folder of a module.

schema.graphqls is the heart of any GraphQL Query implementation and describes what data can be queried. So You can define your query data basic skeleton under the schema.graphqls file.

Customer Order Graphql Schema file,
Path: app/code/Rbj/CustomerOrder/etc/schema.graphqls

type Query {
    customerPlacedOrder (
        customer_id: Int @doc(description: "Id of the Customer for fetch all the placed order")
    ): SalesOrderCollection @resolver(class: "Rbj\\CustomerOrder\\Model\\Resolver\\CustomerOrder") @doc(description: "The Sales Order query returns information about customer all placed order")
}

type SalesOrderCollection @doc(description: "Sales order item information") {
    allOrderRecords: [OrderRecord] @doc(description: "An array containing the all the CMS Page from Magento")
}

type OrderRecord @doc(description: "Sales Order graphql gather Data of specific order information") {
    increment_id: String @doc(description: "Increment Id of Sales Order")
    customer_name: String @doc(description: "Customername of Sales Order")
    grand_total: String @doc(description: "Grand total of Sales Order")
    created_at: String @doc(description: "Timestamp indicating when the order was placed")
    shipping_method: String @doc(description: "Shipping method for order placed")
}

In the Schema file, We have passed customer_id for getting customer id as input. In SalesOrderCollection type for getting all the records as an array,

We have created an array for [OrderRecord]. In the type OrderRecord, we have to display all the field which we required in the response of query. You can add an extra field also here in the above schema.

Now Create a Resolver Model for our custom module.
Rbj\\CustomerOrder\\Model\\Resolver\\CustomerOrder
CustomerOrder Model class which is defined in the schema.graphqls file at above. In this Model, the resolve() method will simply return data of all the Orders of the specific customer.

Path: app/code/Rbj/CustomerOrder/Model/Resolver/CustomerOrder.php

<?php
declare(strict_types=1);

namespace Rbj\CustomerOrder\Model\Resolver;

use Magento\Framework\Exception\NoSuchEntityException;
use Magento\Framework\GraphQl\Config\Element\Field;
use Magento\Framework\GraphQl\Exception\GraphQlInputException;
use Magento\Framework\GraphQl\Exception\GraphQlNoSuchEntityException;
use Magento\Framework\GraphQl\Query\ResolverInterface;
use Magento\Framework\GraphQl\Schema\Type\ResolveInfo;

/**
 * Order sales field resolver, used for GraphQL request processing
 */
class CustomerOrder implements ResolverInterface
{
    public function __construct(
        \Magento\Sales\Api\OrderRepositoryInterface $orderRepository,
        \Magento\Framework\Api\SearchCriteriaBuilder $searchCriteriaBuilder,
        \Magento\Framework\Pricing\PriceCurrencyInterface $priceCurrency,
        \Magento\Directory\Model\Currency $currencyFormat
    ) {
        $this->orderRepository = $orderRepository;
        $this->searchCriteriaBuilder = $searchCriteriaBuilder;
        $this->priceCurrency = $priceCurrency;
        $this->currencyFormat =$currencyFormat;
    }

    /**
     * Get current store currency symbol with price
     * $price price value
     * true includeContainer
     * Precision value 2
     */
    public function getCurrencyFormat($price)
    {
        return $this->getCurrencySymbol() . number_format((float)$price, \Magento\Framework\Pricing\PriceCurrencyInterface::DEFAULT_PRECISION);
    }

    /**
     * Get current store CurrencySymbol
     */
    public function getCurrencySymbol()
    {
        $symbol = $this->priceCurrency->getCurrencySymbol();
        return $symbol;
    }

    /**
     * @inheritdoc
     */
    public function resolve(
        Field $field,
        $context,
        ResolveInfo $info,
        array $value = null,
        array $args = null
    ) {
        $customerId = $this->getCustomerId($args);
        $salesData = $this->getSalesData($customerId);

        return $salesData;
    }

    /**
     * @param array $args
     * @return int
     * @throws GraphQlInputException
     */
    private function getCustomerId(array $args): int
    {
        if (!isset($args['customer_id'])) {
            throw new GraphQlInputException(__('"Customer id must be specified'));
        }

        return (int)$args['customer_id'];
    }

    /**
     * @param int $customerId
     * @return array
     * @throws GraphQlNoSuchEntityException
     */
    private function getSalesData(int $customerId): array
    {
        try {
            /* filter for all customer orders */
            $searchCriteria = $this->searchCriteriaBuilder->addFilter('customer_id', $customerId,'eq')->create();
            $orders = $this->orderRepository->getList($searchCriteria);

            $salesOrder = [];
            foreach($orders as $order) {
                $orderId = $order->getId();
                $salesOrder['allOrderRecords'][$orderId]['increment_id'] = $order->getIncrementId();
                $salesOrder['allOrderRecords'][$orderId]['customer_name'] = $order->getCustomerFirstname().' '.$order->getCustomerLastname();
                $salesOrder['allOrderRecords'][$orderId]['grand_total'] = $this->getCurrencyFormat($order->getGrandTotal());
                $salesOrder['allOrderRecords'][$orderId]['created_at'] = $order->getCreatedAt();
                $salesOrder['allOrderRecords'][$orderId]['shipping_method'] = $order->getShippingMethod();
            }
        } catch (NoSuchEntityException $e) {
            throw new GraphQlNoSuchEntityException(__($e->getMessage()), $e);
        }
        return $salesOrder;
    }
}

We have set logic for getting all the orders from OrderRepositoryInterface. You need to set logic in the above file for display response.

Now Run the Upgrade command to install our module.

php bin/magento setup:upgrade
php bin/magento cache:flush

You can check your GraphQL query response by installing chrome extension ChromeiQL or Altair GraphQL addon.

order list of Customer GraphQL
order list of Customer GraphQL

In Request Body, You need to pass the required data(field) to request payload for getting a response of Products,

Request Payload,

{
  customerPlacedOrder (customer_id: 1) {
    allOrderRecords{
      increment_id
      customer_name
      grand_total
      created_at
      shipping_method
    }
  }
}

We have passed customer id as 1 for getting all the order of a customer with id 1.

Result: The result will be all Customer Order list which ID is equal or greater than 1,

{
  "data": {
    "customerPlacedOrder": {
      "allOrderRecords": [
        {
          "increment_id": "000000001",
          "customer_name": "Rakesh Jesadiya",
          "grand_total": "$525.00",
          "created_at": "2018-10-12 09:51:18",
          "shipping_method": "flatrate_flatrate"
        },
        {
          "increment_id": "000000002",
          "customer_name": "Rakesh Jesadiya",
          "grand_total": "$723.00",
          "created_at": "2018-10-14 13:42:23",
          "shipping_method": "flatrate_flatrate"
        },
        {
          "increment_id": "000000003",
          "customer_name": "Rakesh Jesadiya",
          "grand_total": "$363.00",
          "created_at": "2018-11-23 11:42:54",
          "shipping_method": "flatrate_flatrate"
        },
        {
          "increment_id": "000000004",
          "customer_name": "Rakesh Jesadiya",
          "grand_total": "$204.50",
          "created_at": "2018-11-23 11:43:59",
          "shipping_method": "flatrate_flatrate"
        }
      ]
    }
  }
}