Shopify / shopify-api-js

Shopify Admin API Library for Node. Accelerate development with support for authentication, graphql proxy, webhooks
MIT License
942 stars 391 forks source link

Shopify.Webhooks.Registry.process doesn't trigger Shopify.Webhooks.Registry.addHandler webhookHandler #512

Closed egillanton closed 2 years ago

egillanton commented 2 years ago

Issue summary

My webhook handler is not called when the following code is called:

index.js

...
setupGDPRWebHooks("/webhooks");
setupOrderWebhooks();
... 
export async function createServer(
...
app.post("/webhooks/*", async (req, res) => {
...
await Shopify.Webhooks.Registry.process(req, res); // I am able to reach here
...

setup-order-webhooks.js

export function setupOrderWebhooks() {
    Shopify.Webhooks.Registry.addHandler("ORDERS_PAID", {
      path: "/webhooks/orders/paid",
      webhookHandler: async (topic, shop, body) => {
        console.log(`Called: ${topic} for ${shop}`); // I am not able to reach here
      },
    });
};

auth.js

export default function applyAuthMiddleware(
...
app.get("/auth/callback", async (req, res) => {
...
const responses = await Shopify.Webhooks.Registry.registerAll({
        shop: session.shop,
        accessToken: session.accessToken,
      });

      Object.entries(responses).map(([topic, response]) => {
        // The response from registerAll will include errors for the GDPR topics.  These can be safely ignored.
        // To register the GDPR topics, please set the appropriate webhook endpoint in the
        // 'GDPR mandatory webhooks' section of 'App setup' in the Partners Dashboard.
        if (!response.success && !gdprTopics.includes(topic)) {
          if (response.result.errors) {
            console.log(
              `Failed to register ${topic} webhook: ${response.result.errors[0].message}`
            );
          } else {
            console.log(
              `Failed to register ${topic} webhook: ${
                JSON.stringify(response.result.data, undefined, 2)
              }`
            );
          }
        }
        else{
          console.log(`Successfully registered ${topic} webhook to shop: ${session.shop}`);
        }
      });
...

In my console when I run the app, get the following:

Successfully registered APP_UNINSTALLED webhook to shop: *****.myshopify.com
server/middleware/auth.js:242
Successfully registered ORDERS_PAID webhook to shop: *****.myshopify.com
server/middleware/auth.js:242
Successfully registered ORDERS_FULFILLED webhook to shop: *****.myshopify.com

In my ngrok window I see a request being made but it doesn't respond with any status code.

POST /webhooks/orders/paid    [NO RESPONSE]

Expected behavior

I am expecting the webhook handler to be called:

Called: ORDERS_PAID for *****.myshopify.com

In my ngrok window I would expect to see

POST /webhooks/orders/paid   200 Successful

Actual behavior

When I set the breakpoint on the following line in the webhook handler, the code is never reached. console.log(Called: ${topic} for ${shop});

The code runs to:

await Shopify.Webhooks.Registry.process(req, res);

I am not able to properly debug the registry.js, but I never reach request.on('end' request.on('end'

Steps to reproduce the problem

  1. Create an app using the shopify-cli tool
  2. Create a setup-orders-webhook.js file in root similar file to gdpr.js
  3. Call the setupOrdersWebhook in the index.js file where you are adding the handlers for the GDPR webhooks.
  4. Instead of using "/api/webhooks" in this project I am using "/webhooks".

Checklist

egillanton commented 2 years ago

It seems to work if I add the handlers directly in index.js file instead of exporting the functionality to a separate file (setup-orders-webhook.js)

mkevinosullivan commented 2 years ago

I suspect you may have a bodyParser of some sort being used before the call to Shopify.Webhooks.Registry.process(req, req).

.process will read in and parse the stream itself - if it has already been done, then it will fail.

Please see https://github.com/Shopify/shopify-api-node/blob/main/docs/usage/webhooks.md#note-regarding-use-of-body-parsers.

Also note the ordering in the app template: https://github.com/Shopify/shopify-app-template-node/blob/cli_three/web/index.js#L79-L93

github-actions[bot] commented 2 years ago

We are closing this issue because we did not hear back regarding additional details we needed to resolve this issue. If the issue persists and you are able to provide the missing clarification we need, feel free to respond and reopen this issue.

We appreciate your understanding as we try to manage our number of open issues.