首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >在NestJS中购物Webhook

在NestJS中购物Webhook
EN

Stack Overflow用户
提问于 2021-03-18 05:06:52
回答 1查看 512关注 0票数 3

我正在努力将shopify webhook连接到nestjs。尽管我制作了应用程序并连接到shopify并安装了该应用程序。

同时,我已经在我的nestjs应用程序中创建了端点,但是它没有反映来自shopify的任何东西

下面是一些文件

shopify-orders.service.ts

代码语言:javascript
复制
import "@babel/polyfill";
import { Injectable, BadRequestException, ServiceUnavailableException } from '@nestjs/common';
import "isomorphic-fetch";
import dotenv from "dotenv";
import Koa from 'koa';
const { default: createShopifyAuth } = require('@shopify/koa-shopify-auth');
import { default as Shopify, ApiVersion } from '@shopify/shopify-api';
const { verifyRequest} = require('@shopify/koa-shopify-auth');
// const { default: Shopify, ApiVersion } = require('@shopify/shopify-api');
const Router = require('koa-router');
import {receiveWebhook, registerWebhook} from '@shopify/koa-shopify-webhooks';
const session = require('koa-session');
const app = new Koa();
const router = new Router();

@Injectable()
export class ShopifyOrdersService {
    constructor() {}

    public ShopifyApiCalls = () => {
        const app = new Koa();
        const router = new Router();

    const constport = parseInt(process.env.PORT, 10) || 3000;
    const dev = process.env.NODE_ENV !== "production";
    const { SHOPIFY_API_SECRET, SHOPIFY_API_KEY, SCOPES } = process.env;
    app.use(
        createShopifyAuth({ 
            apiKey: SHOPIFY_API_KEY, 
            secret: SHOPIFY_API_SECRET,
            scopes : [SCOPES],

            async afterAuth(ctx) {
                const { shop, accessToken} = ctx.state.shopify;
                  const handleWebhookRequest = async (topic: string, shop: string, webhookRequestBody: string) => {
        // this handler is triggered when a webhook is sent by the Shopify platform to your application
      }

                const registration = await Shopify.Webhooks.Registry.register({
                    shop,
                    accessToken,
                    path: '/webhooks/orders',
                    topic: 'ORDERS_CREATE', 
                    webhookHandler: handleWebhookRequest,
                })
                if (registration.success) {
                    console.log('Successfully registered webhook!');
                  } else {
                    console.log('Failed to register webhook', registration.result);
                  }

                ctx.redirect(`/?shop=${shop}`);

            }
        })
    )

    app.use(
        receiveWebhook({
            path:'/webhooks/orders',
            secret: SHOPIFY_API_SECRET,
            onReceived(ctx) {
                console.log('received webhook: ',ctx.state.webhook);
            },
        }),
    );
    app.use(verifyRequest());

    app.use(ctx => {
    }); 
}
}

shopify-orders.controller.ts

代码语言:javascript
复制
import "@babel/polyfill";
import {   BadRequestException,
    Body,
    Controller,
    Get,
    Headers,
    HttpCode,
    HttpStatus,
    Post,
    Query, } from '@nestjs/common';
import { ShopifyOrdersService } from './shopify-orders.service';


@Controller('webhooks')
export class ShopifyOrdersController {
    public constructor(
        private readonly shopifyOrdersService: ShopifyOrdersService
    ) {}

    @Get('orders')
    getHello(): any {
        return this.shopifyOrdersService.ShopifyApiCalls();
    }


}

shopify-orders.module.ts

代码语言:javascript
复制
import { Module } from '@nestjs/common';
import { ShopifyOrdersController } from './shopify-orders.controller';
import { ShopifyOrdersService } from './shopify-orders.service';
import { ApiCallsModule } from '../api-calls/api-calls.module'

@Module({
  imports: [
    ApiCallsModule
  ],
  controllers: [ShopifyOrdersController],
  providers: [ShopifyOrdersService]
})
export class ShopifyOrdersModule {}

我不知道我错过了什么,谢谢

EN

回答 1

Stack Overflow用户

发布于 2021-05-24 21:17:36

您正在使用KOA中间件,但我的答案是没有koa,希望它能有所帮助。

1.为节点安装购物模块

代码语言:javascript
复制
   npm install --save shopify-api-node

2.首次创建Webhook

shopify.service.ts

代码语言:javascript
复制
    const shopify = new Shopify({
       shopName: shop_name,
       accessToken: access_token,
    });
    
    // Create Webhook
    await shopify.webhook.create({
      topic: 'YOUR_WEBHOOK_EVENT',
      format: 'json',
      address: 'YOUR_URL_FOR_WEBHOOK',
      });

3.接收Webhooks

3.1在main.ts中使用bodyparser,如下所示

代码语言:javascript
复制
   app.use(
     json({
     verify: (req: any, res, buf, encoding) => {
   
     if (req.headers['x-shopify-hmac-sha256']) {
       req.rawBody = buf.toString(encoding || 'utf8');
     }
    return true;
  },
}),

);

3.2在您的控制器中

代码语言:javascript
复制
   import * as crypto from 'crypto';

   @Post('YOUR_WEBHOOK_URL')
   async webhookHandle(@Req() req: any) {
   const hmacHeader = req.get('X-Shopify-Hmac-Sha256');
   const hash = crypto.createHmac(
    'sha256',
    'SHOPIFY_API_SECRET',
   ).update(req.rawBody).digest('base64');
   if (hash === hmacHeader) {
   console.log('Notification Requested from Shopify received');
   } else {
   console.log('There is something wrong with this webhook');
   }
  }

你将开始接收网络钩子。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/66681238

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档