Stripe发送一个看起来像这样的webhook
{
"created": 1326853478,
"livemode": false,
"id": "evt_00000000000000",
"type": "checkout.session.completed",
"object": "event",
"request": null,
"pending_webhooks": 1,
"api_version": "2016-07-06",
"data": {
"object": {
"id": "cs_00000000000000",
"object": "checkout.session",
"billing_address_collection": null,
"cancel_url": "https://example.com/cancel",
"client_reference_id": "ABC",
"customer": "DEF",
"customer_email": null,
"display_items": [
{
"amount": 1500,
"currency": "usd",
"custom": {
"description": "Comfortable cotton t-shirt",
"images": null,
"name": "T-shirt"
},
"quantity": 2,
"type": "custom"
}
],
"livemode": false,
"locale": null,
"payment_intent": "pi_00000000000000",
"payment_method_types": [
"card"
],
"submit_type": null,
"subscription": null,
"success_url": "https://example.com/success"
}
}
}
这是我的控制器接收它:
import { Controller, Post, Body, ValidationPipe, UsePipes } from '@nestjs/common';
import { CheckoutWebhookDto } from './checkout-webhook.dto';
@Controller('webhooks')
export class StripeWebhooksController {
@Post('checkout')
@UsePipes(new ValidationPipe({transform: true}))
async checkout(@Body() data: CheckoutWebhookDto) {
console.log("Output:", data)
return
}
}
和我当前的Dto
import { ValidateNested, IsNotEmpty } from 'class-validator';
import { Type } from 'class-transformer';
export class CheckoutWebhookObjectDto {
@IsNotEmpty()
readonly client_reference_id: string;
@IsNotEmpty()
readonly customer: string;
}
export class CheckoutWebhookDataDto {
@ValidateNested()
@Type(() => CheckoutWebhookObjectDto)
readonly object: CheckoutWebhookObjectDto;
}
export class CheckoutWebhookDto {
@ValidateNested()
@Type(() => CheckoutWebhookDataDto)
readonly data: CheckoutWebhookDataDto;
}
我想抽出
data.object.client_reference_id
和data.object.customer
唯一的方法是创建3个相互嵌套的Dto。
我很高兴可以将@Body('data')
缩短到2-但有一种方法可以拥有一个Dto,这样最终的数据对象就是:
{
client_reference_id: "ABC",
customer: "DEF"
}