openapi: 3.1.0
info:
  title: railpay API
  version: 1.0.0
  summary: Pasarela de pagos cripto para comercios.
  description: >-
    API p�blica para que un comercio cree pagos, consulte estados y configure un webhook firmado. No
    documenta el panel, la autenticaci�n de usuarios ni operaciones internas.
  contact:
    name: railpay
    url: https://railpay.kabasys.com
servers:
  - url: https://railpay-api.kabasys.com
    description: Producción
  - url: http://localhost:3000
    description: Desarrollo local
security:
  - apiKeyAuth: []
tags:
  - name: Public
    description: Sin autenticación.
  - name: Payments
    description: Órdenes, estado y eventos on-chain.
  - name: Webhooks
    description: Endpoints IPN y entregas.
paths:
  /v1/status:
    get:
      tags:
        - Public
      summary: Estado de la API
      operationId: getV1Status
      responses:
        '200':
          description: OK
          content:
            application/json:
              schema:
                type: object
                required:
                  - status
                  - api
                  - time
                properties:
                  status:
                    type: string
                    const: ok
                  api:
                    type: string
                    const: v1
                  time:
                    type: string
                    format: date-time
  /v1/currencies:
    get:
      tags:
        - Public
      summary: Activos, redes y mínimos
      operationId: getV1Currencies
      responses:
        '200':
          description: Catálogo de monedas
          content:
            application/json:
              schema:
                type: object
                required:
                  - currencies
                properties:
                  currencies:
                    type: array
                    items:
                      $ref: '#/components/schemas/Currency'
        '429':
          $ref: '#/components/responses/RateLimited'
  /v1/min-amount:
    get:
      tags:
        - Public
      summary: Mínimo por moneda o por activo y red
      operationId: getV1MinAmount
      parameters:
        - name: currency
          in: query
          description: Código NOWPayments, por ejemplo `usdttrc20`.
          schema:
            type: string
        - name: asset
          in: query
          schema:
            $ref: '#/components/schemas/Asset'
        - name: network
          in: query
          schema:
            $ref: '#/components/schemas/Network'
      responses:
        '200':
          description: Mínimo aplicable
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/MinAmount'
        '400':
          $ref: '#/components/responses/BadRequest'
  /v1/estimate:
    get:
      tags:
        - Public
      summary: Estima comisión, neto y monto cripto
      operationId: getV1Estimate
      description: >-
        Usa la tasa vigente al momento de la consulta. El pago se congela con su propia tasa al
        crearse.
      parameters:
        - name: amountCents
          in: query
          required: true
          schema:
            type: integer
            minimum: 1
            maximum: 100000000
        - name: asset
          in: query
          required: true
          schema:
            $ref: '#/components/schemas/Asset'
        - name: network
          in: query
          required: true
          schema:
            $ref: '#/components/schemas/Network'
      responses:
        '200':
          description: Estimación
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/Estimate'
        '400':
          $ref: '#/components/responses/BadRequest'
  /v1/payments:
    post:
      tags:
        - Payments
      summary: Crea un pago
      operationId: postV1Payments
      description: |
        Requiere `Idempotency-Key`. La key debe ser única por comercio y cuerpo;
        si se reutiliza con otro cuerpo devuelve 409. El `mode` lo decide la API
        key, no el cuerpo. Scopes: `payments:write`.
      security:
        - apiKeyAuth: []
      parameters:
        - $ref: '#/components/parameters/IdempotencyKey'
      requestBody:
        required: true
        content:
          application/json:
            schema:
              $ref: '#/components/schemas/CreatePayment'
      responses:
        '201':
          description: Pago creado
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/Payment'
        '400':
          $ref: '#/components/responses/BadRequest'
        '401':
          $ref: '#/components/responses/Unauthorized'
        '409':
          $ref: '#/components/responses/Conflict'
        '429':
          $ref: '#/components/responses/RateLimited'
        '503':
          description: Sin direcciones disponibles para ese activo y red
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/Error'
    get:
      tags:
        - Payments
      summary: Lista pagos con cursor
      operationId: getV1Payments
      description: 'Orden descendente por id. Scopes: `payments:read`.'
      security:
        - apiKeyAuth: []
      parameters:
        - name: limit
          in: query
          schema:
            type: integer
            minimum: 1
            maximum: 100
            default: 20
        - $ref: '#/components/parameters/Cursor'
      responses:
        '200':
          description: Página de pagos
          content:
            application/json:
              schema:
                type: object
                required:
                  - items
                  - nextCursor
                properties:
                  items:
                    type: array
                    items:
                      $ref: '#/components/schemas/Payment'
                  nextCursor:
                    type:
                      - string
                      - 'null'
                    format: uuid
        '401':
          $ref: '#/components/responses/Unauthorized'
  /v1/payments/{id}:
    get:
      tags:
        - Payments
      summary: Detalle de un pago
      operationId: getV1PaymentsId
      description: 'Incluye eventos on-chain. Scopes: `payments:read`.'
      security:
        - apiKeyAuth: []
      parameters:
        - $ref: '#/components/parameters/PaymentId'
      responses:
        '200':
          description: Pago
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/PaymentDetail'
        '404':
          $ref: '#/components/responses/NotFound'
  /v1/payments/{id}/events:
    get:
      tags:
        - Payments
      summary: Eventos on-chain del pago
      operationId: getV1PaymentsIdEvents
      security:
        - apiKeyAuth: []
      parameters:
        - $ref: '#/components/parameters/PaymentId'
      responses:
        '200':
          description: Eventos
          content:
            application/json:
              schema:
                type: object
                required:
                  - events
                properties:
                  events:
                    type: array
                    items:
                      $ref: '#/components/schemas/PaymentEvent'
        '404':
          $ref: '#/components/responses/NotFound'
  /v1/sandbox/payments/{id}/pay:
    post:
      tags:
        - Payments
      summary: Simula la confirmación de un pago TEST
      operationId: postV1SandboxPaymentsIdPay
      description: |
        Solo acepta pagos `TEST` y API keys `TEST`. No mueve fondos. Si no
        envías `amount`, usa el monto exacto esperado. Scopes: `payments:write`.
      security:
        - apiKeyAuth: []
      parameters:
        - $ref: '#/components/parameters/PaymentId'
      requestBody:
        required: false
        content:
          application/json:
            schema:
              type: object
              properties:
                amount:
                  type: string
                  pattern: ^\d+(\.\d{1,8})?$
                  example: '15'
      responses:
        '201':
          description: Pago liquidado
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/Payment'
        '400':
          $ref: '#/components/responses/BadRequest'
        '403':
          $ref: '#/components/responses/Forbidden'
  /v1/webhook-endpoints:
    get:
      tags:
        - Webhooks
      summary: Lista endpoints IPN
      operationId: getV1WebhookEndpoints
      description: 'Scopes: `webhooks:read`.'
      security:
        - apiKeyAuth: []
      parameters:
        - name: mode
          in: query
          schema:
            type: string
            enum:
              - TEST
              - LIVE
      responses:
        '200':
          description: Endpoints
          content:
            application/json:
              schema:
                type: array
                items:
                  $ref: '#/components/schemas/WebhookEndpoint'
    post:
      tags:
        - Webhooks
      summary: Crea un endpoint IPN
      operationId: postV1WebhookEndpoints
      description: |
        Solo https público. El `secret` se devuelve una vez. Scopes:
        `webhooks:write`.
      security:
        - apiKeyAuth: []
      requestBody:
        required: true
        content:
          application/json:
            schema:
              $ref: '#/components/schemas/CreateWebhookEndpoint'
      responses:
        '201':
          description: Endpoint con secreto
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/WebhookEndpointCreated'
        '400':
          $ref: '#/components/responses/BadRequest'
  /v1/webhook-endpoints/deliveries:
    get:
      tags:
        - Webhooks
      summary: Entregas recientes
      operationId: getV1WebhookEndpointsDeliveries
      description: 'Scopes: `webhooks:read`.'
      security:
        - apiKeyAuth: []
      parameters:
        - name: limit
          in: query
          schema:
            type: integer
            minimum: 1
            maximum: 100
            default: 50
        - name: mode
          in: query
          schema:
            type: string
            enum:
              - TEST
              - LIVE
      responses:
        '200':
          description: Entregas
          content:
            application/json:
              schema:
                type: array
                items:
                  $ref: '#/components/schemas/WebhookDelivery'
  /v1/webhook-endpoints/{id}:
    patch:
      tags:
        - Webhooks
      summary: Actualiza un endpoint
      operationId: patchV1WebhookEndpointsId
      security:
        - apiKeyAuth: []
      parameters:
        - $ref: '#/components/parameters/Id'
      requestBody:
        required: true
        content:
          application/json:
            schema:
              $ref: '#/components/schemas/UpdateWebhookEndpoint'
      responses:
        '200':
          description: Endpoint actualizado
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/WebhookEndpoint'
        '404':
          $ref: '#/components/responses/NotFound'
    delete:
      tags:
        - Webhooks
      summary: Desactiva un endpoint
      operationId: deleteV1WebhookEndpointsId
      security:
        - apiKeyAuth: []
      parameters:
        - $ref: '#/components/parameters/Id'
      responses:
        '200':
          description: Desactivado
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/Ok'
        '404':
          $ref: '#/components/responses/NotFound'
  /v1/webhook-endpoints/{id}/rotate:
    post:
      tags:
        - Webhooks
      summary: Rota el secreto del endpoint
      operationId: postV1WebhookEndpointsIdRotate
      description: El secreto anterior deja de ser válido de inmediato. En LIVE exige TOTP.
      security:
        - apiKeyAuth: []
      parameters:
        - $ref: '#/components/parameters/Id'
      requestBody:
        required: false
        content:
          application/json:
            schema:
              $ref: '#/components/schemas/WebhookStepUp'
      responses:
        '200':
          description: Nuevo secreto
          content:
            application/json:
              schema:
                type: object
                required:
                  - secret
                properties:
                  secret:
                    type: string
        '404':
          $ref: '#/components/responses/NotFound'
  /v1/webhook-endpoints/{id}/ping:
    post:
      tags:
        - Webhooks
      summary: Envía un evento de prueba firmado
      operationId: postV1WebhookEndpointsIdPing
      description: Máximo 3 pings por minuto. En LIVE exige TOTP.
      security:
        - apiKeyAuth: []
      parameters:
        - $ref: '#/components/parameters/Id'
      requestBody:
        required: false
        content:
          application/json:
            schema:
              $ref: '#/components/schemas/WebhookStepUp'
      responses:
        '200':
          description: Resultado del ping
          content:
            application/json:
              schema:
                type: object
                required:
                  - ok
                  - status
                  - eventId
                properties:
                  ok:
                    type: boolean
                  status:
                    type: integer
                  eventId:
                    type: string
                    format: uuid
        '502':
          description: El endpoint no respondió.
