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

# Create a batch of income invoices

> Accepts up to **1,000** income invoices in one request and stamps them in the background. Each item is
exactly the body of `POST /invoices/income`, and must carry its own `idempotency_key`, unique within the
batch. To send more than 1,000 invoices, send more batches, each with its own `Idempotency-Key`.

**What happens in the request.** Every item is validated against the `POST /invoices/income` body schema,
with no I/O. An invalid item is listed in `rejected` with its reason and the rest go ahead; only an empty
or missing `invoices` array, or more than 1,000 items, refuses the whole request (`400`). The answer is
`202` with the batch in `processing`; the first items may already have started.

**What happens after.** Each accepted item is stamped by the same code as `POST /invoices/income`, with
the credential that created the batch, so it fails for the same reasons (a client that doesn't exist, a
SAT rejection, the credit limit) and consumes one credit when stamped. A temporary failure (PAC
unavailable, its answer lost) is retried automatically, up to 6 attempts per item. Items run about 10 at
a time per team. Follow the batch with `GET /invoices/income/batch/{id}`, or subscribe a webhook to
`invoice_batch.completed` (body `InvoiceBatchCompletedWebhookEvent`, signed, sent once and never
retried; see the `webhookEvent` callback of `POST /webhooks`), then read the per-item results with
`GET /invoices/income/batch/{id}/items`.

**Two levels of idempotency.**
- The `Idempotency-Key` header names the **batch**. The batch id is derived from your team, the
  credential's mode and the header, so the same key with the same body returns the same batch (`200`),
  and nothing is created again. The same key with a different body is `409` `idempotency_key_reused`.
  Bodies are compared as sent, including key order, so resend the exact same JSON.
- Each item's `idempotency_key` names the **invoice**. It is the same key `POST /invoices/income` uses:
  an invoice already issued under it, by an earlier batch or a single call, is not issued again, and the
  item ends `duplicate`. So a new batch that repeats items of a previous one is safe.

**gigstack Connect:** create the batch for a connected team with the `team` parameter, and read it with the
same `team`.

**Mode.** `livemode` comes only from the credential: a test key creates a test batch.

Not supported here: file uploads (CSV/XLSX), egress invoices and payment complements. If most of your
sales are to the general public, the monthly global invoice (*factura global*) that gigstack already
produces may be all you need.




## OpenAPI

