2

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
                    ];
                }
            ];
        }
    ]
]
?>
4

The cart is not baked into \Craft, but craft\commerce\Plugin.

Try the following:

$cart = craft\commerce\Plugin::getInstance()->getCarts()->getCart();

Uses the following function:

/**
 * Get the current cart for this session.
 *
 * @param bool $forceSave Force the cart to save when requesting it.
 * @return Order
 * @throws Exception
 * @throws \Throwable
 * @throws \craft\errors\ElementNotFoundException
 */
public function getCart($forceSave = false): Order

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.