Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Shopify: get current logged in user ID in JavaScript

I'm trying to build an app for shopify and I'm interested if I can get the current logged user ID using javascript api or something similar. I was looking at the ajax api: http://docs.shopify.com/support/your-website/themes/can-i-use-ajax-api and I can see you can get the current products that the current user has added to his shopping cart, but nothing about the user ID.

Is it possible, or am I missing something?

like image 992
Doua Beri Avatar asked Aug 26 '14 08:08

Doua Beri


3 Answers

You can try __st.cid in JavaScript for getting customer id.

like image 72
Sandeep Varma Avatar answered Nov 20 '22 08:11

Sandeep Varma


I've found the __st variables unreliable (__st_uniqToken for one). I believe the proper way to do this in Javascript is using the following call:

ShopifyAnalytics.lib.user().id()

You can also get the unique user id (non-logged in id) with:

ShopifyAnalytics.lib.user().properties().uniqToken

This is also the only reliable way to get it on the checkout page. I previously used __st_uniqToken, but it has since stopped working.

NOTE This is no longer 100% fool-proof. Shopify have AGAIN changed how their site works on the landing and thank-you pages. I've had to resort to the following function to get a user id 'reliably'.

var user_id = function() {
    try {
        return ShopifyAnalytics.lib.user().id();
    } catch(e) {}
    try {
        return ShopifyAnalytics.lib.user().properties().uniqToken;
    } catch(e) {}
    try {
        return ShopifyAnalytics.lib.user().anonymousId();
    } catch(e) {}
    return __st_uniqToken;
};

Developing for Shopify is a true nightmare. I spend 50% of my time un-breaking my product every few weeks because them.

like image 18
Rebs Avatar answered Nov 20 '22 07:11

Rebs


In layout.liquid file you can add this code to define global customerId variable

{% if customer %}
  <script type="text/javascript">
   window.customerId = "{{ customer.id }}";   
  </script>
{% endif %}
like image 10
Tim Kozak Avatar answered Nov 20 '22 08:11

Tim Kozak