怎么添加對Shopify 的WebHook 驗證
背景介紹
Shopify 是一家一站式SaaS 模式的電商服務(wù)平臺弛随,總部位于加拿大首都渥太華,專注于為跨境電商用戶提供海外品牌建立及銷售渠道管理镇辉。為電商賣家提供搭建網(wǎng)店的技術(shù)和模版慢显,管理全渠道的營銷寺滚、售賣、支付、物流等服務(wù)腋颠。
代碼實現(xiàn)
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('設(shè)置在Shopify 上的WebHook url');
if (!isShopify) {
return koaBody({
multipart: true,
formidable: {
maxFileSize: 2000 * 1024 * 1024, // 設(shè)置上傳文件大小最大限制务热,默認(rèn)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, 則可以參照下面這篇文章進行前期設(shè)置:
我前面寫過一篇在NestJS 中添加對Stripe 的WebHook 驗證忆嗜。因為前期的基本流程和步驟是完全一樣的,我在這篇中就不再贅述了崎岂。前期如何截獲Response raw body 相關(guān)的內(nèi)容及怎么寫一個Interceptor 在這就不再重復(fù)了捆毫。參照另外一篇的內(nèi)容照做就可以了。下面重點講怎么處理加密內(nèi)容冲甘。
// 這是你從Shopify 上得到的接口校驗密鑰
const secret = 'xxxx';
// 這是Shopify 響應(yīng)返回的Buffer 體
const buf = '....'
// 這是從響應(yīng)頭里取出來的單次校驗哈希
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'