How to create Shopify webhook for customer login?

263 views Asked by At

I am trying to make my custom application to listen for webhooks from Shopify.

I need to receive customer ID on customer login. Unfortunately Shopify don't have built in functionality.

Is there any way I can achieve this?

Thank you

1

There are 1 answers

2
Hardik Satasiya On BEST ANSWER

There is no webhook for customer login natively available. we can manually trigger web-hook by our custom logic.

Put this JS in your theme.liquid file

<script>
  let loginWebhook = false;  
  {% if customer != nil %}
    if(!window.localStorage.getItem('logged')) {
      loginWebhook = true;  
    }
  {% else %}
    window.localStorage.removeItem('logged')
  {% endif %}
</script>

Put this JS in your main-account.liquid file

<script>
  if(loginWebhook) {
    window.localStorage.setItem('logged', 1);
    console.log('CALL endpoint of webhook', '{{- customer.email -}}');
    // Make a fetch request here and call the webhook endpoint
    // Manually call webhook
    /*
    const webhookURL = 'http://webhookurl.com/log-login';
    const webhookData = {
      'email': '{{- customer.email -}}',
      // HERE add other data which is needed in webhook
      // customer id etc..
    };
    fetch(webhookURL, {
      method: "POST", // *GET, POST, PUT, DELETE, etc.
      headers: {
        "Content-Type": "application/json",
      },
      body: JSON.stringify(webhookData),
    });
    */
  }
</script>

Logic

when the customer object is available on the page, we check if we have already called the webhook or not.

  1. if we did not call webhook we set loginWebhook to true
  2. now the customer will land on the account page` after login every time
  3. here we check loginWebhook if it's true we call webhook
  4. we set the localStorage value logged to 1 so next time we don't call the webhook

Now user will surf the site, and all that time we will not call the webhook as we already called it and store info into localStorage.

If the customer will logout then we remove the logged value from localStorage.

So, Now next time when a user logs in we will again call webhook and we repeat from the top.

Implementation in live-action [Shopify Customer Login Webhook]

Shopify Customer Login Webhook

if any doubt please comment.