````yaml openapi.json POST /invoices/income/batch
openapi: 3.0.3
info:
  title: gigstack API v2
  description: >
    # gigstack API v2


    Build customer, invoice and payment integrations. Start with the
    [quickstart](https://docs.gigstack.io/quickstart), then select the [issuing
    country](https://docs.gigstack.io/concepts/shared-fields).


    ## Authentication and environments


    Use Authorization: Bearer YOUR_API_KEY. Standard live and test keys use
    https://api.gigstack.io/v2. Internal staging uses
    https://gigstack-staging-9z9nnaat.uc.gateway.dev/v2 and separate keys. Test
    mode is a data mode within an environment; a body field does not switch a
    key's mode.


    See [authentication](https://docs.gigstack.io/authentication) for key
    handling, OAuth team scope and gigstack Connect. Signup requires its
    separately documented internal credential; health probes have their own
    security declarations. Operations marked unavailable have no configured
    public gateway route.


    ## Read the operation contract


    Response envelopes, pagination and retry rules differ by endpoint. HTTP
    success alone does not prove external fiscal completion or movement of
    money. Reconcile ambiguous writes before retrying. Use [responses and
    recovery](https://docs.gigstack.io/responses) and the operation's error
    codes; document credits and daily limits are not generic retryable rate
    limits.


    The issuing team's configuration selects Mexico or Colombia; customer
    country and currency do not. Read
    [Mexico](https://docs.gigstack.io/countries/mexico) or
    [Colombia](https://docs.gigstack.io/countries/colombia) before choosing
    fiscal fields. Accepted public input differs from a provider's direct
    payload.


    Examples and schema checks do not imply every operation has been executed
    live. [Verification coverage](https://docs.gigstack.io/verification)
    distinguishes source review, offline checks and observed staging behavior.
    Documentation describes operations and does not authorize execution.
  version: 2.0.0
  contact:
    name: Gigstack API Support
    url: https://gigstack.io
    email: support@gigstack.io
  license:
    name: Proprietary
    url: https://gigstack.io/terms
  termsOfService: https://gigstack.io/terms
servers:
  - url: https://api.gigstack.io/v2
    description: >
      Public API for standard live and test-mode keys. Test data is isolated by
      the key mode

      (`livemode: false`). Internal staging is a separate deployment and key
      store; see

      https://docs.gigstack.io/authentication#environments for its base URL.
security:
  - bearerAuth: []
tags:
  - name: gigstack Connect
    description: >
      **Multi-Team Resource Access**


      gigstack Connect lets a master team act on other teams that share its
      billing account.


      ## 🔗 How It Works


      Add the `team` query parameter to a request made with an **API key**:


      ```bash

      # Access team_xyz789's clients

      GET /clients?team=team_xyz789


      # Create an income invoice for team_abc123

      POST /invoices/income?team=team_abc123


      # Update service in team_def456

      PUT /services/service_456?team=team_def456

      ```


      ## ✅ Requirements


      - The API key's team must be a master team (gigstack Connect enabled)

      - The target team must exist and share the master team's billing account

      - The plan must include the `multipleIssuerAccounts` feature

      - OAuth access tokens cannot act on another team


      ## ⚠️ Error Responses


      Raw `{ "message": … }` bodies from the authentication layer:


      - `401 Unauthorized, not a master team` - gigstack Connect not enabled on
      your key's team

      - `404 Team not found` - Target team doesn't exist

      - `401 Unauthorized, no matched teams` - Target team could not be resolved
      within your billing account

      - `403 Tu plan no incluye múltiples cuentas emisoras. …` - Plan lacks
      `multipleIssuerAccounts`

      - `403 Team mismatch with OAuth token` - OAuth access token used with
      another team's id


      ## 🌐 Availability


      The `team` parameter is read by the authentication layer, so it is
      accepted on every authenticated

      endpoint, including ones whose parameter list does not show it.
  - name: Clients
    description: Client management operations with Mexican tax compliance
  - name: Services
    description: Service and product catalog management with SAT product keys
  - name: Invoices
    description: Invoice management with CFDI 4.0 compliance and SAT integration
  - name: Draft Invoices (Pre-Facturas)
    description: >
      **Create, edit, preview and stamp draft invoices (pre-facturas)**


      Draft invoices let you build CFDI invoices incrementally before stamping
      them with SAT. Use them as **pre-facturas** — generate a preview PDF with
      a "Sin Validez Fiscal" watermark to share with your client for approval,
      then stamp the draft to create a valid CFDI when ready.


      ## Typical Workflow


      1. `POST /invoices/draft` — Create a draft with minimal data

      2. `PUT /invoices/draft/{id}` — Update as more data becomes available

      3. `POST /invoices/draft/{id}/preview` — Generate a preview PDF
      (pre-factura)

      4. `POST /invoices/draft/{id}/stamp` — Finalize into a valid CFDI invoice
  - name: Descarga Masiva SAT
    description: >
      **SAT bulk invoice download via FIEL authentication**


      Download all your issued and received CFDI invoices directly from the SAT
      (Servicio de Administración Tributaria) using your FIEL (Firma Electrónica
      Avanzada).


      ## Setup flow

      1. `GET /invoices/download/activate/status` — Check if activated and
      what's needed

      2. `POST /invoices/download/activate` — Activate billing (adds Stripe
      meter/add-on)

      3. `POST /invoices/download/fiel` — Upload `.cer` + `.key` files
      (auto-registers with SAT)

      4. `PUT /invoices/download/schedule` — Configure daily auto-sync

      5. `POST /invoices/download/request` — Submit manual download requests


      ## Pricing

      - Included in Pro/Business plans: only the download meter ($0.20 MXN/XML)

      - Other paid plans: the same $0.20 MXN/XML download meter, no monthly base
      fee
  - name: Payments
    description: Payment processing, tracking, and refund management
  - name: Receipts
    description: Receipt creation and management with CFDI stamping capabilities
  - name: Retentions
    description: >-
      Tax retention documents (CFDI Retenciones 2.0) — creation, stamping,
      cancellation, and file retrieval
  - name: Platform Payouts
    description: >
      **Plan and stamp a marketplace's provider payouts from two files.**


      For marketplaces and digital platforms that pay providers under the SAT
      digital-platforms scheme

      (Plataformas Tecnológicas, RESICO 625, retention key 26): ride-hailing
      drivers, delivery couriers,

      lodging hosts, sellers of goods. Available to marketplace **master teams**
      whose billing account has

      platform payouts enabled. Upload a movements file and a commissions file.
      gigstack matches each row

      to a provider's team in your billing account and plans three kinds of
      CFDI: the provider's income

      invoice to you, your retention certificate (key 26) to the provider, and
      your monthly commission

      invoice to the provider.


      **Not for your own sales.** This is for a platform invoicing on behalf of
      its providers. A company

      invoicing its own sales, one CFDI per sale, should use `POST
      /invoices/income`.


      **Tax policy per account.** Which documents are issued, and with which SAT
      keys and rates, is set

      per master account at onboarding: allowed tax regimes, CSD requirement,
      service type (`tipoDeServ` /

      `subTipServ`), ISR and IVA withholding rates, product keys and concept
      descriptions. The defaults are

      for ground passenger transport (service type `01`, 2.1% ISR withholding).
      Contact support to

      configure your account's policy; it can't be changed through the API.


      1. `POST /platform-payouts` with an `Idempotency-Key` - upload and plan
      (synchronous)

      2. `GET /platform-payouts/{id}` and `GET /platform-payouts/{id}/movements`
      - review the plan

      3. `POST /platform-payouts/{id}/confirm` - irreversible hand-off to the
      stamping worker

      4. `GET /platform-payouts/{id}` - poll until `completed` or `failed`, then
      read `result`
         (`completed`, `partially_completed` or `failed`)

      Error messages and exclusion reasons are Spanish sentences for end users;
      branch on `error.code`,

      `reason_code` and `exclusion_codes`.
  - name: Documents
    description: >
      SAT supporting documentation (contracts, delivery/payment proofs,
      communications) — upload

      metadata, compliance review, AI extraction, and linking to invoices,
      payments, receipts and clients.
  - name: Teams
    description: Team management, settings, and member administration
  - name: Users
    description: User account management and password operations
  - name: Auth
    description: >
      **API-only signup for AI agents and partner integrations.**


      A single `POST /v2/auth/signup` call provisions a Firebase Auth user,
      billing

      account, team, plan subscription, and returns API keys — no UI, no FIEL
      upload,

      no human onboarding required.


      Designed for the AI-agents-as-customers use case. RFC defaults to genérico

      (`XAXX010101000`) so agents can transact under público en general
      until/unless

      their customer uploads their own RFC.


      Authenticated with `X-Internal-API-Key` (partner-issued) — Bearer tokens
      are

      team-scoped and a brand-new caller doesn't have one yet.


      See `AGENTS.md` in the gigstack-cli repo for end-to-end integration guide.
  - name: Webhooks
    description: Webhook management for real-time event notifications
  - name: Catalogs
    description: >
      **Read-only search over the SAT catalogs**


      Look up the SAT codes required on CFDI line items without hardcoding them:


      - `GET /catalogs/product-keys` — `c_ClaveProdServ`, the item `product_key`

      - `GET /catalogs/unit-keys` — `c_ClaveUnidad`, the item `unit_key` /
      `unit_name`


      Both are typo-tolerant full-text searches ranked by relevance. The
      catalogs are

      published by the SAT and identical for every team, so results carry no
      team data

      and ignore `livemode` — but a valid API key is still required.
  - name: SAT Lists
    description: >
      Read-only access to the RFC lists the SAT publishes under Artículo 69,
      69-B and 69-B Bis.


      gigstack re-syncs all 22 lists from the SAT's published CSVs every Sunday,
      so you can screen a counterparty's

      RFC before invoicing it without scraping the SAT yourself.
externalDocs:
  description: Complete API Documentation & Guides
  url: https://docs.gigstack.io
paths:
  /invoices/income/batch:
    post:
      tags:
        - Invoices
      summary: Create a batch of income invoices
      description: >
        Accepts up to **1,000** income invoices in one request and stamps them
        in the background. Each item is

        exactly the body of `POST /invoices/income`, and must carry its own
        `idempotency_key`, unique within the

        batch. To send more than 1,000 invoices, send more batches, each with
        its own `Idempotency-Key`.


        **What happens in the request.** Every item is validated against the
        `POST /invoices/income` body schema,

        with no I/O. An invalid item is listed in `rejected` with its reason and
        the rest go ahead; only an empty

        or missing `invoices` array, or more than 1,000 items, refuses the whole
        request (`400`). The answer is

        `202` with the batch in `processing`; the first items may already have
        started.


        **What happens after.** Each accepted item is stamped by the same code
        as `POST /invoices/income`, with

        the credential that created the batch, so it fails for the same reasons
        (a client that doesn't exist, a

        SAT rejection, the credit limit) and consumes one credit when stamped. A
        temporary failure (PAC

        unavailable, its answer lost) is retried automatically, up to 6 attempts
        per item. Items run about 10 at

        a time per team. Follow the batch with `GET
        /invoices/income/batch/{id}`, or subscribe a webhook to

        `invoice_batch.completed` (body `InvoiceBatchCompletedWebhookEvent`,
        signed, sent once and never

        retried; see the `webhookEvent` callback of `POST /webhooks`), then read
        the per-item results with

        `GET /invoices/income/batch/{id}/items`.


        **Two levels of idempotency.**

        - The `Idempotency-Key` header names the **batch**. The batch id is
        derived from your team, the
          credential's mode and the header, so the same key with the same body returns the same batch (`200`),
          and nothing is created again. The same key with a different body is `409` `idempotency_key_reused`.
          Bodies are compared as sent, including key order, so resend the exact same JSON.
        - Each item's `idempotency_key` names the **invoice**. It is the same
        key `POST /invoices/income` uses:
          an invoice already issued under it, by an earlier batch or a single call, is not issued again, and the
          item ends `duplicate`. So a new batch that repeats items of a previous one is safe.

        **gigstack Connect:** create the batch for a connected team with the
        `team` parameter, and read it with the

        same `team`.


        **Mode.** `livemode` comes only from the credential: a test key creates
        a test batch.


        Not supported here: file uploads (CSV/XLSX), egress invoices and payment
        complements. If most of your

        sales are to the general public, the monthly global invoice (*factura
        global*) that gigstack already

        produces may be all you need.
      operationId: createIncomeInvoiceBatch
      parameters:
        - $ref: '#/components/parameters/TeamParameter'
        - name: Idempotency-Key
          in: header
          required: true
          description: >
            Your identifier for this batch, 8-128 characters of `A-Z a-z 0-9 . _
            : -`. Reusing it with the same

            body returns the batch it first created; reusing it with a different
            body is `409 idempotency_key_reused`.
          schema:
            type: string
            minLength: 8
            maxLength: 128
            pattern: ^[A-Za-z0-9._:-]{8,128}$
          example: sales-2026-09-29-part-1
      requestBody:
        required: true
        content:
          application/json:
            schema:
              $ref: '#/components/schemas/InvoiceBatchCreateInput'
            example:
              invoices:
                - idempotency_key: order-2026-09-000123
                  automation_type: none
                  currency: MXN
                  use: G03
                  payment_form: '04'
                  payment_method: PUE
                  client:
                    id: client_1234567890
                  items:
                    - description: Professional consulting services
                      product_key: '80141503'
                      unit_key: E48
                      unit_price: 1000
                      quantity: 1
                      taxes:
                        - type: IVA
                          rate: 0.16
                          factor: Tasa
                          withholding: false
                  send_email: true
                - idempotency_key: order-2026-09-000124
                  automation_type: none
                  currency: MXN
                  use: G03
                  payment_form: '03'
                  payment_method: PUE
                  client:
                    id: client_0987654321
                  items:
                    - description: Annual support plan
                      product_key: '81111811'
                      unit_key: E48
                      unit_price: 2500
                      quantity: 1
                      taxes:
                        - type: IVA
                          rate: 0.16
                          factor: Tasa
                          withholding: false
      responses:
        '200':
          description: >
            Retry of an earlier request with the same `Idempotency-Key` and the
            same body: the batch it created,

            as it is now. Nothing is created again. If the first request died
            while writing the batch, this

            request finishes creating it.
          content:
            application/json:
              schema:
                allOf:
                  - $ref: '#/components/schemas/StandardSuccessResponse'
                  - type: object
                    properties:
                      data:
                        $ref: '#/components/schemas/ApiPublicInvoiceBatch'
              example:
                success: true
                data:
                  id: ibatch_5d41402abc4b2a76b9719d911017c592
                  object: invoice_batch
                  type: income
                  livemode: true
                  status: processing
                  result: null
                  total: 250
                  accepted: 248
                  rejected:
                    - index: 17
                      idempotency_key: order-2026-09-000140
                      error:
                        code: invalid_body
                        message: 'client_id: Unexpected field'
                    - index: 42
                      idempotency_key: order-2026-09-000123
                      error:
                        code: duplicate_idempotency_key
                        message: idempotency_key is already used by item 0
                  counts:
                    queued: 131
                    stamped: 115
                    failed: 1
                    duplicate: 1
                    needs_review: 0
                  created_at: 1790780400000
                  completed_at: null
                timestamp: 1790781000000
        '202':
          description: >
            Batch created. `status` is `processing`; the accepted items are
            being stamped in the background.

            Items refused by validation are in `rejected` and will not be
            stamped. A batch in which every item

            was rejected has nothing to stamp and is usually already
            `completed`, with `result: failed`.
          content:
            application/json:
              schema:
                allOf:
                  - $ref: '#/components/schemas/StandardSuccessResponse'
                  - type: object
                    properties:
                      data:
                        $ref: '#/components/schemas/ApiPublicInvoiceBatch'
              example:
                success: true
                data:
                  id: ibatch_5d41402abc4b2a76b9719d911017c592
                  object: invoice_batch
                  type: income
                  livemode: true
                  status: processing
                  result: null
                  total: 250
                  accepted: 248
                  rejected:
                    - index: 17
                      idempotency_key: order-2026-09-000140
                      error:
                        code: invalid_body
                        message: 'client_id: Unexpected field'
                    - index: 42
                      idempotency_key: order-2026-09-000123
                      error:
                        code: duplicate_idempotency_key
                        message: idempotency_key is already used by item 0
                  counts:
                    queued: 248
                    stamped: 0
                    failed: 0
                    duplicate: 0
                    needs_review: 0
                  created_at: 1790780400000
                  completed_at: null
                timestamp: 1790780401250
        '400':
          description: >
            The request was refused and no batch was created. `error.code`:


            - `invalid_request_body`: the `Idempotency-Key` header is missing or
            malformed.

            - `invalid_body`: the body is not `{ "invoices": [ … ] }` with at
            least one item.

            - `too_many_items`: more than 1,000 items. Split them into several
            batches.


            Problems with a single item don't refuse the request; they are
            listed in the batch's `rejected`.
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/StandardErrorResponse'
              examples:
                missing_idempotency_key:
                  summary: Idempotency-Key header missing
                  value:
                    success: false
                    error:
                      code: invalid_request_body
                      message: Idempotency-Key header is required
                    timestamp: 1790780400000
                malformed_idempotency_key:
                  summary: Idempotency-Key does not match the format
                  value:
                    success: false
                    error:
                      code: invalid_request_body
                      message: >-
                        Idempotency-Key must be 8-128 chars matching
                        [A-Za-z0-9._:-]
                    timestamp: 1790780400000
                invalid_body:
                  summary: No invoices array
                  value:
                    success: false
                    error:
                      code: invalid_body
                      message: >-
                        Body must be { "invoices": [ ... ] } with at least one
                        invoice
                    timestamp: 1790780400000
                too_many_items:
                  summary: More than 1,000 invoices
                  value:
                    success: false
                    error:
                      code: too_many_items
                      message: >-
                        A batch holds at most 1000 invoices; send the rest in
                        more batches
                    timestamp: 1790780400000
        '401':
          $ref: '#/components/responses/Unauthorized'
        '403':
          description: >
            Either the authentication layer refused the credential (raw body,
            see `AuthForbidden`), or a

            user-scoped token (MCP, dashboard) lacks `editor` permission on
            invoices (standardized envelope,

            `forbidden`). API keys and OAuth tokens act as the team and are not
            role-checked.
          content:
            application/json:
              schema:
                anyOf:
                  - $ref: '#/components/schemas/StandardErrorResponse'
                  - $ref: '#/components/schemas/AuthMiddlewareError'
              examples:
                missing_invoices_permission:
                  summary: User-scoped token without editor permission on invoices
                  value:
                    success: false
                    error:
                      code: forbidden
                      message: This action requires editor access to invoices
                    timestamp: 1790780400000
                revoked_api_key:
                  summary: Authentication layer - API key revoked or disabled
                  value:
                    message: API Key inválida.
                    details: Invalid API Key
        '409':
          description: >
            `idempotency_key_reused`: the `Idempotency-Key` was already used
            with a **different body**. Nothing

            was created. Send the new body under a new key; to read the original
            batch, use

            `GET /invoices/income/batch/{id}`.
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/StandardErrorResponse'
              example:
                success: false
                error:
                  code: idempotency_key_reused
                  message: >-
                    This Idempotency-Key was already used with a different body.
                    Use a new key for a different batch.
                timestamp: 1790780400000
        '500':
          description: >
            Unexpected failure (`internal_server_error`). Retrying with the
            **same** `Idempotency-Key` and body

            is safe: it returns the batch if it was created, or creates it.
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/StandardErrorResponse'
              example:
                success: false
                error:
                  code: internal_server_error
                  message: An internal server error occurred
                timestamp: 1790780400000
      security:
        - bearerAuth: []
components:
  parameters:
    TeamParameter:
      name: team
      in: query
      required: false
      schema:
        type: string
      description: >
        **gigstack Connect:** Target team ID for multi-team access.


        Requires gigstack Connect enabled on your team and shared billing
        account.


        Also requires the `multipleIssuerAccounts` feature on your plan.
        Requests targeting a

        team other than the one your API key belongs to return `403` without it.


        Only API keys can use it: an OAuth access token sent with another team's
        id is rejected with

        `403 Team mismatch with OAuth token`.


        **Optional — omit it entirely** unless you are acting on another team.
        It deliberately

        carries no example value so generated snippets do not emit
        `?team=undefined`; when the

        parameter is absent, the team is derived from your API key.


        **Example:** `?team=team_xyz789`
  schemas:
    InvoiceBatchCreateInput:
      type: object
      description: >
        Up to 1,000 income invoices. Each item is **exactly** the body of `POST
        /invoices/income`, and must carry

        its own `idempotency_key`, unique within the batch.


        Items are validated one by one: an invalid item is listed in the batch's
        `rejected` and the others go

        ahead. Only a body without a non-empty `invoices` array (`invalid_body`)
        or with more than 1,000 items

        (`too_many_items`) refuses the whole request.


        `livemode`, `team` and `owner` in an item are ignored (they come from
        the credential), and so is

        `return_files`: a batch does not return files. Keep the whole JSON body
        under 10 MB.
      required:
        - invoices
      properties:
        invoices:
          type: array
          minItems: 1
          maxItems: 1000
          description: >-
            The invoices, in the order you want them reported. An item's `index`
            is its position here (from 0).
          items:
            $ref: '#/components/schemas/InvoiceBatchItemInput'
    StandardSuccessResponse:
      type: object
      description: |
        Standardized success envelope emitted by `sendSuccessResponse`.
      required:
        - success
        - data
        - timestamp
      properties:
        success:
          type: boolean
          enum:
            - true
          example: true
        data:
          type: object
          description: The operation payload.
        message:
          type: string
          description: Human-readable summary. Present only when the handler supplies one.
          example: Operation completed successfully
        timestamp:
          type: integer
          format: int64
          description: Server time in **epoch milliseconds** (`Luxon.now().toMillis()`).
          example: 1767225600000
    ApiPublicInvoiceBatch:
      type: object
      description: >
        An income invoice batch: how many invoices it received, which were
        rejected up front, and the progress of

        the rest. Timestamps are epoch milliseconds.
      required:
        - id
        - object
        - type
        - livemode
        - status
        - result
        - total
        - accepted
        - rejected
        - counts
        - created_at
        - completed_at
      properties:
        id:
          type: string
          description: >
            Batch id. Derived from your team, the credential's mode and the
            `Idempotency-Key` you sent, so the

            same key always names the same batch.
          pattern: ^ibatch_[0-9a-f]{32}$
          example: ibatch_5d41402abc4b2a76b9719d911017c592
        object:
          type: string
          enum:
            - invoice_batch
          example: invoice_batch
        type:
          type: string
          description: Kind of document the batch issues. Only `income` exists.
          enum:
            - income
          example: income
        livemode:
          type: boolean
          description: >-
            Mode of the credential that created the batch. A test key only ever
            sees test batches.
          example: true
        status:
          $ref: '#/components/schemas/InvoiceBatchStatusEnum'
        result:
          $ref: '#/components/schemas/InvoiceBatchResultEnum'
        total:
          type: integer
          description: Invoices in the request.
          example: 250
        accepted:
          type: integer
          description: Invoices that passed validation and are processed.
          example: 248
        rejected:
          type: array
          description: >-
            Invoices refused by validation, in request order. Empty when every
            item was accepted.
          items:
            $ref: '#/components/schemas/InvoiceBatchRejectedItem'
        counts:
          $ref: '#/components/schemas/InvoiceBatchCounts'
        created_at:
          type: integer
          format: int64
          description: When the batch was created (epoch ms).
          example: 1790780400000
        completed_at:
          type: integer
          format: int64
          nullable: true
          description: >-
            When the last item reached a final status (epoch ms). `null` while
            `processing`.
          example: 1790784000000
    StandardErrorResponse:
      type: object
      description: >
        Standardized error envelope emitted by `sendErrorResponse` and its
        helpers

        (`sendValidationError`, `sendNotFoundError`, `sendUnauthorizedError`,

        `sendForbiddenError`, `sendConflictError`, `sendBadRequestError`,

        `sendInternalServerError`).
      required:
        - success
        - error
        - timestamp
      properties:
        success:
          type: boolean
          enum:
            - false
          example: false
        error:
          type: object
          required:
            - code
            - message
          properties:
            code:
              type: string
              description: >
                Stable machine-readable code. Values emitted by the shared
                helpers:

                `unauthorized`, `forbidden`, `invalid_token`,
                `validation_failed`,

                `invalid_request_body`, `missing_required_field`,
                `invalid_field_value`,

                `resource_not_found`, `resource_already_exists`,
                `resource_conflict`,

                `business_rule_violation`, `operation_not_allowed`,

                `insufficient_permissions`, `external_service_error`,

                `payment_processor_error`, `cfdi_service_error`,

                `internal_server_error`, `service_unavailable`,
                `rate_limit_exceeded`,

                `database_error`, `data_integrity_error`, `file_not_found`,

                `file_upload_error`, `invalid_file_format`. Individual handlers
                may

                emit additional endpoint-specific codes, documented per
                operation.
              example: validation_failed
            message:
              type: string
              example: Request validation failed
            details:
              oneOf:
                - type: string
                - type: array
                  items:
                    type: string
              description: >
                Present only when the handler supplies detail. Validation
                failures

                emit an array of `"<field path>: <message>"` strings.
              example:
                - 'currency: Field is required'
        timestamp:
          type: integer
          format: int64
          description: Server time in epoch milliseconds.
          example: 1767225600000
    AuthMiddlewareError:
      type: object
      description: >
        Raw error body produced by the authentication layer (before any endpoint
        runs). It is not

        the standardized envelope: there is no `success` and no `timestamp`.
      required:
        - message
      properties:
        message:
          type: string
          description: >-
            Human-readable reason. Some messages are in Spanish; branch on the
            HTTP status, not on this text.
          example: Unauthorized
        error:
          type: string
          description: >-
            OAuth error code. Present only when an OAuth access token was
            presented.
          enum:
            - invalid_token
            - token_expired
            - token_revoked
            - server_error
          example: token_expired
        error_description:
          type: string
          description: Same text as `message`. Present only alongside `error`.
          example: Access token has expired. Please refresh your token.
        details:
          description: >-
            Extra detail, e.g. `Invalid API Key` when a revoked key is rejected
            with `403`.
          oneOf:
            - type: string
            - type: object
          example: Invalid API Key
    InvoiceBatchItemInput:
      description: >-
        One invoice of a batch. The body of `POST /invoices/income`, with
        `idempotency_key` required.
      allOf:
        - $ref: '#/components/schemas/InvoiceIncomeInput'
        - type: object
          required:
            - idempotency_key
          properties:
            idempotency_key:
              type: string
              minLength: 1
              maxLength: 256
              description: >
                Your identifier for this invoice (for example your order id),
                unique within the batch.

                Surrounding spaces are trimmed. It is the same key as on `POST
                /invoices/income`, so an

                invoice already issued under it, by an earlier batch or a single
                call, is not issued

                again: the item ends `duplicate`.
              example: order-2026-09-000123
    InvoiceBatchStatusEnum:
      type: string
      description: >
        - `processing`: some accepted items are still queued.

        - `completed`: every accepted item has a final status. Read `result` to
        know how it went.
      enum:
        - processing
        - completed
      example: processing
    InvoiceBatchResultEnum:
      type: string
      nullable: true
      description: >
        How a finished batch turned out. `null` while `status` is `processing`.


        - `completed`: every item was issued (`stamped`, or `duplicate` because
        it had been issued before), and
          nothing was rejected.
        - `partially_completed`: at least one item was issued, and at least one
        was not (`failed`,
          `needs_review` or rejected up front).
        - `failed`: no item was issued.
      enum:
        - completed
        - partially_completed
        - failed
        - null
      example: partially_completed
    InvoiceBatchRejectedItem:
      type: object
      description: >-
        An item refused by validation when the batch was created. Nothing was
        stamped or charged for it.
      required:
        - index
        - idempotency_key
        - error
      properties:
        index:
          type: integer
          description: Position of the item in `invoices` (from 0).
          example: 17
        idempotency_key:
          type: string
          nullable: true
          description: >-
            The item's key, trimmed. `null` when the item was not an object or
            had no key.
          example: order-2026-09-000140
        error:
          allOf:
            - $ref: '#/components/schemas/InvoiceBatchError'
          description: >
            `code` is one of:


            - `invalid_item`: the item is not a JSON object.

            - `idempotency_key_required`: no `idempotency_key`, or an empty one.

            - `invalid_idempotency_key`: the key is longer than 256 characters.

            - `duplicate_idempotency_key`: an earlier item of this batch has the
            same key (the message names its index).

            - `invalid_body`: the item fails the `POST /invoices/income` body
            validation; the message lists
              each `path: message`.
    InvoiceBatchCounts:
      type: object
      description: >
        Accepted items by status. `queued` is what is still in flight, so it
        reaches `0` when the batch completes.

        The five counts add up to `accepted`; rejected items are not counted
        here.
      required:
        - queued
        - stamped
        - failed
        - duplicate
        - needs_review
      properties:
        queued:
          type: integer
          description: Waiting for, or in, a stamping attempt.
          example: 0
        stamped:
          type: integer
          description: Stamped by this batch.
          example: 245
        failed:
          type: integer
          description: Ended without an invoice. See each item's `error`.
          example: 2
        duplicate:
          type: integer
          description: >-
            Already issued under the same `idempotency_key` before; not issued
            again.
          example: 1
        needs_review:
          type: integer
          description: >-
            The PAC could not confirm whether the invoice was stamped. gigstack
            support resolves these.
          example: 0
    UnauthorizedError:
      allOf:
        - $ref: '#/components/schemas/StandardErrorResponse'
      example:
        success: false
        error:
          code: unauthorized
          message: Unauthorized access
        timestamp: 1767225600000
    InvoiceIncomeInput:
      description: >
        Unknown top-level keys are rejected (`400 validation_failed` /
        `unexpected_key`) — body

        validation runs in strict allowlist mode, so a field the schema does not
        declare

        produces that error. In particular there is no `client_id` field:
        reference an

        existing client with `client: { "id": "client_…" }`, or look one up with

        `client: { "search": { "on_key": "tax_id", "on_value": "…" } }`.
        Supplying both `id`

        and `search` on the same object is a `400`.


        `team`, `livemode` and `owner` are reserved and injected by the auth
        middleware.
      type: object
      additionalProperties: false
      required:
        - client
        - currency
        - use
        - items
        - payment_form
        - payment_method
      properties:
        date:
          type: number
        client:
          $ref: '#/components/schemas/EmbeddedClientInput'
        return_files:
          description: Return base64 encoded PDF and XML files in response
          example: true
          type: boolean
        currency:
          type: string
          example: MXN
        exchange_rate:
          description: >-
            Exchange rate for currency conversion. If not provided, the latest
            rate from our rates collection will be used automatically.
          example: 1
          type: number
        folio_number:
          example: 123
          type: number
        series:
          type: string
          example: A
        idempotency_key:
          description: >
            Your identifier for this invoice, for example your order id. With
            it, sending the same request

            again cannot issue a second CFDI or charge a second credit:


            - Once the invoice exists, the same key answers `400` with
            `duplicate: true` and the existing `uuid`.

            - While another request with the key is being processed, it answers
            `409` `idempotency_in_progress`.

            - After a `503` `PAC_OUTCOME_UNKNOWN`, a retry with the key resends
            the exact same XML and folio, so
              the PAC either stamps it once or reports the stamp it already made.
            - A definitive rejection (for example the SAT refusing the data)
            frees the key, so you can fix the
              body and send it again under the same key.

            Scoped to your team and the credential's mode. Required on every
            item of `POST /invoices/income/batch`.
          example: unique_key_123
          type: string
          nullable: true
        use:
          type: string
          example: G03
        exports:
          example: '01'
          type: string
          enum:
            - '01'
            - '02'
            - '03'
            - '04'
            - null
          nullable: true
        complements:
          type: array
          items:
            type: object
            additionalProperties: false
            required:
              - type
              - data
            properties:
              type:
                example: custom
                type: string
              data:
                example: <xml>...</xml>
                type: string
          nullable: true
        related_documents:
          type: array
          items:
            type: object
            additionalProperties: false
            required:
              - relationship
              - documents
            properties:
              relationship:
                example: '04'
                type: string
              documents:
                type: array
                items:
                  example: 12345678-1234-1234-1234-123456789012
                  type: string
          nullable: true
        invoice_pdf_notes:
          example: Additional notes for PDF
          type: string
        addenda:
          example: <addenda>...</addenda>
          type: string
          nullable: true
        send_email:
          description: >-
            Whether to send the document via email to the client. Defaults to
            `true`.
          example: true
          type: boolean
        ignore_emails:
          description: >
            Suppress all notification emails for this document. Takes precedence
            over

            `send_email` — when `true`, no mail is sent even if `send_email` is
            `true`.
          example: false
          type: boolean
          nullable: true
        emails:
          example:
            - client@example.com
          type: array
          items:
            type: string
            format: email
        metadata:
          type: object
          additionalProperties: true
          properties: {}
        automation_type:
          description: |
            Optional. Invoice automation type:
            - `payment`: Create invoice with payment automation
            - `none`: No automation, create invoice only
          example: payment
          type: string
          enum:
            - payment
            - none
        global:
          type: object
          additionalProperties: false
          required:
            - periodicity
            - months
            - year
          properties:
            periodicity:
              example: '04'
              type: string
            months:
              example: '01'
              type: string
            year:
              example: 2024
              type: integer
          nullable: true
        items:
          type: array
          items:
            $ref: '#/components/schemas/ItemSchema'
        payment_form:
          example: '03'
          type: string
          enum:
            - '01'
            - '02'
            - '03'
            - '04'
            - '05'
            - '06'
            - '08'
            - '12'
            - '13'
            - '14'
            - '15'
            - '17'
            - '23'
            - '24'
            - '25'
            - '26'
            - '27'
            - '28'
            - '29'
            - '30'
            - '31'
            - '99'
        payment_method:
          example: PUE
          type: string
          enum:
            - PPD
            - PUE
    InvoiceBatchError:
      type: object
      description: Why an item was rejected or did not produce an invoice.
      required:
        - code
        - message
      properties:
        code:
          type: string
          description: >-
            Machine-readable reason. See the operation descriptions for the
            possible values.
          example: CFDI40147
        message:
          type: string
          description: >-
            Human-readable reason, at most 500 characters. Stamping errors are
            in Spanish, as on `POST /invoices/income`.
          example: 'Error al timbrar la factura: El campo UsoCFDI no es válido'
    EmbeddedClientInput:
      type: object
      additionalProperties: false
      properties:
        id:
          type: string
          nullable: true
        search:
          type: object
          additionalProperties: false
          required:
            - on_key
            - on_value
          properties:
            on_key:
              type: string
            on_value:
              type: string
            auto_create:
              type: boolean
              nullable: true
            safety_check:
              type: boolean
              nullable: true
            update:
              type: boolean
              nullable: true
          nullable: true
        address:
          type: object
          additionalProperties: false
          properties:
            country:
              type: string
              nullable: true
              maxLength: 3
            street:
              type: string
              nullable: true
            zip:
              type: string
              nullable: true
            city:
              type: string
              nullable: true
            state:
              type: string
              nullable: true
            exterior:
              type: string
              nullable: true
            interior:
              type: string
              nullable: true
            municipality:
              type: string
              nullable: true
            neighborhood:
              type: string
              nullable: true
          nullable: true
        name:
          type: string
          nullable: true
        company:
          type: string
          nullable: true
        phone:
          type: string
          nullable: true
        email:
          type: string
          nullable: true
        bcc:
          type: array
          items:
            type: string
        metadata:
          type: object
          additionalProperties: true
          properties: {}
        legal_name:
          type: string
          nullable: true
        tax_id:
          type: string
          nullable: true
        use:
          type: string
          nullable: true
        tax_system:
          type: string
          nullable: true
        document_type:
          description: DIAN identification document code
          type: string
          enum:
            - ''
            - '11'
            - '12'
            - '13'
            - '21'
            - '22'
            - '31'
            - '41'
            - '42'
            - '47'
            - '48'
            - '50'
            - '91'
            - null
          nullable: true
        organization_type:
          description: 1 = persona jurídica, 2 = persona natural
          oneOf:
            - type: string
              enum:
                - ''
                - '1'
                - '2'
                - null
              nullable: true
            - type: number
              enum:
                - 1
                - 2
        tribute_code:
          description: '''01'' = responsable de IVA, ''ZZ'' = no aplica'
          type: string
          enum:
            - ''
            - '01'
            - ZZ
            - null
          nullable: true
        fiscal_responsibilities:
          description: >-
            DIAN responsabilidades fiscales (lista 53). Omitted means 'R-99-PN'
            (no responsable)
          type: array
          items:
            type: string
            enum:
              - O-13
              - O-15
              - O-23
              - O-47
              - R-99-PN
          nullable: true
        dv:
          description: NIT verification digit
          type: string
          nullable: true
          pattern: ^[0-9]?$
        municipality_code:
          description: DANE municipality code, only for clients domiciled in Colombia
          type: string
          nullable: true
          pattern: ^([0-9]{5})?$
    ItemSchema:
      description: >
        A line item on an invoice, receipt or payment. Only `quantity` is
        required; everything

        else is optional, or resolved from the referenced service when
        `id`/`search` is used.

        `id` and `search` are mutually exclusive — supplying both is a `400`.


        Unknown keys are rejected. Note there is no per-item `metadata` field.
      type: object
      additionalProperties: false
      required:
        - quantity
      properties:
        id:
          description: Service/product ID reference
          example: service_1234567890
          type: string
          nullable: true
        search:
          type: object
          additionalProperties: false
          required:
            - on_key
            - on_value
          properties:
            on_key:
              description: Field to search on (sku, name, etc.)
              example: sku
              type: string
            on_value:
              description: Value to search for
              example: CONS-001
              type: string
            auto_create:
              description: Create service if not found
              example: true
              type: boolean
              nullable: true
            safety_check:
              description: >-
                When true, prevents using multiple matching results (returns
                error). When false, uses the first result found. Default: false
              example: false
              type: boolean
              nullable: true
            update:
              type: boolean
              nullable: true
          nullable: true
        quantity:
          description: Item quantity
          example: 1
          type: number
        description:
          description: Item description
          example: Consulting services
          type: string
          nullable: true
        sku:
          description: Stock keeping unit
          example: CONS-001
          type: string
          nullable: true
        product_key:
          description: SAT product key (c_ClaveProdServ)
          example: '80141503'
          type: string
          nullable: true
        unit_key:
          description: SAT unit key (c_ClaveUnidad)
          example: E48
          type: string
          nullable: true
        unit_name:
          description: Unit name
          example: Servicio
          type: string
          nullable: true
        unit_price:
          description: Unit price
          example: 1000
          type: number
          nullable: true
        discount:
          description: >-
            Discount amount (absolute value in the item currency, not a
            percentage)
          example: 0
          type: number
          nullable: true
        taxability:
          description: SAT `c_ObjetoImp` — whether the item is subject to tax.
          example: '02'
          type: string
          enum:
            - '01'
            - '02'
            - '03'
            - '04'
            - '05'
            - '06'
            - '07'
            - '08'
            - null
          nullable: true
        taxes:
          description: Tax elements applied to this item
          type: array
          items:
            type: object
            additionalProperties: false
            properties:
              base:
                description: >-
                  Taxable base amount. Accepts number or numeric string. If
                  null, calculated automatically from item price.
                example: 100
                oneOf:
                  - type: number
                    nullable: true
                  - type: string
                    description: Numeric string accepted by the request validator.
              factor:
                type: string
                nullable: true
                example: Tasa
                description: SAT tax factor (Tasa, Cuota, Exento)
              inclusive:
                type: boolean
                nullable: true
                example: false
                description: Whether the tax is included in the unit price
              rate:
                description: Tax rate (e.g., 0.16 for 16% IVA)
                example: 0.16
                type: number
                nullable: true
              type:
                description: Type of tax
                example: IVA
                type: string
                enum:
                  - IVA
                  - ISR
                  - IEPS
                  - null
                nullable: true
              withholding:
                type: boolean
                nullable: true
                example: false
                description: Whether this is a withholding tax
            nullable: true
        third_party:
          description: Third party information for items provided by external parties
          type: object
          additionalProperties: false
          properties:
            legal_name:
              description: Third party legal name
              example: Third Party SA
              type: string
              nullable: true
            tax_id:
              description: Third party RFC (tax ID)
              example: TPR800101ABC
              type: string
              nullable: true
            tax_system:
              description: Third party tax system
              example: '601'
              type: string
              nullable: true
            zip:
              description: Third party ZIP code
              example: '03100'
              type: string
              nullable: true
          nullable: true
        item_complement:
          description: CFDI item-level complement.
          type: object
          additionalProperties: false
          properties:
            hydrocarbons:
              description: >-
                Complemento de hidrocarburos. All four fields are required when
                this object is present.
              type: object
              additionalProperties: false
              required:
                - permit_type
                - permit_number
                - fuel_code
                - fuel_sub_product
              properties:
                permit_type:
                  example: PL/12345/EXP/ES/2020
                  type: string
                permit_number:
                  example: '12345'
                  type: string
                fuel_code:
                  example: PR03
                  type: string
                fuel_sub_product:
                  example: '10'
                  type: string
              nullable: true
          nullable: true
  responses:
    Unauthorized:
      description: >
        Authentication failed. Two different bodies can come back with a `401`:


        1. **From the authentication layer**, before the endpoint runs: a raw
        object with
           `message` and — for OAuth access tokens only — `error` / `error_description`. It does
           **not** use the standardized envelope (`success` and `timestamp` are absent). Messages:
           `Unauthorized` (missing header, missing `Bearer ` prefix, unparseable token),
           `Unauthorized, missing team in token`, `Unauthorized, not a master team` and
           `Unauthorized, no matched teams` (gigstack Connect), `Invalid access token`,
           `Access token has expired. Please refresh your token.`, `Access token has been revoked`.
        2. **From the endpoint itself**: the standardized envelope with
        `error.code: unauthorized`.


        Branch on the HTTP status, not on the body shape.
      content:
        application/json:
          schema:
            anyOf:
              - $ref: '#/components/schemas/AuthMiddlewareError'
              - $ref: '#/components/schemas/UnauthorizedError'
          examples:
            missing_or_invalid_key:
              summary: Authentication layer — missing or unparseable API key
              value:
                message: Unauthorized
            oauth_token_expired:
              summary: Authentication layer — expired OAuth access token
              value:
                message: Access token has expired. Please refresh your token.
                error: token_expired
                error_description: Access token has expired. Please refresh your token.
            connect_not_master_team:
              summary: >-
                Authentication layer — `team` sent by a team without gigstack
                Connect
              value:
                message: Unauthorized, not a master team
            endpoint_envelope:
              summary: Endpoint — standardized envelope
              value:
                success: false
                error:
                  code: unauthorized
                  message: Unauthorized access
                timestamp: 1767225600000
  securitySchemes:
    bearerAuth:
      type: http
      scheme: bearer
      bearerFormat: JWT
      description: >
        **Authentication Method:** HTTP Bearer token.


        The runtime requires the literal `Bearer ` prefix — a bare token in the

        `Authorization` header is rejected with `401 unauthorized`.


        **Header Format:** `Authorization: Bearer YOUR_API_KEY`


        Your API key is a JWT. Live keys operate on live data (`livemode:
        true`);

        test keys operate on isolated test data (`livemode: false`).


        **Get your key at:**
        [app.gigstack.pro/settings?tab=api](https://app.gigstack.pro/settings?tab=api)


        **Errors:** credential failures are answered by the authentication layer
        with a raw

        `{ "message": … }` body, not the standardized envelope — `401` for a
        missing, malformed or

        expired token, `403` for a revoked key or a plan without API access. See
        the `Unauthorized`

        and `AuthForbidden` responses.

````

This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.