Why isn't my web-hook registration working in remix framework?

Why isn't my web-hook registration working in remix framework?

riyas-kv
Shopify Partner
8 0 2

I am using remix framework to build a public app. Here I am trying to register a web-hook while installation. But it is not working. There is no error is shown in the console. If anyone has experience in this, please help. Thanks in advance. Here is the 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: {
    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";

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

  switch (topic) {
    case "PRODUCTS_UPDATE":
      console.log(JSON.stringify(session));
      break;
    default:
      throw new Response("Unhandled webhook topic", { status: 404 });
  }

  throw new Response();
};

 

Replies 11 (11)

derenhg
Shopify Partner
14 0 2

I was facing same issue. What I did was whenever I restart app I used to reinstall app in store

first you can checked if webhook has been added using postman GET

https://{store_name}.myshopify.com/admin/api/2023-01/webhooks.json

add this in header X-Shopify-Access-Token: {session.access_token}

 

If you can see that webhook has been added in postman then you can try reinstalling app. After you have restarted you can initiate webhook 

You can see console log in the terminal where you are running npm run dev command

 

riyas-kv
Shopify Partner
8 0 2

Hey @derenhg 
Thanks for the response. I was always trying reinstall app once app restarts. And as you mentioned, I call the GET web-hooks API and it returns empty. Here is the response after I reinstalling the app.

 

Screenshot from 2023-09-27 17-39-07.png

 

 

an_autoserve
Shopify Partner
17 0 1

Hi, have you able to solve this? I am running into the same problem. Uninstalling and reinstalling the app does not register the webhook for me.

 

I am definitely new to Shopify webhook so I don't really understand. But the webhook should be registered once we install the app, am I right?

 

I'm think it's might be that I'm testing it on a development store.

riyas-kv
Shopify Partner
8 0 2

@an_autoserveIt is not solved and I'm also using development store for testing purpose.

 

The webhook should've been registered once we install the app. I don't know why it is not registering.

derenhg
Shopify Partner
14 0 2

I was facing same issue but when I have added GDPR webhooks the issue got resolved although I don't know what happened behind the scene. you can also try to add like this before your custom webhook and let me know

 

APP_UNINSTALLED: {
      deliveryMethod: DeliveryMethod.Http,
      callbackUrl: "/webhooks",
    },
    CUSTOMERS_DATA_REQUEST: {
      deliveryMethod: DeliveryMethod.Http,
      callbackUrl: "/webhooks",
    },
    CUSTOMERS_REDACT: {
      deliveryMethod: DeliveryMethod.Http,
      callbackUrl: "/webhooks",
    },
an_autoserve
Shopify Partner
17 0 1

I have tried to add these webhooks. Then, uninstalled & reinstalled the app. The problem still persists.

 

Do you need to configure these GDPR webhook in your Partner dashboard as well?

derenhg
Shopify Partner
14 0 2

Can you see if your issue is resolved by following this

https://community.shopify.com/c/webhooks-and-events/custom-app-register-webhook-failed/td-p/665010

 

In short you might need to provide correct access_scope required by the webhook

CharlesMoreno
Shopify Partner
21 0 12

Encountered this as well but here's what worked for me that you can try:

 

1. Make sure that you have the proper scopes

2. Uninstall the app installed from your store before running your application again

3. When running your application use this command below:

"npm run dev -- --reset"

 

Installing your App into your store should log the Authentication and as well as the registration of webhooks.

 

Hope that helps.

RuentDev
Shopify Partner
3 0 0

This Methods works on my project Thankyou! 😁

 

vincaslt
Shopify Partner
2 0 2

I managed to fix this by awaiting `registerWebhooks` in `afterAuth`. It comes with this issue from the official template, but the await seems to fix it. Spent 2 hours debugging...

```

afterAuth: async ({ session }) => {
    await shopify.registerWebhooks({ session });
}

```

rdutton
Shopify Partner
4 0 0

If you encounter this issue there is multiple reasons that could be impacting the webhook registration. They are all mentioned in this thread, but here is a list:

- Incorrect or missing scope assigned to your app.  e.g. If you want to listen to orders/create you will need the 'read_orders' scope.

- You have not filled out the 'API Access > Protected customer data access' section of the app setup in shopify.dev.  Even if your app is being installed into a development store, this area needs to be at least partially completed. It only applies to certain topics such as 'orders/create'.

- If you are using the Remix boilerplate app you might need to modify the line:

 

 

shopify.registerWebhooks({ session });

 

 

to

 

 

await shopify.registerWebhooks({ session });

 

 

as pointed out by 'vincaslt'.

I had migrated the code from node to a Cloudflare worker, and without the 'await' I was sometimes having one webhook registered and other times none.

 

It could also be useful to expand the code to:

 

 

const register_result = await shopify.registerWebhooks({ session });
console.log("AFTER REGISTER WEBHOOKS", register_result);

 

 

To see that the code is being run, and potential reasons for the webhook not being applied.

e.g.

✘ [ERROR] [shopify-app/ERROR] Failed to register webhook | {topic: ORDERS_CREATE, shop: some-shop.myshopify.com, result: {"data":{"webhookSubscriptionCreate":{"userErrors":[{"field":["webhookSubscription"],"message":"This app is not approved to subscribe to webhook topics containing protected customer data. See https://partners.shopify.com/2052925/apps/83593625601/customer_data for more details."}]}},"extensions":{"cost":{"requestedQueryCost":10,"actualQueryCost":10,"throttleStatus":{"maximumAvailable":2000,"currentlyAvailable":1990,"restoreRate":100}}}}}