Ad

Shopify API Returns Empty Cart

- 1 answer

Using this API: https://help.shopify.com/en/themes/development/getting-started/using-ajax-api#add-to-cart

From my messenger bot I call cart/add.js multiple times with the variant id and quantity and it returns a success message, but I call cart.js to retrieve the items, the cart is always empty.

I'm adding items to the cart like this:

$cartAPI = 'https://'.$shopKey.':'.$shopSecret.'@'.$shopUrl.'/cart/add.js';
$request = $client->request('POST', $cartAPI, [
      'form_params' => [
          'id'        => (int) $productID,
           'quantity' => 1
       ]
]);

And retrieving cart like this:

$cartAPI = 'https://'.$shopKey.':'.$shopSecret.'@'.$shopUrl.'/cart.js';
$request = $client->get($cartAPI);

I tried to include cookies in the Guzzle call like so $this->client = new Client(['cookies' => true]); and both calls use the same client instance, but it still returns an empty cart.

I don't use CloudFlare or any Caching mechanism for this.

What am I doing wrong?

Ad

Answer

Solution i figured out here for anyone having the same issue. I needed to use the cart cookie. Ended up doing something like:

$cartCookie = Cache::tags(['user:' .$userId, 'cookies'])->get('cart');

if (!$cartCookie) {
    $client  = new Client(['cookies' => true]);
} else {
    $cookieJar = CookieJar::fromArray([
        'cart' => $cartCookie,
    ], conf('shop.url'));
    $client = new Client(['cookies' => $cookieJar]);
}

Cookie is stored in the cache the first time the user adds an item to the cart and used for recurrent adds. I had to put it in Cache since I'm building a chatbot but you can just use cookies from your browser.

Ad
source: stackoverflow.com
Ad