Unable to get Webhook regsitration working

Unable to get Webhook regsitration working

happysentient
Shopify Partner
1 0 0

Hello, I'm a new developer and I getting error with my new App (on Node & express using HTTPs).

I tried 'Shopify CLI' but I could not make the webhook part working. Therefore, I chose to build it ground up.

If anyone can take a look what I'm doing, I'd much appreciate it.

 

I keep getting :

console:

 

 

 

HttpResponseError: Received an error response (406 Not Acceptable) from Shopify:
If you report this error, please include this id: 705e1042-2724-4be4-9aa2-e9b14d518f07

 

 

 

.ENV file

 

 

 

SHOPIFY_API_SCOPES=read_products,read_orders

 

 

 

Code area triggering the issue is below:

 

 

 

 

 

const response = await Shopify.Webhooks.Registry.register({
               path: '/webhooks',
               topic: 'PRODUCTS_UPDATE',
                accessToken: shopSession.accessToken,
               shop: shopSession.shop,
});​

 

 

 

index.js

 

 

 

import express from 'express';
import dotenv from 'dotenv';
import {Shopify} from '@shopify/shopify-api';

dotenv.config();

const host = '127.0.0.1';
const port = 3000;

const {SHOPIFY_API_KEY, SHOPIFY_API_SECRET,SHOPIFY_API_SCOPES,HOST} = process.env;

// this will need to be persisted to keep track of installed apps already.
const shops = {}

// Initialize Shopify
Shopify.Context.initialize({
    API_KEY : SHOPIFY_API_KEY,
    API_SECRET_KEY: SHOPIFY_API_SECRET,
    SCOPES: SHOPIFY_API_SCOPES,
    HOST_NAME : HOST,
    IS_EMBEDDED_APP : true,   
});

// -->  Webhook handling
const handleWebhookRequest = async (topic, shop, webhookRequestBody) => {
  // handler triggered when a webhook is sent by the Shopify platform to your application
  console.log("printing inside handleWebhookRequest")
}
// -->  Webhook loading
Shopify.Webhooks.Registry.addHandler("PRODUCTS_UPDATE", {
  path: "/webhooks",
  webhookHandler: handleWebhookRequest,
});

const app = express();
app.use(express.json());  // <-- to show case in plain text

app.get('/',async (req,res) => {
    if (typeof shops[req.query.shop] !== 'undefined'){
        res.send("Hello"); 
    } else {
        res.redirect(`/auth?shop=${req.query.shop}`);
    }
});

app.get('/auth', async (req,res)=>{
    const authRoute = await Shopify.Auth.beginAuth(req, res, req.query.shop, '/auth/callback',false);
    res.redirect(authRoute);
    console.log("ok in /auth")
});

app.get('/auth/callback', async (req,res)=>{

    try {
        const shopSession = await Shopify.Auth.validateAuthCallback(req, res,req.query,);
        shops[shopSession.shop] = shopSession;
        console.log("printing inside auth/callback")

// -- > Webhook Registration
        const response = await Shopify.Webhooks.Registry.register({
          path: '/webhooks',
          topic: 'PRODUCTS_UPDATE',
          accessToken: shopSession.accessToken,
          shop: shopSession.shop,
        });

        if (!response['PRODUCTS_UPDATE'].success) {
          console.log(
            `Failed to register PRODUCTS_UPDATE webhook: ${response.result}`
          );
        }

        res.redirect(`https://${shopSession.shop}/admin/apps/oath-node-1`);
        
// <---  Webhook Registration
    }  catch (error) {
    console.error(error); // in practice these should be handled more gracefully
    }
});

//------> Webhook Processing
app.post("/webhooks", async (req, res) => {
  try {
    await Shopify.Webhooks.Registry.process(req, res);
    console.log(`Webhook processed, returned status code 200`);
  } catch (error) {
    console.log(`Failed to process webhook: ${error}`);
    if (!res.headersSent) {
      res.status(500).send(error.message);
    }
  }
});


app.listen (port, ()=>{
    console.log(`Server is running at http://${host}:${port}`);
});

 

 

 

Full Error message:
 

 

HttpResponseError: Received an error response (400 Bad Request) from Shopify:
If you report this error, please include this id: 2b8157aa-9b10-4612-9779-54d9aa6b001a
    at HttpResponseError.ShopifyError [as constructor] (/Users/happysentient/Development/Testing/implementing-shopify-Oath-with-nodejs/node_modules/@shopify/shopify-api/dist/error.js:13:28)
    at new HttpResponseError (/Users/happysentient/Development/Testing/implementing-shopify-Oath-with-nodejs/node_modules/@shopify/shopify-api/dist/error.js:96:28)
    at HttpClient.<anonymous> (/Users/happysentient/Development/Testing/implementing-shopify-Oath-with-nodejs/node_modules/@shopify/shopify-api/dist/clients/http_client/http_client.js:244:43)
    at step (/Users/happysentient/Development/Testing/implementing-shopify-Oath-with-nodejs/node_modules/tslib/tslib.js:144:27)
    at Object.next (/Users/happysentient/Development/Testing/implementing-shopify-Oath-with-nodejs/node_modules/tslib/tslib.js:125:57)
    at fulfilled (/Users/happysentient/Development/Testing/implementing-shopify-Oath-with-nodejs/node_modules/tslib/tslib.js:115:62)
    at processTicksAndRejections (node:internal/process/task_queues:96:5) {
  response: {
    code: 400,
    statusText: 'Bad Request',
    body: {},
    headers: [Object: null prototype] {
      date: [Array],
      'content-type': [Array],
      'transfer-encoding': [Array],
      connection: [Array],
      'x-sorting-hat-podid': [Array],
      'x-sorting-hat-shopid': [Array],
      'referrer-policy': [Array],
      'x-frame-options': [Array],
      'x-shopid': [Array],
      'x-shardid': [Array],
      'cache-control': [Array],
      vary: [Array],
      'strict-transport-security': [Array],
      'set-cookie': [Array],
      'x-shopify-stage': [Array],
      'content-security-policy': [Array],
      'x-content-type-options': [Array],
      'x-download-options': [Array],
      'x-permitted-cross-domain-policies': [Array],
      'x-xss-protection': [Array],
      'x-dc': [Array],
      'x-request-id': [Array],
      'cf-cache-status': [Array],
      'expect-ct': [Array],
      server: [Array],
      'cf-ray': [Array],
      'alt-svc': [Array]
    }
  }
}

 

 
Reply 1 (1)

Nicholas_Babu
Shopify Partner
6 0 0

Having the same problem, but I have the right scopes

 

{state":"offline_3638636172083","isOnline":false,"scope":"write_products,read_orders,read_discounts,write_script_tags","accessToken":"shpua_701526b62fc4a2a5b93670dc74c8"}}

Did you manage to solve yours?