cancel
Showing results for 
Search instead for 
Did you mean: 

Rest API call to get cartId for active guest user and logged in customer

Rest API call to get cartId for active guest user and logged in customer

I want to add products to cart on magento 2 from different domain with Node Js setup, the logic is written on node js for sending products to cart. adding products to anonymous guest carts works, but what im looking is for a condition on how to check whether the user on the magento 2 website is a guest or logged in customer, then send add products to cart.

 

So typically, get cart ID for the guest customers who already have a existing cart for adding products to that cart.

Then get customer ID for the logged in customer, and add items to his cart ID.

 

Since Im making all these calls outside of magento 2, before i add products to cart how can i find out, the user on magento 2 website is a guest or logged in customer and how can i achieve above scenarios?.

 

what we can see from externally is PHPSESSID, formkey  under cookies and under local storage we have this data

  1. cart: {summary_count: 0, subtotal: "<span class="price">£0.00</span>", possible_onepage_checkout: true,…}
    1. data_id: 1543310027
    2. isGuestCheckoutAllowed: true
    3. items: []
    4. possible_onepage_checkout: true
    5. subtotal: "<span class="price">£0.00</span>"
    6. subtotal_excl_tax: "<span class="price">£0.00</span>"
    7. subtotal_incl_tax: "<span class="price">£0.00</span>"
    8. summary_count: 0
    9. website_id: "1"
    10. customer: {data_id: 1543310027}
    11. private_content_version:''xxxx"

Can i use any of these data to send to magento 2 rest api and get the customerID or Cart ID for an existing cart and logged in customer?.

 

 

10 REPLIES 10

Re: Rest API call to get cartId for active guest user and logged in customer

Please try this, if the customer is logged in you can get the customer id 

 

Magento gets the customer data with passing anything except token value in API call.

$ch = curl_init('dev.magento2.com/rest/V1/customers/me');curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "GET");curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);curl_setopt($ch, CURLOPT_HTTPHEADER, array(
    'Content-Type: application/json'
));curl_setopt($ch, CURLOPT_COOKIE, 'PHPSESSID=' . $_COOKIE['PHPSESSID']);curl_setopt($ch, CURLOPT_TIMEOUT, 5);curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 5);

//execute post$result = curl_exec($ch);

//close connectioncurl_close($ch);
$json = json_decode($result);
echo $json->id;

 

Re: Rest API call to get cartId for active guest user and logged in customer

 

Thank you for the reply.

I have tried to pass the PHPSESSID as a parameter using POSTMAN, it was asking for customer_id. Do you have any workaround in javascript for node js?.

 

we will have to pass the value using javascript from node js to Magento 2 for getting the customer id and then adding to cart.

Re: Rest API call to get cartId for active guest user and logged in customer

Here is how the magento API works?

 

How magento 2 make calls in-between for the APIs ?

Magento gets the customer data with passing anything except token value in API call.

In between magento calls some API related controllers for the same

vendor/magento/module-customer/etc/webapi.xml

<route url="/V1/customers/me" method="GET">
        <service class="Magento\Customer\Api\CustomerRepositoryInterface" method="getById"/>
        <resources>
            <resource ref="self"/>
        </resources>
        <data>
            <parameter name="customerId" force="true">%customer_id%</parameter>
        </data>
 </route>

in this API call magento get customer data based on token.

Based on API url url="/V1/customers/me" magento calls function from

Magento calls In-between call of dispatch function.

vendor/magento/module-webapi/Controller/Rest.php

 public function dispatch(\Magento\Framework\App\RequestInterface $request)
 {
     /** In between code **/
     // In the same file     $this->processApiRequest();

 }
 protected function processApiRequest()
 {      $inputParams = $this->getInputParamsResolver()->resolve();
 }

And this resolve() function calls override() function

vendor/magento/module-webapi/Controller/Rest/InputParamsResolver.php

 public function resolve()
 {      $inputData = $this->paramsOverrider->override($inputData, $route->getParameters());
 }

and overide() function calls getOverriddenValue() function

vendor/magento/module-webapi/Controller/Rest/ParamsOverrider.php

 public function override(array $inputData, array $parameters)
 {      $value = $this->paramOverriders[$paramValue]->getOverriddenValue();
 }

getOverriddenValue() calls ParamOverriderInterface

