Our Partner & Developer boards on the community are moving to a brand new home: the .dev community forums! While you can still access past discussions here, for all your future app and storefront building questions, head over to the new forums.

Get customer id from JavaScript for use in secondary API call

Get customer id from JavaScript for use in secondary API call

jbcm
Shopify Partner
1 0 0

Im developing a Shopify app that needs to update a customers metafield with a value.

 

I have added a custom JS file to all pages using the ScriptTag API, using the app proxy I get a callback to my server, where I want to update the customer metafield using:

 

POST /admin/api/2022-07/customers/$CUSTOMER-ID/metafields.json

 

The problem is I cant find the customer ID from the JavaScript file. 

 

I tried this codeblock:

 

 var getCustomerId = function() {
    try {
      let curr = window.ShopifyAnalytics.meta.page.customerId;
      if (curr !== undefined && curr !== null && curr !== "") {
        return curr;
      }
    } catch(e) { }
    try {
      let curr = window.meta.page.customerId;
      if (curr !== undefined && curr !== null && curr !== "") {
        return curr;
      }
    } catch (e) { }    
    try {
      let curr = _st.cid;
      if (curr !== undefined && curr !== null && curr !== "") {
        return curr;
      }
    } catch (e) { }
    try {
      let curr = ShopifyAnalytics.lib.user().traits().uniqToken;
      if (curr !== undefined && curr !== null && curr !== "") {
        return curr;
      }
    } catch (e) { }
    return null;
  }

 

And that gives me a customer id, but its a UUID, not a numeric ID, and thus I cannot feed it into the API call to update the metafield.

 

I also tried adding a liquid tag, so that I could extract it from JS

 

 

 

<div id="app-customer-id">{{ customer.id }}</div> 

 

 

 

but no matter what I try and where in the shop I browse, that DIV is always blank. Im sure Im logged in as a valid customer, but on all pages that value is blank. My shop is in development-mode and is password protected.

 

Any help would be very much appreciated! Thanks.

Replies 0 (0)