Webhook handler not firing

pizza123
New Member
2 0 1

I'm following this tutorial to set up my app uninstall webhook: https://shopify.dev/tutorials/build-a-shopify-app-with-node-and-react/listen-for-store-events-with-w...

When I install the app, I get the message that the webhook was successfully registered.

When I uninstall the app, I get a POST request to /webhooks, as expected. For some reason, though, the function I registered in the webhookHandler property initially never seems to run. Here's the relevant code:

 

server.use(
    createShopifyAuth({
      accessMode: 'offline',
      async afterAuth(ctx) {
        console.log('after auth being called')
        const { shop, accessToken, scope } = ctx.state.shopify;

        //store accessToken in db
        await save_app_info(shop, accessToken, scope);

        // Your app should handle the APP_UNINSTALLED webhook to make sure merchants go through OAuth if they reinstall it
        const registration = await Shopify.Webhooks.Registry.register({
          shop,
          accessToken,
          path: "/webhooks",
          topic: "APP_UNINSTALLED",
          apiVersion: ApiVersion.January21,
          webhookHandler: async (_topic, shop, _body) => {
            console.log('webhook handler running')
            console.log(_topic)
          },
        });

        if (registration.success) {
          console.log('Successfully registered webhook!');
        } else {
          console.log('Failed to register webhook', registration.result);
        }

        ctx.redirect(`/?shop=${shop}`);
      },
    }),
  );

 

router.post('/webhooks', async (ctx) => {
    
    // We'll compare the hmac to our own hash
    const hmac = ctx.get('X-Shopify-Hmac-Sha256')

    // Create a hash using the body and our key
    const hash = crypto
      .createHmac('sha256', process.env.SHOPIFY_API_SECRET)
      .update(ctx.request.rawBody, 'utf8', 'hex')
      .digest('base64')

    // Compare our hash to Shopify's hash
    if (hash === hmac) {
      // It's a match! All good
      console.log('Phew, it came from Shopify!')
      await Shopify.Webhooks.Registry.process(ctx.req, ctx.res);
      console.log(`Webhook processed with status code 200`);
      res.sendStatus(200)
    } else {
      // No match! This request didn't originate from Shopify
      console.log('Danger! Not from Shopify!')
      res.sendStatus(403)
    }
  });

 

Any idea why my webhookHandler function wouldn't be firing? I expect it to be called as part of Shopify.Webhooks.Registry.process(). This code is more or less exactly what it was in the various tutorials Shopify provides so I'm not sure where I could be going wrong.

Thank you for any help you can provide!

rac146
New Member
1 0 0

Mr. Pizza - I actually have the exact same problem as you using the new Shopify Node API.

After digging around, it seems the koa-bodyparser is the root cause of the webhook not firing. As a workaround, I created a separate router that initializes before koa-bodyparser. If someone wants to chime in on WHY this is necessary, that would be great. Hope this helps!

  // Webhook router BEFORE bodyparser
  const { webhookRouter } = require('./app/webhookRoutes.js');

  server.use(webhookRouter.routes());
  server.use(webhookRouter.allowedMethods());

  // Use module 'koa-bodyparser'
  server.use(bodyParser());

 

0 Likes
SBD_
Shopify Staff
Shopify Staff
1071 143 189

Hey @pizza123,

Did @rac146's response help?

I just tested with a fresh app from the CLI and the handler ran. The tutorial has evolved over time, so our code might be different - are you able to post a link to an example app with the issue?

0 Likes
pizza123
New Member
2 0 1

Hi SBD_,

Thank you for your response. I sent you a PM with my app's details.

And thank you to @rac146 for sharing your solution. I have a similar setup so I'm not sure why mine wouldn't be working.

0 Likes