import { HttpStatus, Inject } from '@midwayjs/core'; import { Controller, Post, Body, Headers, Get, Query, } from '@midwayjs/decorator'; import { Context } from '@midwayjs/koa'; import * as crypto from 'crypto'; import { WpProductService } from '../service/wp_product.service'; import { WPService } from '../service/wp.service'; import { SiteService } from '../service/site.service'; import { OrderService } from '../service/order.service'; @Controller('/webhook') export class WebhookController { private secret = 'YOONE24kd$kjcdjflddd'; @Inject() private readonly wpProductService: WpProductService; @Inject() private readonly wpApiService: WPService; @Inject() private readonly orderService: OrderService; @Inject() ctx: Context; @Inject() private readonly siteService: SiteService; // 中文注释:移除配置中的站点数组,来源统一改为数据库 @Get('/') async test() { return 'webhook'; } @Post('/woocommerce') async handleWooWebhook( @Body() body: any, @Query('siteId') siteId: string, @Headers() header: any ) { const signature = header['x-wc-webhook-signature']; const topic = header['x-wc-webhook-topic']; const source = header['x-wc-webhook-source']; // 中文注释:从数据库获取站点配置 const site = await this.siteService.get(Number(siteId), true); if (!site || !source.includes(site.wpApiUrl)) { console.log('domain not match'); return { code: HttpStatus.BAD_REQUEST, success: false, message: 'domain not match', }; } if (!signature) { return { code: HttpStatus.BAD_REQUEST, success: false, message: 'Signature missing', }; } const rawBody = this.ctx.request.rawBody; const hash = crypto .createHmac('sha256', this.secret) .update(rawBody) .digest('base64'); try { if (hash === signature) { switch (topic) { case 'product.created': case 'product.updated': // 变体更新 if (body.type === 'variation') { const variation = await this.wpApiService.getVariation( site, body.parent_id, body.id ); this.wpProductService.syncVariation( siteId, body.parent_id, variation ); break; } const variations = body.type === 'variable' ? await this.wpApiService.getVariations(site, body.id) : []; await this.wpProductService.syncProductAndVariations( site.id, body, variations ); break; case 'product.deleted': await this.wpProductService.delWpProduct(site.id, body.id); break; case 'order.created': case 'order.updated': await this.orderService.syncSingleOrder(siteId, body); break; case 'order.deleted': break; case 'customer.created': break; case 'customer.updated': break; case 'customer.deleted': break; default: console.log('Unhandled event:', body.event); } return { code: 200, success: true, message: 'Webhook processed successfully', }; } else { return { code: 403, success: false, message: 'Webhook verification failed', }; } } catch (error) { console.log(error); } } }