How To

Magento 2: How to Get Login Customer Data in GraphQL Resolver File

Hello Magento Friends,

Today we will learn about Magento 2: How to Get Login Customer Data in GraphQL Resolver File.

As we all know Magento 2 provides GraphQL functionalities and with the help of that our Magento database can be used by some third-party service just by API call. In Magento 2 we can directly call built-in APIs as well as we can create custom API calls as per our need and to access this APIs call, the caller needs to authenticate some APIs before API call and for that, we need some customer information for authentications.

So with the help of this blog, we are going to understand How to Get Login Customer Data in GraphQL Resolver File in our custom API call.

Let’s Do,

Steps to Get Login Customer Data in GraphQL Resolver File in Magento 2:

Step 1: First of all you need to create schema.graphqls in the below path

app\code\Vendor\Extension\etc\ 

And add below code

type Query
{
    getCustomerData: Response 
    @resolver(class:"Vendor\\Extension\\Model\\Resolver\\Getcustomerdata")
}

type Response
{
    cust_id: String
    cust_name: String
}

Step 2: Next, you need to create Getcustomerdata.php in the following path

app\code\Vendor\Extension\Model\Resolver\

And add below code

<?php
namespace Vendor\Extension\Model\Resolver;

use Magento\Framework\GraphQl\Query\ResolverInterface;
use Magento\Framework\GraphQl\Config\Element\Field;
use Magento\Framework\GraphQl\Schema\Type\ResolveInfo;
use Magento\Framework\GraphQl\Exception\GraphQlNoSuchEntityException;
use Magento\Framework\GraphQl\Exception\GraphQlAuthorizationException;
use Magento\CustomerGraphQl\Model\Customer\GetCustomer;

class Getcustomerdata implements ResolverInterface
{
   private $getCustomer;
     
   public function __construct(GetCustomer $getCustomer)
   {
      $this->getCustomer = $getCustomer;
   }
   public function resolve(Field $field, $context, ResolveInfo $info, array $value = null, array $args = null)
   {
      try
      {
         if (false === $context->getExtensionAttributes()->getIsCustomer())
         {
            throw new GraphQlAuthorizationException(__('The current customer isn\'t authorized.try agin with authorization token'));
         }
         $customer = $this->getCustomer->execute($context);
         $cname = $customer->getFirstName().” “.$customer->getLastName();
         $result = ['cust_id' => $customer->getId(),
                    'cust_name' => $cname
                   ]; 
         return $result;
      }
      catch(\Exception $exception)
      {
          throw new GraphQlNoSuchEntityException(__($exception->getMessage()));
      }
   }
}

Step 3: Finally Clear Cache and Remove generated folder using the below commands.

php bin/magento c:f
rm -rf generated

Output:

Once you have performed the above steps successfully, you can get the customer data as follows,

{
  "data": {
    "cust_id": "3",
    "cust_name": "Mage Tester"
  }
}

Conclusion:

This way you can Get Login Customer Data in GraphQL Resolver File in Magento 2. In case of any trouble with the above code, mention it in the comment box. Make sure to spread the article within your friend circle and social media handles.

Happy Coding!

Click to rate this post!
[Total: 8 Average: 4]
Dhiren Vasoya

Dhiren Vasoya is a Director and Co-founder at MageComp, Passionate 🎖️ Certified Magento Developer👨‍💻. He has more than 9 years of experience in Magento Development and completed 850+ projects to solve the most important E-commerce challenges. He is fond❤️ of coding and if he is not busy developing then you can find him at the cricket ground, hitting boundaries.🏏

View Comments

Recent Posts

How to Integrate ChatGPT with Laravel Application?

In this guide, we'll explore how to integrate ChatGPT, an AI-powered chatbot, with a Laravel…

3 days ago

What are Net Sales? How to Calculate Your Net Sales?

In the world of business, understanding financial metrics is crucial for making informed decisions and…

5 days ago

Magento 2 Extensions Digest April 2024 (New Release & Updates)

Welcome to the MageComp Monthly Digest, where we bring you the latest updates, releases, and…

5 days ago

The ABCs of Geofencing: Definition, Features and Uses

In this era, businesses are always on the lookout for ways to engage with their…

6 days ago

How to Delete Product Variant in a Shopify Remix App using GraphQL Mutations?

Managing a Shopify store efficiently involves keeping your product catalog organized. This includes removing outdated…

7 days ago

6 Innovative Tools Revolutionizing E-Commerce Operations

E-commerce has transformed the way consumers shop for products and services and interact with businesses.…

1 week ago