I want to be able to retrieve the current users Cart via a JSON API endpoint, so I can loop through the products in the cart in JS on the front end.
I've got the Element API plugin installed, but I am not understanding how to grab the current cart from inside the endpoint via PHP. Any help much appreciated.
<?php
use craft\helpers\UrlHelper;
use craft\commerce\elements\Product;
use craft\commerce\elements\Order;
function requireLogin() {
$currentUser = Craft::$app->user->getIdentity();
if(!$currentUser) {
throw new \yii\web\ForbiddenHttpException("You are not logged in");
}
}
function requireCart() {
// TWIG would be: {% set cart = craft.commerce.getCarts().getCart() %}
$currentCart = Craft::WHAT?;
$cartId = $currentCart->id;
if(!$currentCart) {
throw new \yii\web\ForbiddenHttpException("You don't have a cart yet");
}
}
return [
'endpoints' => [
'cart.json' => function() {
requireLogin();
requireCart();
\Craft::$app->response->headers->set('Access-Control-Allow-Origin', '*');
return [
'elementType' => Order::class,
'criteria' => ['id' => $cartId],
'transformer' => function(Order $order) {
$items = [];
foreach($order->lineItems as $lineItem) {
$items[] = [array(
'itemTitle' => $lineItem->title
)];
}
return [
'items' => $items
];
}
];
}
]
]
?>