> ## Documentation Index
> Fetch the complete documentation index at: https://devs.tapipay.la/llms.txt
> Use this file to discover all available pages before exploring further.

# Crear suscripción

> Crea un cobro recurrente; genera todas las deudas del ciclo por adelantado.



## OpenAPI

````yaml /api-reference/openapi.yaml post /subscriptions
openapi: 3.0.0
info:
  title: TapiPay Facade API
  version: 1.0.0
  description: >
    Facade API pública de la plataforma de cobranzas TapiPay.  Ofrece un
    contrato limpio y desacoplado del modelo interno del OFU,  permitiendo a los
    clientes crear y gestionar cobros (deudas puntuales,  suscripciones
    recurrentes, links de pago, productos y contactos)  sin conocer detalles
    internos de Company, Modalities o GenerationData.
  contact:
    name: TapiPay Team
    url: https://www.tapipay.com
  license:
    name: Proprietary
servers:
  - url: https://tapipay-facade.dev.tapila.cloud
    description: Desarrollo
security:
  - apiKeyAuth: []
    tapiAuth: []
paths:
  /subscriptions:
    post:
      tags:
        - Subscriptions
      summary: Crear suscripción
      description: >-
        Crea un cobro recurrente; genera todas las deudas del ciclo por
        adelantado.
      operationId: createSubscription
      parameters:
        - name: Idempotency-Key
          in: header
          schema:
            type: string
          description: >
            Clave de idempotencia (opcional). Se usa como llave única
            (`externalRequestId`) de la suscripción. El `externalRequestId` es
            una llave **permanente** sin TTL (constraint UNIQUE en el OFU). Una
            request repetida con la misma key devuelve **error 409
            RESOURCE_CONFLICT** (no es replay/idempotencia clásica; es rechazo
            de duplicado por constraint UNIQUE). Si no se envía, el backend
            genera un `externalRequestId` único. Ver ADR-004 v1.1 para detalles
            de semántica.
      requestBody:
        required: true
        content:
          application/json:
            schema:
              $ref: '#/components/schemas/SubscriptionCreateRequest'
      responses:
        '201':
          description: Suscripción creada
          content:
            application/json:
              schema:
                type: object
                properties:
                  data:
                    $ref: '#/components/schemas/Subscription'
                  requestId:
                    type: string
        '400':
          description: Validación fallida
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/Error'
        '401':
          description: No autenticado
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/Error'
        '409':
          description: externalSubscriptionId ya existe
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/Error'
        '422':
          description: Error de resolución o violación de regla de negocio
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/Error'
components:
  schemas:
    SubscriptionCreateRequest:
      type: object
      required:
        - externalSubscriptionId
        - amount
        - intervalUnit
        - intervalCount
        - startDate
      properties:
        externalSubscriptionId:
          type: string
          description: Llave natural de la suscripción. Única por organización.
        externalClientId:
          type: string
          description: |
            Identificador del deudor (externalClientId o contactData, no ambos).
        contactData:
          $ref: '#/components/schemas/ContactInput'
          description: Datos del deudor inline (alternativa a externalClientId)
        amount:
          type: number
          minimum: 0.01
          multipleOf: 0.01
          description: Monto por ciclo en pesos (hasta 2 decimales, mínimo 0.01)
        currency:
          $ref: '#/components/schemas/Currency'
          default: MXN
        intervalUnit:
          $ref: '#/components/schemas/IntervalUnit'
          description: Unidad del intervalo (day, week, month, year)
        intervalCount:
          type: integer
          minimum: 1
          description: Cantidad de unidades por ciclo
        startDate:
          type: string
          format: date
          description: Fecha de inicio de la suscripción
        totalCycles:
          type: integer
          minimum: 1
          description: |
            Total de ciclos. Mutuamente excluyente con endDate.
        endDate:
          type: string
          format: date
          description: >
            Fecha de fin de la suscripción. Mutuamente excluyente con
            totalCycles.
        billingDay:
          $ref: '#/components/schemas/BillingDay'
          description: |
            Override del día de cobro. Por default se infiere del startDate.
        description:
          type: string
        productName:
          type: string
          description: >
            Nombre del producto a asociar (opcional).  Se resuelve por name en
            el OFU o se crea inline si no existe. Identificado por name único
            por companyCode.
        allowOverduePayment:
          type: boolean
          default: true
        enforcePaymentOrder:
          type: boolean
          default: false
          description: Si true, el deudor debe pagar en orden cronológico
        autopay:
          type: boolean
          default: false
        paymentMethods:
          type: array
          items:
            $ref: '#/components/schemas/PaymentMethod'
        additionalData:
          type: object
    Subscription:
      type: object
      required:
        - subscriptionId
        - externalSubscriptionId
        - status
        - amount
        - currency
        - intervalUnit
        - intervalCount
        - startDate
        - billingDay
        - enforcePaymentOrder
        - autopay
        - createdAt
      properties:
        subscriptionId:
          type: string
          pattern: ^sub_[a-zA-Z0-9]+$
          description: ID interno (prefijo sub_)
        externalSubscriptionId:
          type: string
        status:
          $ref: '#/components/schemas/SubscriptionStatus'
        amount:
          type: number
          description: Monto por ciclo en pesos (hasta 2 decimales)
        currency:
          $ref: '#/components/schemas/Currency'
        intervalUnit:
          $ref: '#/components/schemas/IntervalUnit'
        intervalCount:
          type: integer
        startDate:
          type: string
          format: date
        totalCycles:
          type: integer
        endDate:
          type: string
          format: date
        billingDay:
          $ref: '#/components/schemas/BillingDay'
          description: Día de cobro efectivo
        enforcePaymentOrder:
          type: boolean
        autopay:
          type: boolean
        paymentMethods:
          type: array
          items:
            $ref: '#/components/schemas/PaymentMethod'
        paymentUrl:
          type: string
          format: uri
          nullable: true
          description: >-
            URL pública del portal de pago. Comportamiento según configuración
            privateLinks del biller.

            Con privateLinks habilitado: URL opaca
            `https://app.tapipay.la/s/{slug}/portal/{shortCode}/`

            (shortCode anti-enumeración, NO expone identidad del deudor).
            Compartido por todas las deudas de

            esta suscripción (sin ?externalRequestId deep-linking a nivel
            Subscription). Puede ser null si falla

            la integración.

            Con privateLinks deshabilitado: URL legacy
            `https://app.tapipay.la/s/{slug}/portal/{identifierValue}/`

            (identifierValue = externalClientId con PII). Compartido por todas
            las deudas de esta suscripción

            (sin ?externalRequestId deep-linking a nivel Subscription).

            Nota: Deep-linking solo aplica a deudas INDIVIDUALES. Para acceder a
            deudas específicas con deep-linking,

            usá GET /subscriptions/{id}/debts y consultá el paymentUrl de cada
            Debt. Ver ADR-007 para detalles.
        contact:
          $ref: '#/components/schemas/ContactWithInline'
        product:
          $ref: '#/components/schemas/ProductWithInline'
        createdAt:
          type: string
          format: date-time
    Error:
      type: object
      required:
        - error
        - requestId
      properties:
        error:
          type: object
          required:
            - code
            - message
          properties:
            code:
              type: string
              enum:
                - INVALID_REQUEST
                - AUTHENTICATION_FAILED
                - RESOURCE_NOT_FOUND
                - RESOURCE_CONFLICT
                - RESOLUTION_ERROR
                - BUSINESS_RULE_VIOLATION
                - RATE_LIMITED
                - INTERNAL_ERROR
              description: Código de error estándar
            message:
              type: string
              description: Mensaje legible del error
            details:
              type: array
              description: Array de detalles adicionales (validaciones por campo, etc.)
              items:
                type: object
                properties:
                  field:
                    type: string
                  issue:
                    type: string
        requestId:
          type: string
          pattern: ^req_[a-zA-Z0-9]+$
          description: ID único del request para trazabilidad
    ContactInput:
      type: object
      required:
        - externalClientId
        - name
        - email
      properties:
        externalClientId:
          type: string
          description: Llave natural del contacto. Única por organización.
        name:
          type: string
          description: Nombre del deudor
        email:
          type: string
          format: email
          description: Email del deudor (requerido)
        phones:
          type: array
          description: Lista de teléfonos del deudor (opcional)
          items:
            $ref: '#/components/schemas/Phone'
    Currency:
      type: string
      enum:
        - MXN
        - ARS
        - PEN
        - COP
        - CLP
        - USD
      default: MXN
      description: >
        Código de moneda ISO 4217. Whitelist de monedas aceptadas por la Facade.
        Si no se envía, se usa el default de la organización (fallback: MXN). Si
        se envía un valor fuera de este whitelist, la Facade devuelve 400
        INVALID_REQUEST.
    IntervalUnit:
      type: string
      enum:
        - day
        - week
        - month
        - year
    BillingDay:
      type: object
      required:
        - day
      properties:
        day:
          type: integer
          minimum: 1
          maximum: 31
          description: >-
            Día del mes para cobro (1-31). Edge case: si el mes tiene menos
            días, se usa el último.
        month:
          type: integer
          minimum: 1
          maximum: 12
          description: Mes específico (solo para frecuencia anual)
    PaymentMethod:
      type: string
      enum:
        - CASH
        - CARD
        - TRANSFER
        - WALLET
        - BANK_TRANSFER
    SubscriptionStatus:
      type: string
      enum:
        - ACTIVE
        - PAUSED
        - CANCELLED
        - ENDED
    ContactWithInline:
      type: object
      required:
        - contactId
        - externalClientId
        - createdInline
      properties:
        contactId:
          type: string
          pattern: ^con_[a-zA-Z0-9]+$
          description: ID interno del contacto (prefijo con_)
        externalClientId:
          type: string
          description: Llave natural del contacto
        createdInline:
          type: boolean
          description: >
            Indica si el contacto fue creado inline en esta operación. NOTA:
            Este es un embedded thin contact (no incluye
            name/email/phones/active/updatedAt del contacto completo). Para
            obtener datos completos del contacto, consultá GET /contacts/{id}.
    ProductWithInline:
      type: object
      required:
        - productId
        - name
        - active
        - createdInline
      properties:
        productId:
          type: string
          description: ID del producto en el OFU (sin prefijo prod_)
        name:
          type: string
          description: Nombre del producto
        active:
          type: boolean
          description: Estado del producto
        createdInline:
          type: boolean
          description: Indica si el producto fue creado inline en esta operación
    Phone:
      type: object
      required:
        - number
        - type
      properties:
        number:
          type: string
          description: Número de teléfono. Ej +5215512345678
        type:
          $ref: '#/components/schemas/PhoneType'
        primary:
          type: boolean
          default: false
          description: >
            Indica si es el número telefónico principal. Opcional (default:
            false). El facade mapea a OFU.
        description:
          type: string
          description: >
            Descripción o etiqueta del teléfono. Opcional (default: type cuando
            no se especifica). El facade mapea a OFU.
    PhoneType:
      type: string
      enum:
        - MAIN
        - MOBILE
        - WORK
        - RELATIVE
        - OTHER
  securitySchemes:
    apiKeyAuth:
      type: apiKey
      in: header
      name: x-api-key
      description: >
        API key del API Gateway de Tapi. Requerida en todas las operaciones.
        Distinta por ambiente (desarrollo, homologación, producción).
    tapiAuth:
      type: apiKey
      in: header
      name: x-authorization-token
      description: >
        Token TAPI JWT. Requerido en todas las operaciones. Se envía sin prefijo
        "Bearer". Ej: x-authorization-token: eyJhbGci...

````