Need help implementing webhooks in the newest remix template?

Hello I am using newest remix template version, which doesn’t have web folder or gdpr.js file. I am trying to implement webhooks but notice I don’t have gdpr.js file. Here is my code I thought it might work? But the console doesn’t log anything when I modify product. Anyone have any idea? Thank you!

import "@shopify/shopify-app-remix/adapters/node";
import {
  AppDistribution,
  DeliveryMethod,
  shopifyApp,
  LATEST_API_VERSION,
} from "@shopify/shopify-app-remix";
import { PrismaSessionStorage } from "@shopify/shopify-app-session-storage-prisma";
import { restResources } from "@shopify/shopify-api/rest/admin/2023-07";

import prisma from "./db.server";

const shopify = shopifyApp({
  apiKey: process.env.SHOPIFY_API_KEY,
  apiSecretKey: process.env.SHOPIFY_API_SECRET || "",
  apiVersion: LATEST_API_VERSION,
  scopes: process.env.SCOPES?.split(","),
  appUrl: process.env.SHOPIFY_APP_URL || "",
  authPathPrefix: "/auth",
  sessionStorage: new PrismaSessionStorage(prisma),
  distribution: AppDistribution.AppStore,
  restResources,
  webhooks: {
    PRODUCTS_UPDATE: {
      deliveryMethod: DeliveryMethod.Http,
      callbackUrl: "/ItemUpdates",
      callback: async (topic, shop, body, webhookId) => {
        console.log('--- Product update ---');
        const payload = JSON.parse(body);
        console.log(payload);
        console.log('--- /Product update ---');
      },
    },
    APP_UNINSTALLED: {
      deliveryMethod: DeliveryMethod.Http,
      callbackUrl: "/webhooks",
      callback: async (topic, shop, body, webhookId) => {
        try {
          console.error("Success!");
        } catch (error) {
          console.error('Error processing APP_UNINSTALLED webhook:', error);
        }
      },
    },
  },
  hooks: {
    afterAuth: async ({ session }) => {
      shopify.registerWebhooks({ session });
    },
  },
  ...(process.env.SHOP_CUSTOM_DOMAIN
    ? { customShopDomains: [process.env.SHOP_CUSTOM_DOMAIN] }
    : {}),
});

export default shopify;
export const apiVersion = LATEST_API_VERSION;
export const addDocumentResponseHeaders = shopify.addDocumentResponseHeaders;
export const authenticate = shopify.authenticate;
export const login = shopify.login;
export const registerWebhooks = shopify.registerWebhooks;
export const sessionStorage = shopify.sessionStorage;
import { authenticate } from "../shopify.server";

export const action = async ({ request }) => {
  const { topic, shop, session } = await authenticate.webhook(request);

  switch (topic) {
    case "PRODUCTS_UPDATE":
       console.log("product update works");
    default:
      throw new Response("Unhandled webhook topic", { status: 404 });
  }

  throw new Response();
};

Are you getting any error messages in the console? Do you have the correct scope in place?

Did you find any solutions?

When I deployed it locally without nginx the URL will change every time. This means I have to uninstall and install my app in my test shop to test webhooks. Also, I should have added console.log statement to the second code snippet. The first code runs when I register webhooks, while the second one is when webhook being call. This is my understanding, please correct me if you have any suggestion.

1 Like

Hello, @andrewZZZ
Can you tell me why my order create webhook is not registered?
I have done this code in my shopify.server.js file

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

Create a new file for the order crate like this:-

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

export const action = async ({ request }) => {
  const { topic, shop, session } = await authenticate.webhook(request);

  switch (topic) {
    case "ORDERS_CREATE":
      if (session) {
        await db.session.deleteMany({ where: { shop } });
      }
      break;
    default:
      throw new Response("Unhandled webhook topic", { status: 404 });
  }

  throw new Response();
};

But the order create webhook is not registered, I don’t know why.

Hey @Ronak3 correct name for order/create webhook is ORDER_TRANSACTIONS_CREATE

According to this documentation.

https://shopify.dev/docs/api/admin-graphql/2023-07/enums/WebhookSubscriptionTopic

Hey @andrewZZZ , I’m facing the same problem. I’m not able to register webhooks while installation. I’ve done the same code as you mentioned above. What do you think the problem with my code?

import "@shopify/shopify-app-remix/adapters/node";
import {
  AppDistribution,
  DeliveryMethod,
  shopifyApp,
  LATEST_API_VERSION,
} from "@shopify/shopify-app-remix/server";
import { PrismaSessionStorage } from "@shopify/shopify-app-session-storage-prisma";
import { restResources } from "@shopify/shopify-api/rest/admin/2023-07";

import prisma from "./db.server";

