-
Notifications
You must be signed in to change notification settings - Fork 0
/
process-webhook.handler.ts
59 lines (49 loc) · 1.74 KB
/
process-webhook.handler.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
import { Inject } from '@nestjs/common';
import { ConfigService } from '@nestjs/config';
import { CommandHandler, ICommandHandler } from '@nestjs/cqrs';
import { OrderInjectionModuleToken } from 'src/orders/application/order-injection-module.token';
import { OrderQuery } from 'src/orders/domain/order/order-query';
import { PaymentFactory } from 'src/payment/domain/factory';
import Stripe from 'stripe';
import { ProcessWebhookCommand } from './process-webhook.command';
@CommandHandler(ProcessWebhookCommand)
export class ProcessWebhookCommandHandler
implements ICommandHandler<ProcessWebhookCommand, void>
{
constructor(
@Inject(OrderInjectionModuleToken.ORDER_QUERY)
private readonly orderQuery: OrderQuery,
private readonly configService: ConfigService,
private readonly paymentFactory: PaymentFactory,
) {}
private config: Stripe.StripeConfig = null;
private stripe: Stripe = new Stripe(
this.configService.get('STRIPE_SK_TEST'),
this.config,
);
async execute(command: ProcessWebhookCommand): Promise<any> {
const event = this.stripe.webhooks.constructEvent(
command.payload,
command.signature,
this.configService.get('STRIPE_WEBHOOK_SECRET'),
);
const paymentIntent: any = event.data.object;
const order = await this.orderQuery.findOrderByPaymentIntentId(
paymentIntent.id,
);
if (!order) return;
const payment = this.paymentFactory.create(order.id);
switch (event.type) {
case 'payment_intent.succeeded':
payment.succeed();
payment.commit();
break;
case 'payment_intent.failed':
payment.failed();
payment.commit();
break;
default:
console.log(`Unhandled event type ${event.type}`);
}
}
}