当前位置: 首页 > 后端技术 > Node.js

NestJS为Shopify添加WebHook验证

时间:2023-04-03 12:42:30 Node.js

如何为Shopify海外品牌建设和销售渠道管理添加WebHook验证。为电商卖家提供搭建网店的技术和模板,管理全渠道营销、销售、支付、物流等服务。实现Koa的代码如果你想在Koa中连接Shopify,可以参考下面的方法://这是你从Shopify获取的接口验证密钥constsecret='xxxx';constapp=newKoa();asyncfunctionrun(){//使用其他中间件/app.use...app.use(async(ctx,next)=>{constisShopify=ctx.request.path.startsWith('setonShopifyWebHookurl');if(!isShopify){returnkoaBody({multipart:true,formidable:{maxFileSize:2000*1024*1024,//设置最大上传文件大小限制,默认2M},})(ctx,next);}else{letstr='';awaitnewPromise((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);}});constbuf=Buffer.from(str);consthash=crypto.createHmac('sha256',secret).update(buf).digest('base64');constisOK=hash===ctx.request.headers['x-shopify-hmac-sha256'];ctx.request.body=JSON.parse(str);如果(!isOK){ctx.status=403;ctx.body='禁止';返回;返回等待下一个();}})Nest如果你想在Nest中连接Shopify,可以参考下面这篇文章进行前置设置:我在NestJS中为Stripe添加WebHook验证之前写了一篇文章,因为前面的基本流程和步骤正是同理,这里不再赘述。前期如何拦截Responserawbody相关的内容,如何写一个Interceptor,这里不再赘述。按照另一篇文章的内容去做就好了。下面重点介绍如何处理加密内容。//这是你从Shopify得到的接口验证密钥constsecret='xxxx';//这是Shopify的响应返回的Bufferbodyconstbuf='....'//这是从响应头中取出来的单验证哈希consthash=request.headers['x-shopify-hmac-sha256'];constisOK=hash===crypto.createHmac('sha256',secret).update(buf).digest('base64')//IfisOK===false不为真,如果是普通的Shopify通知,则为真。//crypto是原生Node自带的库import*ascryptofrom'crypto'