2

I'm building rest api to get data based on customer session, but it always returns false when I call isLoggedIn() function

that's my module.xml:

<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:Module/etc/module.xsd">

<module name="Bit68_Cart" setup_version="2.1.15"/>

</config>

that's webapi.xml:

<?xml version="1.0"?>

<routes xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:module:Magento_Webapi:etc/webapi.xsd">

<route url="/V1/cart/items" method="GET">
    <service class="\Bit68\Cart\Api\Cart\MyCartInterface" method="getItems"/>
    <resources>
        <resource ref="self"/>
    </resources>
</route>

</routes>

that's my interface:

<?php

namespace Bit68\Cart\Api\Cart;

interface MyCartInterface{

/**
* @api
* @param int $id
* @return bool
*/

public function getItems();

}

?>

and that's my class:

<?php

namespace Bit68\Cart\Model\Cart;
use Bit68\Cart\Api\Cart\MyCartInterface;
use \Magento\Checkout\Model\Cart\CartInterface;
use \Magento\Customer\Model\Session;

class MyCart implements MyCartInterface{
/**
* @var Magento\Checkout\Model\Cart\CartInterface
*/
private $cartObj;

/**
* @var Magento\Customer\Model\Session
*/
private $customerSession;

/**
* @param \Magento\Customer\Model\Session $customerSession
* @param \Magento\Checkout\Model\Cart $cartObj
*/

public function __construct(\Magento\Checkout\Model\Cart $cartObj,
\Magento\Customer\Model\Session $customerSession){
    $this->cartObj = $cartObj;
    $this->customerSession = $customerSession;
}

/**
* @api
* @return bool
*/

public function getItems(){

    $customerId = $this->customerSession->isLoggedIn();

    return $customerId;
}
}

?>

and that's where I call My api:

<?php

session_start();

$host = 'http://domain.com/';


if (!isset($_SESSION['access_token'])) {
echo 'Authenticating...<br>';
/*
* authentication details of the customer
*/
$username = 'customer_email';
$password = 'password';
$postData['username'] = $username;
$postData['password'] = $password;

/*
* init curl
*/
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $host.'rest/V1/integration/customer/token');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
/*
* set content type and length
*/
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
       'Content-Type: application/json',
       'Content-Length: '.strlen(json_encode($postData)),
   )
);
/*
* setpost data
*/
curl_setopt($ch, CURLOPT_POST, count($postData));
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($postData));
$output = curl_exec($ch);
curl_close($ch);
/*
* access token in json format
*/
echo $output;
$_SESSION['access_token'] = $output;
}
if (isset($_SESSION['access_token'])) {
   /*
   * create headers for authorization
   */
   $headers = array(
       'Authorization: Bearer '.json_decode($_SESSION['access_token']),
   );
   echo '<pre>';
   echo 'api call... with key: '.$_SESSION['access_token'].'<br><br><br>';
   $ch = curl_init();
   /*
   * set api resource url
   */
   $get_params = http_build_query($j);
   curl_setopt($ch, CURLOPT_URL, $host.'rest/V1/cart/items');
   curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
   curl_setopt($ch, CURLOPT_HTTPHEADER, $headers
);
   $output = curl_exec($ch);

   curl_close($ch);
   echo '<br>';
   echo gettype($output);
   echo '<br>';
   echo $output;
   echo '<br>';
   echo "Today is " . date("Y-m-d") . "<br>";
   /*
    * json response need to rtrim with [], some times it is appended to the respose so the json becomes invalid so need to rtrim the response
   */
   $test = json_decode(rtrim($output, '[]'));
   echo '
   =========================RESPONSE================================<br>
   ';

   print_r($test);
  // echo($test->item_id);
  }
 exit(0);


 ?>
3

To get customerId during api call you need to follow below code.

public function __construct(
 -----
 \Magento\Authorization\Model\UserContextInterface $userContext
 -----
){
$this->userContext = $userContext;
}

public function getItems()
{  
 $customerId = $this->userContext->getUserId();
}

\Magento\Customer\Model\Session class only used when customer logged in from web interface or storefront. Let me know if you need more help on this.

  • Was my answer helpful for you @Yomna ? if yes then please accept it. – Ramkishan Suthar Nov 15 '18 at 3:41
  • That's working, but what if I need customer session during api, like for example I'm building the Api for mobile app and I need to get cart items for every logged in customer. will \Magento\Customer\Model\Session class help me? – Yomna Mansour Nov 15 '18 at 9:15
  • 1
    No you can't use Magento\Customer\Model\Session class during api call. Meanwhile can you please give upvote as well :) – Ramkishan Suthar Nov 15 '18 at 9:21
  • 1
    Let me give you answer, I think you have already ask this question. – Ramkishan Suthar Nov 15 '18 at 9:22
  • Ok, BTW I have posted answer as well on your question you can check there. – Ramkishan Suthar Nov 15 '18 at 9:28

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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