Getting a NodeResponse error when trying to verify webhook in Shopify Remix app

140 views Asked by At

I am trying to authenticate a webhook in Shopify using Remix. I have successfully created a webhook for 'checkouts/create' using the REST API method below and I can see it is firing my webhook route in Remix.

const res = await axios.post(
    `https://${shop}/admin/api/2023-10/webhooks.json`,
     {
       webhook: {
         topic: 'checkouts/create',
         address: `${process.env.APP_URL}/api/create-checkout`,
         format: 'json',
       },
     },
     {
       headers: {
         'X-Shopify-Access-Token': accessToken,
         'Content-Type': 'application/json',
       },
     }
);

However when I try and do the following to verify this webhook...

export async function action({ request }) {
  console.log('webhook hit');

  if (request.method === 'POST') {

    try {
      const { topic, payload, webhookId, shop } = await authenticate.webhook(request);
      console.log('SUCCESS');
    } catch (err) {
      console.log('ERROR: ', err);
    }

  }

I get this error:

ERROR: NodeResponse [Response] { 
  size: 0, [Symbol(Body internals)]: {   
    body: null,
    type: null,
    size: 0,
    boundary: null,
    disturbed: false,
    error: null 
  }, 
  [Symbol(Response internals)]: {   
    url: undefined,   
    status: 400,   
    statusText: 'Bad Request',   
    headers: {},   
    counter: 0,   
    highWaterMark: undefined 
  }
}

I have also tried not using the shopify authenticate.webhook(request) method and to use crypto to do the following, but the hmac values never match:

const url = new URL(request.url);

const hmacHeader = request.headers.get('X-Shopify-Hmac-SHA256');
const data = await request.json();
const requestStore = request.headers.get('x-shopify-shop-domain');

const calculated_hmac = crypto.createHmac('sha256', process.env.SECRET_KEY).update(JSON.stringify(data)).digest('base64');

return hmacHeader == calculated_hmac;

I know the secret key being used is correct because it is working on app install to verify the first hmac. Just isn't working on the webhook verification. I think it is probably down to the data value being used but can't see how else to stringify it and pass it in from the Remix route.

Any help would be greatly appreciated! Thank you.

0

There are 0 answers