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!