cancel
Showing results for 
Search instead for 
Did you mean: 

How to add a product to cart using api

How to add a product to cart using api

Use-case: We need to add a js script to the product page which opens a model popup. User will be able to chat with a representative from that popup. That representative will send similar products from the same website. User should be able to add those products to cart from the popup without a page reload.

 

Is there any API through which we can add products to the user's cart using the product's ID or SKU? or Is there any other way we can achieve this?

3 REPLIES 3

Re: How to add a product to cart using api

@saiprasada4dec 

 

Here is the official documents for add to cart api

 

https://devdocs.magento.com/guides/v2.4/rest/tutorials/orders/order-add-items.html

Manish Mittal
https://www.manishmittal.com/

Re: How to add a product to cart using api

Thanks for the update. @Manish Mittal 

 

I've tried the below apis

1. POST -  /rest/default/V1/guest-carts

Res: "0RA1VYNAdzxJMphDCt27XHrJ1D7gOMT8" -> returns new guestcart id every time 

2.GET - /rest/default/V1/guest-carts/{cartId}/items 

Res: [] 

3. POST- /rest/default/V1/guest-carts/{cartId}/items 

payload={ 

"cartItem": { 

"item_id": 1, 

"sku": "Dell", 

"qty": 1, 

"name": "Dell Laptop", 

"price": 30.00, 

"product_type": "simple", 

"quote_id": "1",

"product_option": {}, 

"extension_attributes": {} 

} 

} 

Res: 400 error 

{"message":"\"%fieldName\" is required. Enter and try again.","parameters":{"fieldName":"quoteId"}} 

4. GET - /rest/default/V1/carts/mine 

Res: 401 error  

{"message":"The consumer isn't authorized to access %resources.","parameters":{"resources":"self"}}

 

I've seen we need to use "POST <host>/rest/<store_code>/V1/integration/customer/token" and send username and password to get the customer's auth token.

 

As per my requirement, I will not be able to get those details. I'm stuck here. How to get the auth token without credentials? can we get the current cart Id without auth token? How to get quoteId? Is there any other way to achieve my functionality?

Note: Just to add again, A model popup will be shown on the product page. user should be able to add different products to the cart by clicking on the buttons in the popup(by making ajax calls or any other way. we can not get the user info by the way for auth token)

Re: How to add a product to cart using api

@saiprasada4dec 

 

You cant call API without auth token.

 

For your requirement, you can just add any popup and call products into this popup. And add to cart ajax functionality to  add products to cart.

 

You can use some plugins for pop up or add to cart.

https://marketplace.magento.com/magebird-popup.html

https://www.mageplaza.com/magento-2-better-popup/

https://bsscommerce.com/magento-2-popup-extension.html

Manish Mittal
https://www.manishmittal.com/