components:
  schemas:
    Currency:
      type: object
      required:
        - currency
        - asset
        - network
        - min_amount_cents
        - min_amount
      properties:
        currency:
          type: string
          example: usdttrc20
        asset:
          $ref: '#/components/schemas/Asset'
        network:
          $ref: '#/components/schemas/Network'
        min_amount_cents:
          type: integer
          example: 100
        min_amount:
          type: string
          example: '1.00000000'
    Asset:
      type: string
      enum:
        - BTC
        - ETH
        - SOL
        - USDT
    Network:
      type: string
      enum:
        - BITCOIN
        - ETHEREUM
        - SOLANA
        - TRON
    MinAmount:
      type: object
      required:
        - currency
        - asset
        - network
        - min_amount_cents
        - min_amount
      properties:
        currency:
          type: string
          example: usdttrc20
        asset:
          $ref: '#/components/schemas/Asset'
        network:
          $ref: '#/components/schemas/Network'
        min_amount_cents:
          type: integer
        min_amount:
          type: string
    Estimate:
      type: object
      required:
        - currency_from
        - currency_to
        - amount_cents
        - amount
        - fee_cents
        - net_cents
        - rate
        - pay_amount
      properties:
        currency_from:
          type: string
          const: usd
        currency_to:
          type: string
          example: usdttrc20
        amount_cents:
          type: integer
        amount:
          type: string
          example: '12.34'
        fee_cents:
          type: integer
        net_cents:
          type: integer
        rate:
          type: string
          example: '1.00000000'
        pay_amount:
          type: string
          example: '12.34000000'
    CreatePayment:
      type: object
      required:
        - amountCents
        - asset
        - network
      properties:
        amountCents:
          type: integer
          minimum: 1
          maximum: 100000000
          description: Monto en centavos de USD.
          example: 1234
        asset:
          $ref: '#/components/schemas/Asset'
        network:
          $ref: '#/components/schemas/Network'
        externalId:
          type: string
          minLength: 1
          maxLength: 128
          description: Tu identificador de orden.
          example: order-123
        description:
          type: string
          minLength: 1
          maxLength: 255
        metadata:
          type: object
          additionalProperties: true
    Payment:
      type: object
      description: Vista del comercio. Incluye alias snake_case por compatibilidad.
      required:
        - id
        - status
        - publicStatus
        - mode
        - amountCents
        - currency
        - asset
        - network
        - cryptoAmount
        - feeCents
        - netCents
        - address
        - riskStatus
        - expiresAt
        - createdAt
        - checkoutUrl
      properties:
        id:
          type: string
          format: uuid
        status:
          type: string
          enum:
            - AWAITING_PAYMENT
            - PROCESSING
            - PARTIALLY_PAID
            - SUCCEEDED
            - EXPIRED
            - FAILED
            - REFUNDED
        publicStatus:
          type: string
          enum:
            - waiting
            - confirming
            - partially_paid
            - finished
            - expired
            - failed
            - refunded
        mode:
          type: string
          enum:
            - TEST
            - LIVE
        externalId:
          type:
            - string
            - 'null'
        description:
          type:
            - string
            - 'null'
        amountCents:
          type: integer
        currency:
          type: string
          example: USD
        asset:
          $ref: '#/components/schemas/Asset'
        network:
          $ref: '#/components/schemas/Network'
        cryptoAmount:
          type: string
          example: '15.00000000'
        actuallyPaid:
          type:
            - string
            - 'null'
        overpaidCents:
          type: integer
        underpaidCents:
          type: integer
        rate:
          type: string
        rateAt:
          type: string
          format: date-time
        feeBps:
          type: integer
          example: 100
        feeCents:
          type: integer
        netCents:
          type: integer
        address:
          type: string
        riskStatus:
          type: string
          enum:
            - NORMAL
            - REVIEW
            - HOLD
            - CLEARED
        parentPaymentId:
          type:
            - string
            - 'null'
          format: uuid
        expiresAt:
          type: string
          format: date-time
        createdAt:
          type: string
          format: date-time
        merchantName:
          type: string
        checkoutUrl:
          type: string
          format: uri
        payment_id:
          type: string
          format: uuid
        payment_status:
          type: string
        price_amount:
          type: string
          example: '15.00'
        price_currency:
          type: string
          example: usd
        pay_amount:
          type: string
        pay_address:
          type: string
        pay_currency:
          type: string
          example: usdttrc20
        order_id:
          type:
            - string
            - 'null'
        outcome_amount:
          type: string
        outcome_currency:
          type: string
    Error:
      type: object
      required:
        - code
        - message
        - requestId
      properties:
        code:
          type: string
          description: Código estable para programar.
          examples:
            - validation_error
            - unauthorized
            - forbidden
            - not_found
            - conflict
            - rate_limited
            - unavailable
            - internal_error
            - totp_required
            - invalid_totp
        message:
          type: string
        requestId:
          type:
            - string
            - 'null'
          description: Correlación con logs.
        details:
          type: array
          items: {}
    PaymentDetail:
      allOf:
        - $ref: '#/components/schemas/Payment'
        - type: object
          required:
            - events
          properties:
            events:
              type: array
              items:
                $ref: '#/components/schemas/PaymentEvent'
    PaymentEvent:
      type: object
      required:
        - id
        - txHash
        - amount
        - confirmations
        - status
        - createdAt
      properties:
        id:
          type: string
          format: uuid
        txHash:
          type: string
        logIndex:
          type: integer
        amount:
          type: string
        confirmations:
          type: integer
        blockHeight:
          type:
            - integer
            - 'null'
        status:
          type: string
          enum:
            - DETECTED
            - CONFIRMED
        createdAt:
          type: string
          format: date-time
    WebhookEndpoint:
      type: object
      required:
        - id
        - url
        - mode
        - secretHint
        - events
        - active
        - createdAt
      properties:
        id:
          type: string
          format: uuid
        url:
          type: string
          format: uri
        mode:
          type: string
          enum:
            - TEST
            - LIVE
        secretHint:
          type: string
        events:
          type: array
          items:
            type: string
        active:
          type: boolean
        createdAt:
          type: string
          format: date-time
        updatedAt:
          type: string
          format: date-time
    CreateWebhookEndpoint:
      type: object
      required:
        - url
      properties:
        url:
          type: string
          format: uri
          maxLength: 2048
        mode:
          type: string
          enum:
            - TEST
            - LIVE
          default: TEST
        totp:
          type: string
          minLength: 6
          maxLength: 32
          description: Obligatorio para LIVE.
        events:
          type: array
          maxItems: 20
          items:
            type: string
            enum:
              - payment.finished
              - payment.partially_paid
              - payment.expired
              - payment.failed
              - payment.refunded
    WebhookEndpointCreated:
      allOf:
        - $ref: '#/components/schemas/WebhookEndpoint'
        - type: object
          required:
            - secret
          properties:
            secret:
              type: string
              description: Se muestra solo al crear o rotar.
    WebhookDelivery:
      type: object
      required:
        - id
        - eventId
        - eventType
        - status
        - attempts
        - createdAt
        - endpoint
      properties:
        id:
          type: string
          format: uuid
        eventId:
          type: string
          format: uuid
        eventType:
          type: string
        status:
          type: string
          enum:
            - PENDING
            - DELIVERED
            - FAILED
            - DLQ
        attempts:
          type: integer
        responseStatus:
          type:
            - integer
            - 'null'
        lastError:
          type:
            - string
            - 'null'
        createdAt:
          type: string
          format: date-time
        deliveredAt:
          type:
            - string
            - 'null'
          format: date-time
        endpoint:
          type: object
          properties:
            id:
              type: string
              format: uuid
            url:
              type: string
              format: uri
    UpdateWebhookEndpoint:
      type: object
      minProperties: 1
      properties:
        url:
          type: string
          format: uri
          maxLength: 2048
        events:
          type: array
          maxItems: 20
          items:
            type: string
            enum:
              - payment.finished
              - payment.partially_paid
              - payment.expired
              - payment.failed
              - payment.refunded
        active:
          type: boolean
        totp:
          type: string
          minLength: 6
          maxLength: 32
          description: Obligatorio para LIVE.
    Ok:
      type: object
      required:
        - ok
      properties:
        ok:
          type: boolean
          const: true
    WebhookStepUp:
      type: object
      properties:
        totp:
          type: string
          minLength: 6
          maxLength: 32
  responses:
    RateLimited:
      description: Límite de peticiones excedido
      content:
        application/json:
          schema:
            $ref: '#/components/schemas/Error'
          examples:
            limited:
              value:
                code: rate_limited
                message: too many requests
                requestId: 5f0c2f7e-1c2a-4b52-9f7e-7f3b2d8b6a11
    BadRequest:
      description: Error de validación
      headers:
        X-Request-Id:
          $ref: '#/components/headers/X-Request-Id'
      content:
        application/json:
          schema:
            $ref: '#/components/schemas/Error'
    Unauthorized:
      description: Falta autenticación o es inválida
      content:
        application/json:
          schema:
            $ref: '#/components/schemas/Error'
    Conflict:
      description: Conflicto de idempotencia o estado
      content:
        application/json:
          schema:
            $ref: '#/components/schemas/Error'
    NotFound:
      description: No encontrado
      content:
        application/json:
          schema:
            $ref: '#/components/schemas/Error'
    Forbidden:
      description: Sin permiso, scope o modo requerido
      content:
        application/json:
          schema:
            $ref: '#/components/schemas/Error'
  parameters:
    IdempotencyKey:
      name: Idempotency-Key
      in: header
      required: true
      description: Única por comercio. Repetirla con el mismo cuerpo devuelve la misma respuesta.
      schema:
        type: string
        minLength: 8
        maxLength: 128
    Cursor:
      name: cursor
      in: query
      description: Id del último elemento de la página anterior.
      schema:
        type: string
        format: uuid
    PaymentId:
      name: id
      in: path
      required: true
      schema:
        type: string
        format: uuid
    Id:
      name: id
      in: path
      required: true
      schema:
        type: string
        format: uuid
  headers:
    X-Request-Id:
      description: Identificador de la petición para soporte.
      schema:
        type: string
  securitySchemes:
    apiKeyAuth:
      type: apiKey
      in: header
      name: X-API-Key
      description: API key de servidor. Prefijo `sk_test_` o `sk_live_`.
