Retrieve customers who have ordered a specific product

Use case: I want to retrieve customers who have ordered a specific product using the Shopify GraphQL API. I’m currently working with Lucee to make this query, but I’m not getting any results

<cfset accessToken = "#token#">
<cfset shopName = "#shop#">
<cfset apiUrl = "https://" & shopName & ".myshopify.com/admin/api/2024-10/graphql.json">
<cfset productId = "8926452449608">

<cfset graphqlQuery = '{"query": "query { orders(first: 250, query: \"line_items.product_id: ' & productId & '\") { edges { node { id customer { id firstName lastName email } } } } }"}'>

<cfhttp url="#apiUrl#" method="POST" result="response">
    <cfhttpparam type="header" name="Content-Type" value="application/json">
    <cfhttpparam type="header" name="X-Shopify-Access-Token" value="#accessToken#">
    <cfhttpparam type="body" value="#graphqlQuery#">
</cfhttp>

<cfset responseData = DeserializeJSON(response.fileContent)>
<cfdump var="#responseData#">

Can someone assist me with this? Is it even possible? I’m not receiving an error, just an empty array. I’m using a product where purchases are made.

Hi Samall,

I’ve tested out the query below with the GraphiQL app on my test store and it returns a list of customers who have made orders that contain a product with id 8449274904890 - can you try the same but with your product ID?

query GetCustomersByProduct {
  orders(first: 10, query: "line_items.product_id:8449274904890") {
    edges {
      node {
        customer {
          id
          firstName
          lastName
          email
        }
      }
    }
  }
}

Hi Liam,

Thanks for your reply. I also tested your query before, but it is not working. You can reproduce by editing your product_id to a non existing ID. Also notice that the output has warnings:

“warnings”: [
{
“field”: “line_items.product_id”,
“message”: “Invalid search field for this query.”
}
]

query GetCustomersByProduct {
  orders(first: 10, query: "sku: yourProductSku") {
    edges {
      node {
        customer {
          id
          firstName
          lastName
          email
        }
      }
    }
  }
}

Thanks, but no results

<cfset query = '{
  "query": "query GetCustomersByProduct {orders(first: 10, query: \"sku: TEST123\") { edges {node {customer {id firstName lastName email} } } } }"
}'>

I’ve given some more thought for adding the SKU. I expect that adding a SKU afterward won’t work for existing orders. Therefore, I created a new product with a SKU. When I place an order for this product, I can see my order, including the SKU, in the order overview (admin panel). However, I’m not getting any output from the API, empty array.

{
  "data": {
    "orders": {
      "edges": []
    }
  }

BTW my Admin API access scopes is:

In my side ,this GraphQL works, have you ever used your testting tool to test it such as postman ?