Shopify: get current user id in JavaScript
I am trying to build an app for shopify and I am wondering if I can get the current user id using the 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 see that you can get the current products that the current user has added to your shopping cart, but nothing contains your user ID.
Is this possible or am I missing something?
source to share
I found the variables to be __st
unreliable ( __st_uniqToken
for one). I believe the correct way to do it in Javascript is to use the following call:
ShopifyAnalytics.lib.user().id()
You can also get a unique user id (no login) with:
ShopifyAnalytics.lib.user().properties().uniqToken
It is also the only reliable way to get it from the checkout page. I have used previously __st_uniqToken
but since then it stops working.
NOTE This is no longer 100% fool proof. Shopify have AGAIN changed how their site performs on the landing and thank you pages. I had to resort to the following function to get a reliable user ID.
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 real nightmare. I spend 50% of my time breaking my product every few weeks because they are.
source to share
It looks like the Shopify API has changed again, I can see that the user id is now in ShopifyAnalytics.lib.user().traits().uniqToken
. It may also take a while to load this value.
I am using this piece of code to get the job done as soon as a value is available.
<script type="text/javascript">
actOnUser = function(retry, func){
if (ShopifyAnalytics && ShopifyAnalytics.lib && ShopifyAnalytics.lib.user) {
console.log(ShopifyAnalytics.lib.user().traits().uniqToken); // Do your work here.
} else {
if (retry > 0) {
setTimeout(function() {
func(retry - 1, func);
}, 1000);
}
console.log('User not ready'); // Can be removed - just for debug
}
}
console.log('Starting');
setTimeout(function() {
actOnUser(10, actOnUser);
}, 1000);
</script>
source to share