Automate Your E-commerce with Shopify Webhooks

This article explains how webhooks work and how they can automate different parts of your online business. We’ll also show you how to set them up.

Introduction

In today’s dynamic e-commerce world, process automation is key to efficiency and competitiveness. The Shopify e-commerce management platform offers many webhook topics in its API. In this article, we’ll explore how webhooks work, how they can help automate various aspects of your e-commerce business and how to configure them.

What are Webhooks?

Webhooks are a method for apps to communicate with each other automatically. They send real-time data from one application to another whenever a specific event occurs. In the context of Shopify, webhooks allow your store to send notifications to an external URL when certain events take place, such as order creations, inventory updates, or customer information changes.

This enables seamless automation of various processes without the need for manual intervention.

Use Cases

Shopify Webhooks offer numerous possibilities for automating your e-commerce processes. Here are some examples:

  • Automated SMS Notifications: Send an automatic SMS to customers with a tracking link once their order is handed over to the delivery provider.
  • Product Feed Distribution: Automatically send product feeds to other e-commerce platforms like Google Shopping, Facebook, Ceneo, Allegro, and Empik whenever certain events occur in your store.
  • Advanced Analytics Integration: Integrate advanced tools like Mixpanel to track customer behavior and order placements in real-time.
  • Discount Code Automation: Automatically generate and send one-time discount codes to customers who abandon the checkout process, encouraging them to complete their purchase.

As you can see, with webhooks, there’s plenty of room to enhance your store’s functionality and efficiency. A full list of Shopify webhooks topics can be found under this link.

Configuration

 

Shopify admin panel

One way to integrate with Shopify webhooks is by subscribing to a webhook through the admin panel. This method is ideal for simple integrations, such as with the tool Zapier.

To configure such a webhook, go to Shopify admin panel -> Settings -> Notifications -> Webhooks -> Create a webhook.

This will bring up the following modal window:

screenshot from shopify admin panel
Screenshot

Here’s a brief explanation of the fields:

  • Event: This is the topic of the webhook you want to listen to, such as order creation or inventory updates.
  • Format: This option allows you to choose the format of the received data. You can select either JSON or XML.
  • URL: This is the address where the event data will be sent (e.g., https://hooks.zapier.com/hooks/catch/1234567/X1X2Xxyz/).
  • Webhook API version: This defines the version of the Shopify API and determines the structure of the data sent by the webhook.

If you save and test thoroughly then congratulations, you have just configured your first webhook correctly!

Shopify app

Another method for configuring webhooks involves creating a dedicated Shopify app for your store. This allows for more advanced utilization of webhooks using JavaScript code. An example scenario could involve the need to utilize two interdependent webhooks.

Firstly, you need to have a Shopify Partners account and create a Shopify app. After setting up your environment (in this example, using JavaScript with Remix), you can proceed with configuring the webhooks.

In the shopify.server.ts file, add the desired webhook to the webhooks object, for example:

ORDERS_CREATE: {
  deliveryMethod: DeliveryMethod.Http,
  callbackUrl: "/webhooks",
},

This prepares your application to receive data for the specified webhook topic. Next, in the routes/webhook.tsx file, add a new case to the switch statement, for instance:

case "ORDERS_CREATE":
  // Add business logic here to handle the webhook

  break;

In this section, you can implement the business logic responsible for handling the webhook data.

Halfway through our success, now we need to subscribe to the webhook so that the application can use it. It’s best to do this in a way that allows the application user to enable and disable the webhook.

Therefore, the first step is to create a user interface. Shopify provides a very user-friendly library called Shopify Polaris, which is recommended for use. Here’s an example view with a toggle:

import { useSubmit } from "@remix-run/react";

export default function WebhooksPage() {

  const submit = useSubmit();

  const subscribeWebhook = () => {
      const data = new FormData();
      data.append("custom_data", "x"); // You can add here some data

      submit(data, { method: "POST" });
  };

  return (
    <Page>
      <ui-title-bar title="Webhooks" />
      <Layout>
        <Layout.Section>
          <Button onClick={subscribeWebhook}>On</Button>
        </Layout.Section>
      </Layout>
    </Page>
  );
}

Then, we need to attach an action to the toggle button that sends a request to subscribe to the webhook:

import { json } from "@remix-run/node";
import { authenticate } from "~/shopify.server";

export const action = async ({ request }: ActionFunctionArgs) => {
  const { admin, session } = await authenticate.admin(request);
  const formData = new URLSearchParams(await request.text()); // here you can use your passed data

  const webhooksUrl = new URL(
    "/webhooks",
    process.env.SHOPIFY_APP_URL,
  ).toString();

  if (request.method === "POST") {
      const webhook = new admin.rest.resources.Webhook({ session: session });

      if (!webhook) {
        return json(
          { error: "No webhook object for given session" },
          { status: 400 },
        );
      }

      webhook.topic = "orders/create";
      webhook.address = webhooksUrl;
      webhook.format = "json";

      try {
        await webhook.save({ update: true });
        return json(null, { status: 200 });
      } catch (e) {
        return json({ error: "Failed while saving webhook" }, { status: 400 });
      }
  }
  return json({ error: "Method not allowed" }, { status: 405 });
};

It’s crucial to note that webhook subscription visibility is limited to the current session. Therefore, sending a request for active webhooks using a different API_KEY and API_SECRET than the application that subscribed to the webhook will return a different webhook context.

To test and verify whether the webhook has been successfully subscribed you can use the loader function and return all subscribed webhooks:

import { authenticate } from "~/shopify.server";

export const loader = async ({ request }: LoaderFunctionArgs) => {
  const { admin, session } = await authenticate.admin(request);

  try {
    const response = await admin.rest.resources.Webhook.all({
      session: session,
    });

    const activeWebhooks = (response?.data ?? [])
      .map((webhook) => ({
        topic: webhook.topic,
        id: webhook.id,
        address: webhook.address,
      }));

    console.log("Active webhooks: ", activeWebhooks);

    return json({ activeWebhooks }, { status: 200 });
  } catch (e) {
    console.log("Error while loading webhooks page");
    return json({ error: "Error while loading webhooks page" }, { status: 500 });
  }
};

Congratulations! If everything has been done correctly, you have successfully configured the webhook using Shopify app!

The next steps will involve adding business logic upon receiving responses from the webhook and deploying the application to a production server so that it can operate on the target store.

If your store requires highly intricate business logic or if you feel overwhelmed by the complexity of configuring webhooks, don’t hesitate to reach out to us. We specialize professionally in handling such matters and we are here to help you.

 

Summary

In summary, we delved into the versatility of Shopify Webhooks for automating e-commerce operations. We

  • defined webhooks,
  • outlined integration methods,
  • and showcased practical use cases.

Shopify Webhooks offer a powerful way to automate and streamline various aspects of your e-commerce store, enhancing efficiency and competitiveness. Whether you’re handling simple integrations or complex business logic, webhooks can significantly improve your operations.

Embrace automation and take your e-commerce business to the next level.

Leave a Reply

Your email address will not be published. Required fields are marked *