How to add WebHook authentication to Shopify

background

Shopify is a one-stop SaaS e-commerce service platform, headquartered in Ottawa, Canada, focusing on overseas brand building and sales channel management for cross-border e-commerce users. Provide technology and template for e-commerce sellers to build online stores, and manage all-channel marketing, sales, payment, logistics and other services.

Code implementation

Koa

If you want to dock with Shopify in Koa, do the following:

// This is the interface verification key you got from Shopify
const secret = 'xxxx';

const app = new Koa();

async function run() {
  // Other middleware use/app.use...

  app.use(async (ctx, next) => {
    const isShopify = ctx.request.path.startsWith('Set WebHook URL on Shopify');

    if(! isShopify) {return koaBody({
        multipart: true.formidable: {
          maxFileSize: 2000 * 1024 * 1024.// Set the maximum size of a file to be uploaded. The default size is 2 MB
        },
      })(ctx, next);
    } else {
      let str = ' ';

      await new Promise((resolve, reject) = > {
        try {
          ctx.req.on('data'.function(data: string) {
            str += data;
          });
          ctx.req.on('end'.function(chunk: string) {
            resolve(str);
          });
        } catch (e) {
          str = '{}'; reject(e); }});const buf = Buffer.from(str);
      const hash = crypto.createHmac('sha256', secret).update(buf).digest('base64');
      const isOK = hash === ctx.request.headers['x-shopify-hmac-sha256'];

      ctx.request.body = JSON.parse(str);

      if(! isOK) { ctx.status =403;
        ctx.body = 'Forbidden';
        return;
      }

      return awaitnext(); }})Copy the code

Nest

If you want to connect To Shopify in Nest, check out this article to get started:

I wrote earlier about adding WebHook validation to Stripe in NestJS. Because the basic process and steps in the early stage are exactly the same, I will not repeat them in this article. How to intercept the Response raw body and how to write an Interceptor will not be repeated here. Just follow the instructions in the other passage. The following focuses on how to handle encrypted content.

// This is the interface verification key you got from Shopify
const secret = 'xxxx';
// This is the Buffer returned by Shopify
const buf = '....'
// This is the single-check hash taken from the response header
const hash = request.headers['x-shopify-hmac-sha256'];

const isOK = hash === crypto.createHmac('sha256', secret).update(buf).digest('base64')

// false if isOK === false, true if normal Shopify notifications.
Import * as crypto from 'crypto'
Copy the code