动态

详情 返回 返回

在NestJS 中添加對Shopify 的WebHook 驗證 - 动态 详情

怎麼添加對Shopify 的WebHook 驗證

背景介紹

Shopify 是一家一站式SaaS 模式的電商服務平台,總部位於加拿大首都渥太華,專注於為跨境電商用户提供海外品牌建立及銷售渠道管理。為電商賣家提供搭建網店的技術和模版,管理全渠道的營銷、售賣、支付、物流等服務。

代碼實現

Koa

如果你是想在Koa 中對接Shopify, 則可以參照下面的做法:

// 這是你從Shopify 上得到的接口校驗密鑰
const secret = 'xxxx';

const app = new Koa();

async function run() {
  // 其他的中間件的使用 / app.use...

  app.use(async (ctx, next) => {
    const isShopify = ctx.request.path.startsWith('設置在Shopify 上的WebHook url');

    if (!isShopify) {
      return koaBody({
        multipart: true,
        formidable: {
          maxFileSize: 2000 * 1024 * 1024, // 設置上傳文件大小最大限制,默認2M
        },
      })(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 await next();
    }
  })

Nest

如果你是想在Nest 中對接Shopify, 則可以參照下面這篇文章進行前期設置:

我前面寫過一篇在NestJS 中添加對Stripe 的WebHook 驗證。因為前期的基本流程和步驟是完全一樣的,我在這篇中就不再贅述了。前期如何截獲Response raw body 相關的內容及怎麼寫一個Interceptor 在這就不再重複了。參照另外一篇的內容照做就可以了。下面重點講怎麼處理加密內容。

// 這是你從Shopify 上得到的接口校驗密鑰
const secret = 'xxxx';
// 這是Shopify 響應返回的Buffer 體
const buf = '....'
// 這是從響應頭裏取出來的單次校驗哈希
const hash = request.headers['x-shopify-hmac-sha256'];

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

// 如果isOK === false 則不對,如果是正常的Shopify 通知則為true.
// crypto 是原生Node 自帶的庫 import * as crypto from 'crypto'

Add a new 评论

Some HTML is okay.