I want to add products in cart in Magento 2 using Rest API
I have created a controller and using this code.
<?php
$userData = array("username" => "admin", "password" => "password");
$ch = curl_init("http://127.0.0.1/mag/index.php/rest/V1/integration/admin/token");
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($userData));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, array("Content-Type: application/json", "Content-Lenght: " . strlen(json_encode($userData))));
$token = curl_exec($ch);
$customerData = [
'customer_id' => 12
];
$ch = curl_init("http://127.0.0.1/mag/index.php/rest/V1/carts/mine");
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($customerData));
curl_setopt($ch, CURLOPT_HTTPHEADER, array("Content-Type: application/json", "Authorization: Bearer " . json_decode($token)));
$result = curl_exec($ch);
$quote_id = json_decode($result, 1);
echo '<pre>';var_dump($quote_id);
$productData = [
'cart_item' => [
'quote_id' => $quote_id,
'sku' => 'test',
'qty' => 1
]
];
$ch = curl_init("http://127.0.0.1/mag/index.php/rest//V1/carts/mine/items");
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($productData));
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>';var_dump($result);
$ch = curl_init("http://127.0.0.1/mag/index.php/rest//V1/carts/".$quote_id);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "GET");
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>';var_dump($result);
It doesn't show any error but it doesn't add that product in cart i have checked customer id
$customerData = [
'customer_id' => 12
];
for my current logged in user from Database 'customer_entity' table and 'entity_id' row. Any one know how to add that and view it from fronted. Any help is appreciated.