Question

I need customer ID in Model class as I am creating custom API.

I can get customer ID in Controller as well as in Block class by all below ways:

Injecting in constructor

\Magento\Customer\Model\Session $session

and using as

public function getCustomerId()
    {
        return $this->_session->getCustomer()->getId();
    }

Also by Object manager:

$objectManager = \Magento\Framework\App\ObjectManager::getInstance();

        $customerSession = $objectManager->create("Magento\Customer\Model\Session");

        if($customerSession->isLoggedIn()){
        echo $customerSession->getCustomerId();
        }

Also I tried using this class:

\Magento\Customer\Helper\Session\CurrentCustomer $currentCustomer,

It gives output in controller and block but no output in Model. The problem is all above code works fine in Controller and block but when I use in Model class it did not show any result. Model class is working fine for other features and I debugged using die() exit; it works. Cache is also disabled.

Edit: I think I need to do something like this to access logged in customer ID

<route url="/V1/customers/updateProfileDetails" method="PUT">
        <service class="Vendor\Module\Api\CustomerRegInterface" method="updateProfileDetails"/>
        <resources>
            <resource ref="self"/>
        </resources>
          <data>
            <parameter name="customerId" force="true">%customer_id%</parameter>
        </data>
    </route>

Still looking how to do it

Was it helpful?

Solution

You will get customerId as first argument of updateProfileDetails function in your repository (CustomerRegInterface), Just follow below code.

CustomerRegInterface.php

<?php
namespace Vendor\Module\Api;

class CustomerRegInterface {

/**
 * Update Profile Details
 *
 * @param int $customerId
 * @return bool  (whatever return type you have)
 */
public function updateProfileDetails($customerId);

}

Let me know if any other help needed. Happy coding :)

OTHER TIPS

There is only 1 good approach is that we define a customer id in your API declaration which Ramkishan already suggested.

The reason we need that customer id is that on the controller and block, we're active in the store and we can access the current customer session, but for the API, we can't access to the customer session.

Licensed under: CC-BY-SA with attribution
Not affiliated with magento.stackexchange
scroll top