0

I am trying to get the customer's name by POST Method API if it's logged in but when I hit the link the postman, returns the Customer's Name even if it's not logged in. Please take a look

CODE:

<?php 
namespace Vendor\Login\Model\Customer;

use Magento\Authorization\Model\UserContextInterface;
use Magento\Customer\Api\AccountManagementInterface;
use Magento\Customer\Block\Account\AuthorizationLink;
use Magento\Customer\Model\Session;
use Magento\Customer\Model\Url;
use Magento\Framework\App\Action\Context;
use Magento\Framework\Controller\Result\JsonFactory;
use Magento\Framework\Exception\AuthenticationException;
use Magento\Framework\Exception\LocalizedException;

//use Vendor\Login\Controller\Index\ApiController;

/**
 * Implementing the logic
 */
class Extra
{
    protected AuthorizationLink $ath;
    protected UserContextInterface $userContext;
    /**
     * @var Session
     */
    protected Session $customerSession;
    /**
     * @var AccountManagementInterface
     */
    protected AccountManagementInterface $customerAccountManagement;
    /**
     * @var Url
     */
    protected Url $customerUrl;
    protected JsonFactory $jsonFactory;

    /**
     * @param Context $context
     * @param Url $customerUrl
     * @param AccountManagementInterface $customerAccountManagement
     * @param Session $customerSession
     * @param JsonFactory $jsonFactory
     * @param UserContextInterface $userContext
     * @param AuthorizationLink $ath
     */
    public function __construct(
        Context $context,
        Url $customerUrl,
        AccountManagementInterface $customerAccountManagement,
        Session $customerSession,
        JsonFactory $jsonFactory,
        UserContextInterface $userContext,
        AuthorizationLink $ath

    ) {
        parent::__construct($context);
        $this->customerUrl = $customerUrl;
        $this->customerAccountManagement = $customerAccountManagement;
        $this->customerSession = $customerSession;
        $this->jsonFactory = $jsonFactory;
        $this->userContext = $userContext;
        $this->ath = $ath;

    }

    /**
     * @param string $email
     * @param string $password
     * @return array[]
     * @throws LocalizedException
     */
    public function login(string $email, string $password): array
    {
        $validate = array();
        $login = array();
        $result = $this->jsonFactory->create();
        $customerinfo = array();

        if ($email) {
            $login['username'] = $email;
        }
        if ($password) {
            $login['password'] = $password;
        }

        try {

            if (($email == null) || ($password == null)) {
                $message = __('Invalid Username');

                return array($message);
            } 

            else {


                $customer = $this->customerAccountManagement->authenticate($email, $password);

                $this->customerSession->setCustomerDataAsLoggedIn($customer);

                $this->customerSession->regenerateId();

                if (!$this->ath->isLoggedIn()) {
                    $customer_data = $this->customerSession->getCustomer()->getData();

                    $customerinfo = array(
                        "name" => $customer_data['firstname'] . $customer_data['lastname']
                    );

                    return array($customerinfo);

                }
                else {

                    $error = __('Error');
                    return array($error);
                }
            }

        } 
        catch (AuthenticationException $e) {
            $new = __('You are not logged in');
            return array($new);
        }
    }

}

2 Answers 2

0

You can use it like this. This code will return customer tokens if logged in so hopefully, this will help a lot.

<?php

$userDataArr = ["username" => "[email protected]", "password" => "654321"];
$ch = curl_init("http://example.com/rest/V1/integration/customer/token");
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($userDataArr));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, array("Content-Type: application/json", "Content-Lenght: " . strlen(json_encode($userDataArr))));

$token = curl_exec($ch);

//Get customer info
$ch = curl_init("http://example.com/rest/V1/customers/me");
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "GET"); // Get method
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, array("Content-Type: application/json", "Authorization: Bearer " . json_decode($token)));

$result = curl_exec($ch);

$result = json_decode($result, 1);
echo '<pre>';print_r($result);
11
  • Where to put this code? with above one or replace the above code with yours one? Commented Aug 5, 2022 at 6:10
  • I just give you an example to understand the logic of this code. I do not know what you wrote inside your file because we have to put some dependencies inside the constructor etc... if you were not able to get my point then send me the file name full of code.
    – Dotsquares
    Commented Aug 5, 2022 at 6:13
  • Can you please just tell me how to get customers logged in session in API, Any Library? Commented Aug 5, 2022 at 6:23
  • The code I wrote above that will help you to get a customer token in API if the customer is logged in. Either you can create another function and create the above API and return the customer token. But it would be better then you can share the file code, I want to see what functions and dependencies you have passed inside.
    – Dotsquares
    Commented Aug 5, 2022 at 6:34
  • Please update your question with the full path code. Open that file press Ctrl+A and replace it with the above code.
    – Dotsquares
    Commented Aug 5, 2022 at 6:35
0

First of all you need to create a new POST request in POSTMAN

Using below url

http://localhost/magento2/rest/V1/integration/customer/token?username=customer_email_id&password=customer_password

Change customer_email_id in url with the customer's email you want to get the name

And Change customer_password in url with the customer's password and also change http://localhost/magento2 with your project url

It will return a token, you need to copy that token

NEXT STEP

Now open your custom request where you are getting customer name

Go to Authorization Tab and choose Bearer Token

Now copy the token generated in previous request and page in Bearer Token in your request

It will verify the customer token and print your output

Hope it will work for you!

Please let me know if you get any issue.

12
  • I followed your steps but it returned the customer name I checked Magento frontend and the customer is not logged in. Same Issue Commented Aug 5, 2022 at 6:51
  • Can you please elaborate more? Commented Aug 5, 2022 at 6:56
  • So first I got the token and then added the auth bearer token in my custom request, it returned the customer name in output but the customer was not logged in Magento 2. I want to get the customer's name when I logged in. That's it Commented Aug 5, 2022 at 7:01
  • In your webapi.xml file update <resource ref="anonymous"/> from anonymous to self. <resource ref="self"/> Then follow the above step Commented Aug 5, 2022 at 7:16
  • I followed the same steps after replacing "anonymous" with "self", But still the same issue. it returned the customer name but customer is logged out Commented Aug 5, 2022 at 7:30

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.