vendor/magento/framework/Webapi/Rest/Request/ParamOverriderInterface.php

  • To Override parameter values
  • Parameters in the webapi.xml can be forced. This ensures that on specific routes, a specific value is always used.
  • For instance, if there is a ".../me/..." route, the route should use only user information specific to the
  • currently logged in user. More specifically, if there was a "/customers/me/addresses" route, the service method
  • invoked could have a signature of "getAddresses($customerId)", but in the webapi.xml, the $customerId parameter
  • would be forced to be the customer id of the current authenticated user.
  • The forced override parameter configuration is in the webapi.

   <data>
     <parameter name="customer.id" force="true">%customer_id%</parameter>
   </data>

and for business logic of this function is in file -

vendor/magento/module-webapi/Controller/Rest/ParamOverriderCustomerId.php

   /**
    * {@inheritDoc}
    */
   public function getOverriddenValue()
   {
       if ($this->userContext->getUserType() === UserContextInterface::USER_TYPE_CUSTOMER) {
           return $this->userContext->getUserId();
   }
   return null;
   }

So this is how Magento get Customer Id between API calls !!

 

 

Another solution, try to get customer token and then pass the token to get the customer details in REST API.

 

If nothing works we need to create custom REST API based on requirement in magento

Re: Rest API call to get cartId for active guest user and logged in customer

Hi,

 

Thanks for the solution.

I used javascript to output the ID and cart ID of a logged in customer.

I just need one small advice regarding fetching the cartID of a guest customer(not a logged-in customer) who already created a cart. so I need to get the CartID.

 

$.ajax({
url: "https://magento2/rest/V1/customers/me",
type: "get",
error: function(e) {
console.log("TESTING ERROR", e);
createGuestCart();
},
success: function(resp) {
console.log("testing response", resp.id);
getCart(resp.id);
}
});
}
function createGuestCart() {
const url = "https://magento2/rest/V1/guest-carts";
$.ajax({
type: "POST",
suceess: function(resp) {
console.log("got guest cart", resp.data);
},
error: function(error) {
console.log("error in creating guest cart", e);
}
});
}
function getCart(customerId) {
const url =
"https://magento2/rest/V1/carts/mine?customer_id=" +
customerId;
$.ajax({
url: url,
type: "POST",
error: function(e) {
console.log("TESTING ERROR", e);
},
success: function(resp) {
console.log("testing cart data", resp);
}
});
}

 

 

Re: Rest API call to get cartId for active guest user and logged in customer

Hi,

 

can you please tell me what is getting in the guestcart? didn't you get the cart id?

 

 

Thanks

Re: Rest API call to get cartId for active guest user and logged in customer

Hi,

 

I get the below error:

TESTING ERROR:


responseJSON: {…}
​​
message: "%fieldName is a required field."
​​
parameters: Object { fieldName: "customerId" }
​​
<prototype>: Object { … }

responseText: "{\"message\":\"%fieldName is a required field.\",\"parameters\":{\"fieldName\":\"customerId\"}}"

setRequestHeader: function setRequestHeader()

state: function state()

status: 400

statusCode: function statusCode()

statusText: "Bad Request"


Re: Rest API call to get cartId for active guest user and logged in customer

Hi,

 

[POST] http://.../Magento2/index.php/rest/V1/guest-carts/ - gives cart Id.

 

Did you try this?

 

Thanks!!

Re: Rest API call to get cartId for active guest user and logged in customer

Hi,

 

Thank you, but this is for the anonymous guest user for creating a cart ID and then add cart items.

what I'm looking is to retrieve cart ID for an existing cartID of a guest user and further add items to his CartID.

 

So, as you said I tried using POST for getting the CartID like below, it gives me an empty response.

 

Just to let you know I added this code on Magento 2 website when the guest user clicks on custom AddtoCart button, it should return the CartID of that guest, so that I can send it to my nodejs logic on other domain, then add items to cart using CartID.

 

function AddToCartCuboidClear() {
const url = "https://magento2/rest/V1/guest-carts";
$.ajax({
type: "POST",
suceess: function (resp) {
console.log("got guest cart", resp.data);
},
error: function (error) {
console.log("error in creating guest cart", e);
}
});
}

 

Re: Rest API call to get cartId for active guest user and logged in customer