如何在OpenAPI中动态定义Stripe Event的data.object结构?
问题分析与解决方案
当前配置的核心问题
你定义的StripeEventObject中,object字段同时声明了type: object和$ref,这违反了OpenAPI规范——$ref会忽略所有同级属性,导致解析器无法正确识别data.object的结构,最终出现字段为空的情况。
修复步骤与动态定义方案
方案1:快速修复基础问题(兼容所有动态结构)
如果不需要精准校验data.object的具体字段,只需要确保能正常接收内容,可直接调整定义,允许data.object包含任意属性:
StripeEvent: type: object properties: api_version: type: string nullable: true object: type: string account: type: string nullable: true created: type: integer data: type: object properties: object: type: object additionalProperties: true # 允许任意类型的属性 id: type: string livemode: type: boolean pending_webhooks: type: integer request: type: object properties: id: type: string nullable: true idempotency_key: type: string nullable: true type: type: string
方案2:精准动态解析(结合事件类型)
如果需要根据type字段(如plan.created)匹配对应的data.object结构,可使用OpenAPI的discriminator实现类型关联:
- 先定义各事件对应的具体对象结构:
components: schemas: PlanObject: type: object properties: id: type: string object: type: string enum: ["plan"] active: type: boolean amount: type: integer amount_decimal: type: string billing_scheme: type: string created: type: integer currency: type: string interval: type: string interval_count: type: integer livemode: type: boolean metadata: type: object product: type: string usage_type: type: string # 其他plan相关字段... CustomerObject: type: object properties: id: type: string object: type: string enum: ["customer"] email: type: string name: type: string nullable: true # 其他customer相关字段...
- 修改
StripeEvent定义,通过discriminator关联事件类型与对象结构:
StripeEvent: type: object properties: api_version: type: string nullable: true object: type: string enum: ["event"] created: type: integer data: type: object properties: object: oneOf: - $ref: '#/components/schemas/PlanObject' - $ref: '#/components/schemas/CustomerObject' # 追加其他事件对应的对象结构 id: type: string livemode: type: boolean pending_webhooks: type: integer request: type: object properties: id: type: string nullable: true idempotency_key: type: string nullable: true type: type: string enum: ["plan.created", "customer.created"] # 对应事件类型 discriminator: propertyName: type mapping: plan.created: '#/components/schemas/PlanObject' customer.created: '#/components/schemas/CustomerObject'
这样当type为plan.created时,解析器会自动将data.object映射为PlanObject结构,既保证了校验准确性,又支持动态匹配。
内容的提问来源于stack exchange,提问作者nonus25
相关产品推荐
相关产品推荐

