Magento 2 API Add Product To Cart

The following code will add product to a cart/quote for a logged-in customer.

<?php
 $magentoURL = "http://127.0.0.1/mage2/";
 $apiURL = $magentoURL."index.php/rest/V1/integration/customer/token";
 $data = array("username" => "Test.User1521623008@phpcodez.com", "password" => "phpcodezpwd");
 $data_string = json_encode($data);

$ch = curl_init($apiURL);
 curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
 curl_setopt($ch, CURLOPT_POSTFIELDS, $data_string);
 curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
 curl_setopt($ch, CURLOPT_HTTPHEADER, array("Content-Type: application/json","Content-Length: ".strlen($data_string)));
 $token = curl_exec($ch);

$quoteUrl =$magentoURL.'index.php/rest/V1/carts/mine';

$chQuote = curl_init($quoteUrl);
 curl_setopt($chQuote, CURLOPT_HTTPHEADER, array("Content-Type: application/json", "Authorization: Bearer " . json_decode($token)));
 curl_setopt($chQuote, CURLOPT_RETURNTRANSFER, true);
 $quote = json_decode(curl_exec($chQuote));
 
 $cartData = [
 'cartItem' => [
 "quote_id" => $quote->id,
 "sku" => "152110360696",
 "qty" => 2
 ]
 ];

$requestUrl =$magentoURL.'index.php/rest/V1/carts/mine/items';

$ch = curl_init($requestUrl);
 curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
 curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
 curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($cartData));
 curl_setopt($ch, CURLOPT_HTTPHEADER, array("Content-Type: application/json", "Authorization: Bearer " . json_decode($token)));
 $result = json_decode(curl_exec($ch));
 echo "<pre>";print_r($result);

?>

Leave a Reply

Your email address will not be published. Required fields are marked *