openapi: 3.1.0
info:
  title: BloomCore API - Payment Webhooks
  version: 1.1.0
  description: |
    Подписанные webhooks `payment.received` и `payment.refunded` с финансовой операцией
    и обязательным snapshot заказа.
    Все CRM `id` и `*_id` являются UUID; внутренние bigint ID не отправляются. Payload
    содержит финансовые и фискальные данные. Проверяйте HMAC до JSON parsing,
    ограничивайте доступ и не записывайте полное тело события в открытые логи.
servers:
  - url: https://{tenant_subdomain}.crm.flowers/api/v1
    variables:
      tenant_subdomain:
        default: demo
        description: Поддомен магазина.
paths: {}
webhooks:
  paymentReceived:
    post:
      summary: Получена оплата заказа
      description: |
        Событие содержит только payment type, положительную сумму и связанный order snapshot.
        Refund публикуется отдельным событием и не должен интерпретироваться как
        `payment.received`. Получатель дедуплицирует delivery по `event_id`.
      parameters:
        - $ref: '#/components/parameters/webhookEvent'
        - $ref: '#/components/parameters/webhookEventId'
        - $ref: '#/components/parameters/webhookDeliveryId'
        - $ref: '#/components/parameters/webhookTimestamp'
        - $ref: '#/components/parameters/webhookSignature'
      requestBody:
        required: true
        content:
          application/json:
            schema: {$ref: '#/components/schemas/PaymentReceivedWebhookEnvelope'}
            example:
              event: payment.received
              event_id: 019f58c6-0913-79eb-aed9-a20d0b255c9f
              created_at: '2026-07-18T09:00:00+00:00'
              payload_schema_version: crm.webhook.v1
              tenant_id: 019f58c1-cc38-75aa-afd8-bdf3dc77fa2c
              store_id: 019f58c1-e3da-72f7-baad-f67b453fe468
              retry_count: 0
              data:
                payment:
                  id: 019f58c6-170e-7ca0-bc88-bba4fa57f195
                  tenant_id: 019f58c1-cc38-75aa-afd8-bdf3dc77fa2c
                  store_id: 019f58c1-e3da-72f7-baad-f67b453fe468
                  order_id: 019f58c5-15ce-75fb-b544-07a26ad3cab4
                  customer_id: 019f58c3-0180-7b38-a4c0-049096c70ca9
                  payment_method_id: 019f58c6-2224-7a7e-a7ac-d352b21ccb3f
                  cash_register_id: 019f58c6-2d06-7f55-892c-64d1196cba89
                  cash_shift_id: 019f58c6-3670-7c57-b7ba-4d8e26bd76cd
                  user_id: 019f58c4-46f8-7ed3-a118-b8c14ca3d90c
                  type: payment
                  status: succeeded
                  fiscal_status: pending
                  amount: '5000.00'
                  currency_code: RUB
                  paid_at: '2026-07-18T08:59:58+00:00'
                  refunded_at: null
                  provider: terminal
                  external_id: ext-payment-125
                  reference: receipt-125
                  created_at: '2026-07-18T08:59:58+00:00'
                  updated_at: '2026-07-18T08:59:58+00:00'
                order:
                  id: 019f58c5-15ce-75fb-b544-07a26ad3cab4
                  number: FL-2026-00125
                  tenant_id: 019f58c1-cc38-75aa-afd8-bdf3dc77fa2c
                  store_id: 019f58c1-e3da-72f7-baad-f67b453fe468
                  customer_id: 019f58c3-0180-7b38-a4c0-049096c70ca9
                  recipient_customer_id: null
                  manager_id: 019f58c4-46f8-7ed3-a118-b8c14ca3d90c
                  florist_id: null
                  courier_id: null
                  source: crm
                  type: delivery
                  status: paid
                  payment_status: paid
                  delivery_status: planned
                  customer_name: Анна Петрова
                  customer_phone: '+79990000000'
                  customer_email: anna@example.test
                  recipient_same_as_customer: true
                  recipient_name: Анна Петрова
                  recipient_phone: '+79990000000'
                  is_surprise: false
                  do_not_call_recipient: false
                  desired_at: '2026-07-19T12:00:00+00:00'
                  subtotal: '7500.00'
                  discount_total: '0.00'
                  delivery_price: '0.00'
                  total: '7500.00'
                  paid_total: '7500.00'
                  refunded_total: '0.00'
                  payment_due: '0.00'
                  completed_at: null
                  cancelled_at: null
                  created_at: '2026-07-18T08:00:00+00:00'
                  updated_at: '2026-07-18T08:59:58+00:00'
                  items: []
      responses:
        '200': {description: Событие принято интеграцией.}
  paymentRefunded:
    post:
      summary: Выполнен возврат оплаты заказа
      description: |
        Событие создается отдельно для каждой успешной проводки возврата. При составном
        возврате одного заказа получатель может получить несколько событий с разными
        `refund.id`. `original_payment_id` содержит UUID исходной оплаты только для
        source-bound возврата; для возврата без однозначной привязки значение равно null.
        Внешние идентификаторы провайдера, reference и metadata намеренно не публикуются.
        Получатель дедуплицирует delivery по `event_id`.
      parameters:
        - $ref: '#/components/parameters/webhookRefundEvent'
        - $ref: '#/components/parameters/webhookEventId'
        - $ref: '#/components/parameters/webhookDeliveryId'
        - $ref: '#/components/parameters/webhookTimestamp'
        - $ref: '#/components/parameters/webhookSignature'
      requestBody:
        required: true
        content:
          application/json:
            schema: {$ref: '#/components/schemas/PaymentRefundedWebhookEnvelope'}
      responses:
        '200': {description: Событие принято интеграцией.}