const shopify = shopifyApp({
  apiKey: process.env.SHOPIFY_API_KEY,
  apiSecretKey: process.env.SHOPIFY_API_SECRET || "",
  apiVersion: LATEST_API_VERSION,
  scopes: process.env.SCOPES?.split(","),
  appUrl: process.env.SHOPIFY_APP_URL || "",
  authPathPrefix: "/auth",
  sessionStorage: new PrismaSessionStorage(prisma),
  distribution: AppDistribution.AppStore,
  restResources,
  webhooks: {
    APP_UNINSTALLED: {
      deliveryMethod: DeliveryMethod.Http,
      callbackUrl: "/webhooks",
    },
    PRODUCTS_UPDATE: {
      deliveryMethod: DeliveryMethod.Http,
      callbackUrl: "/webhooks",
      callback: async (topic, shop, body, webhookId) => {
        console.log('--- Product update ---');
        const payload = JSON.parse(body);
        console.log(payload);
        console.log('--- /Product update ---');
      },
    }
  },
  hooks: {
    afterAuth: async ({ session }) => {
      shopify.registerWebhooks({ session });
    },
  },
  ...(process.env.SHOP_CUSTOM_DOMAIN
    ? { customShopDomains: [process.env.SHOP_CUSTOM_DOMAIN] }
    : {}),
});

export default shopify;
export const apiVersion = LATEST_API_VERSION;
export const addDocumentResponseHeaders = shopify.addDocumentResponseHeaders;
export const authenticate = shopify.authenticate;
export const unauthenticated = shopify.unauthenticated;
export const login = shopify.login;
export const registerWebhooks = shopify.registerWebhooks;
export const sessionStorage = shopify.sessionStorage;
import { authenticate } from "../shopify.server";
import db from "../db.server";

export const action = async ({ request }) => {
  const { topic, shop, session } = await authenticate.webhook(request);

  switch (topic) {
    case "APP_UNINSTALLED":
      if (session) {
        await db.session.deleteMany({ where: { shop } });
      }
      break;
    case "PRODUCTS_UPDATE":
      console.log(JSON.stringify(session));
      break;
    case "CUSTOMERS_DATA_REQUEST":
    case "CUSTOMERS_REDACT":
    case "SHOP_REDACT":
    default:
      throw new Response("Unhandled webhook topic", { status: 404 });
  }

  throw new Response();
};

Please help. Thanks in advance!

Hi @riyas-kv

Did you solved the problem?

Thanks

Hi @walidev ,

No, it is not solved. I’ve posted it as a separate query in the community. Here is the link to it: https://community.shopify.com/c/shopify-apps/remix-framework-webhook-flow/m-p/2241390#M68659

If you have any idea, please help

Thanks

Could you try adding a breakpoint at

shopify.registerWebhooks({ session });

? I don’t know why it’s not registered, but if you use Cloudfare (default), every time link will be updated, you have to uninstall and install it again to trigger hooks.

@andrewZZZ As you said every time I’m reinstalling the app. I tried adding a breakpoint and the execution never reached that point. It is not getting triggered. Am I missing something here?

I guess you should check files in prev process then

@andrewZZZ What do you mean by prev process? Could you please explain?

Did you test this on your development store? Are there any special environment setup that you need to do to be able to test the webhook?

I am testing my own webhook but it seems like it did not register correctly.

@an_autoserve Yes, I’m testing this on development store. I think we both have same problem. Could you please check by adding breakpoint at below line as suggested by @andrewZZZ and see if this part get executed?

shopify.registerWebhooks({ session });

I checked where registerWebhooks is used and noticed it’s mostly used in the build folder. Are you using a remix framework? Did you try recreating a new one and testing it?

I don’t think the APP_UNINSTALLED webhook is running either. Since it supposes to delete all the data from Prisma on uninstallation. But, it doesn’t.

So I think none of the webhooks in my app are being registered.

Hi everyone,

I think this is a global issue, I tried everything I found in Internet, but webhooks are still not registered.

I changed server to ngrok to have a fixed server address,

When I trigger a webhook using the CLI, the wehbook is fired, that means the issue is in registering the webhooks

Did you tried to register the webhook using a rest/graphql api (ex, postman) ?

Hi @walidev , I have the same problem, do you have solved it ?

I was having the same issue. I fixed it by using the Graphiql API to subscribe to a topic, instead of the shopify.server.js file.

mutation MyMutation {
        webhookSubscriptionCreate(
          topic: PRODUCTS_UPDATE
          webhookSubscription: {callbackUrl: "{tunnel-URL}/webhooks"}
        ) {
          webhookSubscription {
            callbackUrl
            createdAt
            id
          }
        }
      }`

I still haven’t fixed the issue in the shopify.server.js this is just a workaround for now.