skip to Main Content

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?

2

Answers


  1. Chosen as BEST 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.


  2. You are doing something wrong. Why would you make a call to Shopify with a key and a secret? Are you not selling yourself a little short here? I mean if I examined your source code, and saw a key and secret, I would be able to use that to do anything I want. Is that the goal here? Allowing anyone on the Internet to make you look silly? Shopify has a button you can place anywhere to add products to a cart. You can use that. It is secure.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search