components:
  parameters:
    webhookEvent:
      name: X-CRM-Webhook-Event
      in: header
      required: true
      schema: {type: string, const: payment.received}
    webhookRefundEvent:
      name: X-CRM-Webhook-Event
      in: header
      required: true
      schema: {type: string, const: payment.refunded}
    webhookEventId:
      name: X-CRM-Webhook-Id
      in: header
      required: true
      schema: {type: string, format: uuid}
    webhookDeliveryId:
      name: X-CRM-Webhook-Delivery
      in: header
      required: true
      schema: {type: string, format: uuid}
    webhookTimestamp:
      name: X-CRM-Webhook-Timestamp
      in: header
      required: true
      schema: {type: string, pattern: '^[0-9]{10}$'}
    webhookSignature:
      name: X-CRM-Webhook-Signature
      in: header
      required: true
      schema: {type: string, pattern: '^sha256=[a-f0-9]{64}$'}
  schemas:
    PaymentReceivedWebhookEnvelope:
      type: object
      additionalProperties: false
      required: [event, event_id, created_at, payload_schema_version, tenant_id, store_id, retry_count, data]
      properties:
        event: {type: string, const: payment.received}
        event_id:
          type: string
          format: uuid
        created_at: {type: string, format: date-time}
        payload_schema_version: {type: string, const: crm.webhook.v1}
        tenant_id:
          type: string
          format: uuid
        store_id:
          type: string
          format: uuid
        retry_count: {type: integer, minimum: 0}
        data: {$ref: '#/components/schemas/PaymentReceivedWebhookData'}
    PaymentReceivedWebhookData:
      type: object
      additionalProperties: false
      required: [payment, order]
      properties:
        payment: {$ref: '#/components/schemas/PaymentWebhookPayment'}
        order: {$ref: './order-webhooks.v1.yaml#/components/schemas/OrderWebhookOrder'}
    PaymentWebhookPayment:
      type: object
      additionalProperties: false
      required: [id, tenant_id, store_id, order_id, customer_id, payment_method_id, cash_register_id, cash_shift_id, user_id, type, status, fiscal_status, amount, currency_code, paid_at, refunded_at, provider, external_id, reference, created_at, updated_at]
      properties:
        id:
          type: string
          format: uuid
        tenant_id:
          type: string
          format: uuid
        store_id:
          type: string
          format: uuid
        order_id:
          type: string
          format: uuid
        customer_id:
          type: [string, 'null']
          format: uuid
        payment_method_id:
          type: [string, 'null']
          format: uuid
        cash_register_id:
          type: [string, 'null']
          format: uuid
        cash_shift_id:
          type: [string, 'null']
          format: uuid
        user_id:
          type: [string, 'null']
          format: uuid
        type: {type: string, const: payment}
        status: {type: string, enum: [pending, succeeded, failed, cancelled]}
        fiscal_status: {type: string, enum: [not_required, pending, sent, succeeded, failed]}
        amount: {type: string, pattern: '^[0-9]+\.[0-9]{2}$'}
        currency_code: {type: string, pattern: '^[A-Z]{3}$'}
        paid_at: {type: [string, 'null'], format: date-time}
        refunded_at: {type: [string, 'null'], format: date-time}
        provider: {type: [string, 'null']}
        external_id:
          type: [string, 'null']
          description: Не является CRM UUID; внешний идентификатор платежного провайдера.
        reference: {type: [string, 'null']}
        created_at: {type: [string, 'null'], format: date-time}
        updated_at: {type: [string, 'null'], format: date-time}
    PaymentRefundedWebhookEnvelope:
      type: object
      additionalProperties: false
      required: [event, event_id, created_at, payload_schema_version, tenant_id, store_id, retry_count, data]
      properties:
        event: {type: string, const: payment.refunded}
        event_id:
          type: string
          format: uuid
        created_at: {type: string, format: date-time}
        payload_schema_version: {type: string, const: crm.webhook.v1}
        tenant_id:
          type: string
          format: uuid
        store_id:
          type: string
          format: uuid
        retry_count: {type: integer, minimum: 0}
        data: {$ref: '#/components/schemas/PaymentRefundedWebhookData'}
    PaymentRefundedWebhookData:
      type: object
      additionalProperties: false
      required: [refund, order]
      properties:
        refund: {$ref: '#/components/schemas/PaymentWebhookRefund'}
        order: {$ref: './order-webhooks.v1.yaml#/components/schemas/OrderWebhookOrder'}
    PaymentWebhookRefund:
      type: object
      additionalProperties: false
      required: [id, tenant_id, store_id, order_id, customer_id, payment_method_id, cash_register_id, cash_shift_id, user_id, original_payment_id, type, status, fiscal_status, amount, currency_code, refunded_at, created_at, updated_at]
      properties:
        id:
          type: string
          format: uuid
        tenant_id:
          type: string
          format: uuid
        store_id:
          type: string
          format: uuid
        order_id:
          type: string
          format: uuid
        customer_id:
          type: [string, 'null']
          format: uuid
        payment_method_id:
          type: [string, 'null']
          format: uuid
        cash_register_id:
          type: [string, 'null']
          format: uuid
        cash_shift_id:
          type: [string, 'null']
          format: uuid
        user_id:
          type: [string, 'null']
          format: uuid
        original_payment_id:
          type: [string, 'null']
          format: uuid
          description: UUID исходной успешной оплаты для source-bound возврата или null.
        type: {type: string, const: refund}
        status: {type: string, const: succeeded}
        fiscal_status: {type: string, enum: [not_required, pending, sent, succeeded, failed]}
        amount: {type: string, pattern: '^[0-9]+\\.[0-9]{2}$'}
        currency_code: {type: string, pattern: '^[A-Z]{3}$'}
        refunded_at: {type: string, format: date-time}
        created_at: {type: [string, 'null'], format: date-time}
        updated_at: {type: [string, 'null'], format: date-time}
