【问题标题】:Shopify Webhook in NestJSNestJS 中的 Shopify Webhook
【发布时间】:2021-06-15 06:32:02
【问题描述】:

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

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

下面是文件

shopify-orders.service.ts

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

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

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 {}

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

【问题讨论】:

    标签: typescript shopify nestjs shopify-app shopify-api-node


    【解决方案1】:

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

    1.为节点安装 shopify 模块

       npm install --save shopify-api-node
    

    2。 第一次创建 Webhook

    shopify.service.ts

        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.接收 Webhook

    3.1 在你的 main.ts 中像这样使用 bodyparser

       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 在你的控制器中

       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');
       }
      }
    

    您将开始接收 webhook。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-11-05
      • 1970-01-01
      • 1970-01-01
      • 2016-05-12
      • 2015-03-28
      • 1970-01-01
      • 2021-05-13
      • 1970-01-01
      相关资源
      最近更新 更多