Magento 2 How to generate customer token and use in customer query using GraphQL

When using all customer related data or others, we need to generate customer token, so in this article, we will show you how to generate customer token and how to retrieve information using this token for login customer.

Generate customer token

Use generateCustomerToken mutation to create a new customer token. Magento recommends use customer tokens in the header of GraphQL.

Syntax

mutation {
  generateCustomerToken(
    email: String!
    password: String!
  ) {
    CustomerToken
  }
}

Create new customer token in the following example.

Request

saveCopyzoom_out_map
mutation { generateCustomerToken( email: "roni_cost@example.com" password: "roni_cost3@example.com" ) { token } }

Response

saveCopyzoom_out_map
{ "data": { "generateCustomerToken": { "token": "c53jtlkkac4l0bakwz9js2837ie4nvcg" } } }

Now, we will show you how to get login customer information using this token.

First of all, you need to add the token in the header GraphQL. Add token (token) in the header key and add token value (c53jtlkkac4l0bakwz9js2837ie4nvcg) in the header value.

After, you need to use the following customer query in your GraphQL.

Syntax

{customer: {Customer}}

Retrieving the logged-in customer

Request

saveCopyzoom_out_map
{ customer { firstname middlename lastname suffix email addresses { firstname middlename lastname street city region { region_code region } postcode country_code telephone } } }

Response

saveCopyzoom_out_map
{ "data": { "customer": { "firstname": "Veronica", "middlename": null, "lastname": "Costello", "suffix": null, "email": "roni_cost@example.com", "addresses": [ { "firstname": "Veronica", "middlename": null, "lastname": "Costello", "street": [ "6146 Honey Bluff Parkway" ], "city": "Calder", "region": { "region_code": "MI", "region": "Michigan" }, "postcode": "49628-7978", "country_code": "US", "telephone": "(555) 229-3326" } ] } } }

Retrieve the customer’s wish list

The below query returns customer's wishlist.

Request

saveCopyzoom_out_map
{ customer { wishlist { items { id description qty product { sku name price_range { maximum_price { regular_price { value } } } } } } } }

Response

saveCopyzoom_out_map
{ "data": { "customer": { "wishlist": { "items": [ { "id": 1, "description": null, "qty": 1, "product": { "sku": "24-MB02", "name": "Fusion Backpack", "price_range": { "maximum_price": { "regular_price": { "value": 59 } } } } } ] } } } }

That's it!!

If you are looking for more GraphQL solutions then check out our another article which is List of GraphQL Queries and Mutations for Magento 2.

I hope this article helps you to find what you were looking for.

Bookmark it for your future reference. Do comment below if you have any other questions on that.

P.S. Do share this article with your team.




Recent Articles
Tags
Newsletter
Chrome Extension
Copyright © 2024 devhooks.in All rights reserved.
Ads OFF toggle_off
wifi_off