# QI Tech — Outros Produtos

Documentação da QI Tech em texto corrido, para colar em um LLM.
Fonte: https://docs.qitech.com.br
3 página(s).

Índice:
- Manual de Cessão de Direitos Creditórios (/documentation/iaas/negociacao_recebiveis/manual_api)
- Homologation Roadmap - BNPL (/documentation/manual_bnpl_ecommerce/)
- Manual QI Sign (/documentation/manual_qi_sign/)

---

# Manual de Cessão de Direitos Creditórios

URL: /documentation/iaas/negociacao_recebiveis/manual_api

Esse manual descreve o passo a passo envolvido na Cessão de Direitos Creditórios aos Fundos administrados pela QI CTVM. Além disso, é explicados as regras de negócio do produto e quais os principais pontos de atenção que o parceiro integrador deve ter para se ter uma integração mais rápida e eficiente.

## Pré Requisitos

1. Um Contrato de Cessão ter sido constituído e o Produto respectivo ter sido ativado (Vide APIs de **[Homologação de Cedente](/documentation/iaas/homologacao_cedente/contrato_de_cessao/pedido_de_contrato)**);

2. Somente o Gestor do Fundo, o Cedente parte do Contrato e Originadores vinculados que podem acessar esse serviço.

3. Ter armazenado a chave única de identificação do Fundo Cessionário ( fund_class_key ), e a chave única de identificação da Configuração de Cessão ( assignment_configuration_key ).

```python
BASE_URL = "/fund_class/{fund_class_key}/assignment_configuration/{assignment_configuration_key}"
```

:::info
A _**BASE_URL**_ será o caminho utilizado em todos os endpoints desta API.
:::

## Fluxo de Estados

A esteira de Cessão possui duas entidades principais onde as suas máquinas de estados possuem relações. De um lado temos o Lote, denominado assignment e de outro temos os Ativos, que chamamos de asset . Para o primeiro temos o seguinte fluxo:

![Fluxo de estados do Lote (assignment)](/img/diagrams/iaas-negociacao-recebiveis-manual-api-1.svg)

Para o Ativo, temos o seguinte:

![Fluxo de estados do Ativo (asset)](/img/diagrams/iaas-negociacao-recebiveis-manual-api-2.svg)

## Resumo da Integração

Em suma, para chegarmos no Encarteiramento dos Ativos, temos o seguinte passo a passo:

1. Criação do Lote;
2. Inserção dos Ativos;
3. Encerrar inserção de Ativos;
4. Webhook de Elegibilidade dos Ativos;
6. Envio da Documentação ;
7. Webhook de Elegiblidade do Lote;
8. Aprovação do Gestor;
9. Assinatura do Termo de Cessão;
10. Pagamento da Cessão;
11. Encarteiramento dos Ativos;

## 1 - Criação do Lote;

Para a **[criação do Lote](/documentation/iaas/negociacao_recebiveis/assignment/criacao)** é exigido apenas um identificador único, gerado no sistema do parceiro integrador. Esse será o identificador utilizado tanto nas devoluções de Webhooks quanto nas rotas para as outras funcionalidades, que serão explicadas abaixo.

É de suma importância que esse identificador seja único, e o sistema da QI CTVM não permitirá que o parceiro mande duas vezes o mesmo Lote.

## 2 - Inserção dos Ativos;

A inserção de Ativos é o processo mais delicado de toda a integração. Nessa seção iremos explicar quais as regras de negócio envolvidas na criação dos Ativos, sejam aquelas que independem do tipo, ou aquelas que são específicas para um determinado tipo.

É muito importante para o entendimento dessa API, entender o conceito do Valor do Ativo e do Valor de Compra do Ativo. Para isso vamos utilizar a seguinte notação:

**[A]** como Valor de Compra do Ativo, fornecido no raiz do objeto, e significa o quanto o Fundo deve pagar por esse Ativo.

**[B]** como a soma total do Ágios da operação. Pode ser obtido através da soma de todos os total_values dos premiums fornecidos.

**[C]** como a soma total do Deságios da operação. Pode ser obtido através da soma de todos os total_values das deductions fornecidas.

**[D]** como o Valor do Ativo, que pode ser inferido através da seguinte fórmula.

:::tip Relação
[D] = [A] - [B] + [C]
:::

### 2.1 - Regras Independentes de Tipo de Ativo

#### 2.1.1 - Compatibilidade de Tipo de Ativo com Configuração de Cessão;

Toda Configuração de Cessão é única por tipo de ativo. Nunca será possível colocar num mesmo lote CCBs e e Duplicatas por exemplo. O produto ativado que gerou a assignment_configuration_key contém um tipo de ativo especifico, e esse será o único tipo aceito em uma dada Configuração.
Caso isso seja violado retornaremos o seguinte erro:

Response Body
STATUS 400

```json title='Response Body'
{
    "code": "TRC000025"
}
```

#### 2.1.2 - Inserção em Lotes Finalizados;

Caso tente-se inserir um ativo em lotes que já foram fechados, o parceiro integrador receberá o seguinte erro:

Response Body
STATUS 400

```json title='Response Body'
{
    "code": "TRC000022"
}
```

#### 2.1.3 - Validação de Código Postal;

O código postal do objeto de endereço do tomador da operação deve ser válido. Portanto caso algum inexistente seja fornecido, a requisição não será aceita e devolverá o seguinte erro:

Response Body
STATUS 404

```json title='Response Body'
{
    "code": "TRC000070"
}
```

#### 2.1.4 - Unicidade de External ID;

Um mesmo ativo não pode ser cedido 2 vezes pelo parceiro. Portanto caso esse ativo já exista em nossa base e não tenha sido descartado, o seguinte erro será levantado:

Response Body
STATUS 409

```json title='Response Body'
{
    "code": "TRC000054"
}
```

### 2.2 - Regras para Operações de Crédito

As Operações de Crédito são aquele ativos que derivam de um compromisso firmado por um Sacado, que toma dinheiro a uma determinada taxa, e honra um compromisso de pagamento de acordo com um determinado fluxo. Portanto esses ativos sempre possuem um principal em aberto, e uma taxa de juros que aumenta esse valor. A estrutura de dados exigida na Criação de uma Operação de Crédito encontra **[nesta página](/documentation/iaas/negociacao_recebiveis/asset/criacao_co)**.

#### 2.2.1 - Divergência Valor do Ativo vs Principal em Aberto;

Para uma Operação de Crédito é necessário que o Valor do Ativo seja sempre maior ou igual ao Principal em Aberto (Campo principal_value do Objeto de Operação de Crédito). O erro relacionado a essa regra de negócio é:

Response Body
STATUS 409

```json title='Response Body'
{
    "code": "TRC000054"
}
```

#### 2.2.2 - Divergência Valor de Emissão vs Principal em Aberto;

O valor de Emissão do Contrato deve ser sempre maior ou igual ao principal em Aberto. O erro relacionado a essa regra de negócio é:

Response Body
STATUS 409

```json title='Response Body'
{
    "code": "TRC000054"
}
```

#### 2.2.3 - Parcelas Sequenciais;

Todas as parcelas de uma operação de crédito devem ser ordenadas em ordem crescente de data de vencimento ( maturity_date ) e com os números ( installment_number ) sequenciais. Portanto se o fluxo começa com a parcela número 1, a próxima deve ser a 2, a seguinte a 3, e assim por diante.

Os erros relacionados a essas regras são respectivamente:

Response Body
STATUS 409

```json title='Response Body'
{
    "code": "TRC000054"
}
```

Response Body
STATUS 409

```json title='Response Body'
{
    "code": "TRC000054"
}
```

#### 2.2.4 - Objetos pré e pós fixados;

De acordo com o tipo de juros ( interest_rate_type ) de uma operação, é preciso fornecer os objetos de pré e/ou pós fixados. Caso o tipo de juros seja pré fixado, é necessário fornecer **apenas** o objeto de pré fixado, enquanto na pós fixada, o objeto de pós fixado é **obrigatório** e o de pré fixado é **opcional**. Por exemplo, se a operação de

<!-- #### 2.2.5 - Fluxo de Pagamentos de Operações Pré Fixadas;
DEVEM EXISTIR APENAS O VALOR DE FACE
VP TEM QUE BATER VALOR DO ATIVO
#### 2.2.5 - Fluxo de Pagamentos de Operações Pós Fixadas;
DEVEM EXISTIR SEMPRE O VALOR DE PRINCIPAL;
TAMBÉM DEVE EXISTIR O VALOR DE FACE PRA VENCIDAS;
PRINCIPAL TOTAL == PRINCIAPL EM ABERTA -->

## 3 - Encerrar inserção de Ativos;

Após todos os ativos do Lote terem sido criados, o parceiro pode comandar o **[encerramento da Inserção de Ativos](/documentation/iaas/negociacao_recebiveis/assignment/fechamento)**. Esse processo é importante para que o sistema da QI CTVM saiba que a partir desse momento, quando todos os ativos tiverem sido devidamente analisados pela Elegibilidade, e com toda a documentação fornecida, pode-se analisar a Elegibilidade do Lote como um todo.

:::info
Não é necessário esperar o Webhook de todos os Ativos para realizar essa ação. No momento em que não se desejar mais inserir ativos, pode-se executar esse comando.
:::

## 4 - Webhook de Elegibilidade dos Ativos;

De acordo com o que os Ativos forem sendo analisados pelas regras de Elegibilidade do Fundo, o sistema devolve os **[Webhooks](/documentation/iaas/negociacao_recebiveis/asset/webhooks)**, 1 a 1. Esses Webhooks serão identificados com o identificador único do ativo, fornecido pelo parceiro no momento de criação.

Apenas duas possibilidades podem incorrer dessa análise, a **aprovação** dos ativos, ou a **reprovação**. Caso aconteça o primeiro, o Ativo irá seguir a sua esteira, ficando sujeito a inserção de documentos, caso contrário, ele irá para o Estado de descartado, e não irá seguir para os próximos passos.

## 5 - Envio da Documentação;

Com a aprovação de um determinado ativo na Elegibilidade, o parceiro pode seguir com a **[inserção dos documentos](/documentation/iaas/negociacao_recebiveis/asset/documents)** exigidos pelo produto. O envio deve ocorrer com uma requisição para cada documento necessário. O conteúdo será transmitido através de um Base64 do binário, portanto viabilizando que isso seja feito através de JSON, como todo o restante das APIs do nosso sistema.

Note que para realizar essa requisição é exigido, além do binário do arquivo, o tipo de documento desse arquivo. O Ativo só seguirá a esteira quando todos os documento exigidos forem enviados. Quando isso acontecer, este irá seguir para o estado de Pré Aprovado ( pre_approved ).

:::warning Aviso
Os documentos exigidos dependem do tipo de Produto e do Regulamento do Fundo. Isso pode ser obtido recuperando o Produto do Contrato de Cessão, que foi ativado para obtenção da assignment_configuration_key desse respectivo lote.
::: 

:::info
Não é necessário ter comandado o Encerramento da Inserção de Ativos. Caso queira vincular a lógica do Envio de Documentos ao Recebimento do Webhook, é totalmente possível e recomendado.
:::

## 6 - Webhook de Elegiblidade do Lote;

Assim que um determinado Lote que ja teve a inserção de ativos encerrada, e todos os seus Ativos tiverem ou descartado ou pré-aprovados, ele irá seguir para uma análise de Elegibilidade do Lote todo. Mesmo que todos os Ativos ali tenha sido aprovados, pode ser que o Lote como um todo cause algum desenquadramento do Fundo. Por isso é necessário um segundo passo na execução da Elegibilidade.

De forma similar ao Ativo, podemos ter duas opções de resultado decorrido da Elegibilidade, a aprovação ou a reprovação. O resultado será informado através de um **[Webhook](/documentation/iaas/negociacao_recebiveis/assignment/webhooks)**, mas dessa vez identificado com o external_id do Lote.

Caso o Lote seja reprovado, ele será descartado, e o processo finaliza-se. Caso contrário, ele seguirá para uma etapa de análise e aprovação do Gestor.

## 7 - Aprovação do Gestor;

A aprovação do Gestor deve ser feita através de uma **[requisição especifica](/documentation/iaas/negociacao_recebiveis/assignment/aprovacao)**, ou através do nosso **[Portal](https://manager-dash.qidtvm.com.br/)**. Caso o Lote seja negado, ele será descartado e o processo finaliza-se. Caso contrário, o sistema providencia a geração do Termo de Cessão e o envia para assinatura, levando o Lote para o Estado pending_assignment_term_signature , e assim ficará ate que todas as partes relacionadas assinem o Documento.

## 8 - Assinatura do Termo de Cessão;

Uma vez assinado, enviamos um **[Webhook](/documentation/iaas/negociacao_recebiveis/assignment/webhooks)** avisando que o Termo foi assinado e deve prosseguir para o pagamento, ficando, portanto, em pending_payment

## 9 - Pagamento da Cessão;

Nesse momento, o sistema paga o Cedente, o montante total da Cessão, que é a soma de todos os total_purchase_value dos ativos não descartados, na conta que foi informada no momento de ativação do Produto. Uma vez que esse pagamento for confirmado, enviamos um **[Webhook](/documentation/iaas/negociacao_recebiveis/assignment/webhooks)**, e os ativos começam a serem encarteirados.

## 10 - Encarteiramento dos Ativos;

Por fim, assim que todos os ativos forem devidamente encarteirados, o Lote se tornará completed , e a partir desse momento o parceiro integrador tem a total certeza de que todos aqueles ativos já se encontram devidamente dentro do estoque do Fundo.

---

# Homologation Roadmap - BNPL

URL: /documentation/manual_bnpl_ecommerce/

## Summary
This document guides clients through integrating Buy Now Pay Later (BNPL) with the QI Tech platform. It outlines the essential steps and provides answers to common questions.

## 1. Document Inquiry
The document inquiry can be performed using the following request:

### Request Body Upload

ENDPOINT /document/[document_key]/url
METHOD GET

Testar no Playground

### Path Params

| Field          | Description                              |
|--------------- |------------------------------------------|
| `document_key` | Unique document key                      |

:::caution Attention
The document URL will be generated with an expiration period of 10 minutes.
:::

Response Body

```json
{
	"document_key": "8a1e62f3-7add-4240-a51d-e0f1a2f421fa",
	"document_url": "expirable_url",
	"signed_document_url": "expirable_url",
	"expiration_datetime": "2024-05-01T01:00:00.000Z"
}
```

## 2. Document upload
To receive the document_key for the debt issuance documents, you must upload them using the following request:

### Request Body Upload

ENDPOINT /upload
METHOD POST

Testar no Playground

Response Body

```json
{
  "document_key": "cfbc8469-89ea-4a80-9f64-ba7b1566c68b",
  "document_md5": "cd451103fa512frc98ce684d3896698c"
}
```

:::caution Atenção
Remember to save the **document_key**, as this key is required to query the document.
:::

### API call example

Example for uploading an image from a URL.

**Python**

```python

import jwt
import hashlib
import requests
from requests_toolbelt.multipart.encoder import MultipartEncoder
import json
from datetime import datetime

BASE_URL = "https://api-auth.sandbox.qitech.app"
API_KEY = "4c268c0a-53ff-429b-92b6-47ef98a6d89a" # This key is an example; please use your own key.
CLIENT_PRIVATE_KEY = ''''
-----BEGIN EC PRIVATE KEY-----
MIHbAgEBBEHh1hIeOPE5XNNhn6bxRAmVswsPZ0wZCmzVvP8Tl/LZK9ofVmRVGzll
srU1uezJEyHKYdOHrE2p52xUj+pHzjJvb6AHBgUrgQQAI6GBiQOBhgAEAAofUz1J
hBSOyGHLsnV9Sz0DSWmhl7U+ljqbfa8PKVFWSV3w16I1v2zME5/UzUhHn1gWsjnv
7/ekcLLAQbvqMPNXAfjIhFXLAPzqbB9iCuVua1v0Vgy52rBemOWrJka/Ws2bnKR8
h1N1OxOYeYr6C2jqMygBLktKMAs+282CEiEb4bIv
-----END EC PRIVATE KEY----- 
''' # This key is an example; please use your own key.

def get_document(url):
    try:
        response = requests.get(url)
        return response.content
    except Exception as error:
        print("Error fetching document:", error)
        raise

def upload_document(array_buffer):
    endpointeger= "/upload"
    method = "POST"
    timestamp = datetime.utcnow().strftime("%Y-%m-%dT%H:%M:%S.%f")[:-3] + "Z"
    md5_hash = hashlib.md5(array_buffer).hexdigest()

    jwt_header = {
        "typ": "JWT",
        "alg": "ES512",
    }

    jwt_body = {
        "payload_md5": md5_hash,
        "timestamp": timestamp,
        "method": method,
        "uri": endpoint,
    }

    encoded_header_token = jwt.encode(jwt_body, CLIENT_PRIVATE_KEY, algorithm="ES512", headers=jwt_header)

    signed_header = {
        "Authorization": encoded_header_token,
        "API-CLIENT-KEY": API_KEY,
        "Content-Type": "multipart/form-data",
    }

    url = f"{BASE_URL}{endpoint}"
    multipart_data = MultipartEncoder(
        fields={'file': ('image.jpeg', array_buffer, 'image/jpeg')}
    )
    signed_header['Content-Type'] = multipart_data.content_type

    try:
        response = requests.post(url, headers=signed_header, data=multipart_data)
        response_data = response.json()
        document_key = response_data.get('document_key')
        print(f'Response data is: {response_data} and document_key is: {document_key}')
        return document_key
    except Exception as error:
        print('Error:', error)
        raise

def main():
    file_url = "{FILE_URL}"

    document_buffer = get_document(file_url)

    document_key = upload_document(document_buffer)

    print("document_key is", document_key)

if __name__ == "__main__":
    main()

```
  

**Node.js**

```js
const jwt = require('jsonwebtoken')
const crypto = require('crypto')
const axios = require('axios')
const FormData = require('form-data')
const fs = require('fs')
const fetch = require('node-fetch')

async function getDocument(url) {
  try {
    const response = await axios.get(url, { responseType: 'arraybuffer' })
    return response.data
  } catch (error) {
    console.error('Error fetching document:', error)
    throw error
  }
}

async function uploadDocument(arrayBuffer) {
  const endpointeger= '/upload'
  const method = 'POST'
  const timestamp = new Date().toISOString()
  const md5_hash = crypto.createHash('md5').update(arrayBuffer).digest('hex')
  const client_private_key = `-----BEGIN EC PRIVATE KEY-----
    MIHbAgEBBEHh1hIeOPE5XNNhn6bxRAmVswsPZ0wZCmzVvP8Tl/LZK9ofVmRVGzll
    srU1uezJEyHKYdOHrE2p52xUj+pHzjJvb6AHBgUrgQQAI6GBiQOBhgAEAAofUz1J
    hBSOyGHLsnV9Sz0DSWmhl7U+ljqbfa8PKVFWSV3w16I1v2zME5/UzUhHn1gWsjnv
    7/ekcLLAQbvqMPNXAfjIhFXLAPzqbB9iCuVua1v0Vgy52rBemOWrJka/Ws2bnKR8
    h1N1OxOYeYr6C2jqMygBLktKMAs+282CEiEb4bIv
    -----END EC PRIVATE KEY-----`; // This key is an example; please use your own key.
  const api_key = '4c268c0a-53ff-429b-92b6-47ef98a6d89a' // This key is an example; please use your own key.

  try {
    const jwt_header = {
      typ: 'JWT',
      alg: 'ES512',
    }

    const jwt_body = {
      payload_md5: md5_hash,
      timestamp: timestamp,
      method: method,
      uri: endpoint,
    }

    const encoded_header_token = jwt.sign(jwt_body, client_private_key, {
      algorithm: 'ES512',
      header: jwt_header,
    })

    const signed_header = {
      AUTHORIZATION: encoded_header_token,
      'API-CLIENT-KEY': api_key,
      'Content-Type': 'multipart/form-data',
    }

    const url = `${base_url}${endpoint}`
    const formData = new FormData()
    formData.append('file', Buffer.from(arrayBuffer), {
      filename: 'image.jpeg',
    })

    fetch(url, {
      method: 'POST',
      headers: signed_header,
      body: formData,
    })
      .then(data => {
        console.log('Response data is: ' + data)

        return data.document_key
      })
      .catch(error => {
        console.log('Error: ' + error)
      })
  } catch (error) {
    console.error('Error:', error)
  }
}

async function main() {
  const fileUrl = '<URL_LINK_TO_DOCUMENT_IMAGE>'
  const documentBuffer = await getDocument(fileUrl)
  const documentKey = await uploadDocument(documentBuffer)

  console.log('Document key is: ' + documentKey)
}

main()
```

- OBS: The example above uses the library [node-fetch](https://www.npmjs.com/package/node-fetch) to make the call, but you can use the library of your choice. The important thing is that the call must be made using the POST method, with the `Content-Type` header set to `multipart/form-data` and the body must be a FormData object with the key `file` and the value as the file binary to be sent.

:::warning Aviso
The 'Axios' library has a bug that causes FormData to be sent empty. The issue can be seen on the [GitHub repository](https://github.com/axios/axios/issues/5986). If this problem has not yet been resolved at the time of your integration, we suggest using the 'node-fetch' library to make this call.
:::

  

## 3. Debt Simulation

### Request Debt Simulation

At QI Tech, we provide our clients with the ability to simulate the values of a credit operation before it is actually issued. The simulation follows the same pattern as the debt issuance request, but it is not necessary to provide the debtor’s registration and disbursement account details. The following endpoint is a simplified version of /debt_simulation, but much more optimized. It is used to calculate only one disbursement option.

ENDPOINT /v2/credit_operation/simulation
METHOD POST

Testar no Playground

Request Body

```json
{
    "credit_operation_type": "ccb",
    "disbursed_issue_amount": 2800,
    "disbursement_date": "2025-09-24",
    "first_due_date": "2025-10-24",
    "force_installments_on_workdays": true,
    "interest_type": "pre_price_days",
    "issuer_person_type": "natural",
    "monthly_interest_rate": 0.04488,
    "number_of_installments": 12,
    "principal_amortization_month_period": 1
}
```

### Request Body Details

| Field  | Type   | Description | Max. Char. |
|---|--- |---|---|
| **credit_operation_type***                 | string    |   Type of credit agreement      |  **[Credit Operation Type Enumerator](#credit-operation-type-enumerator)**           |
| **disbursed_issue_amount***                | float   | The value actually released to the borrower      | 15,2           |
| **disbursement_date***                     | string    | The specific date the loan funds are made available      | 10            |
| **first_due_date***                        | string    | Due date of the first installment      | 10             |
| **force_installments_on_workdays***        | boolean | If true, ensures all installment due dates are moved to the next business day  |       5       |
| **interest_type***                         | string    |  Amortization method      | **[Interest Type Enumerator ](#interest-type-enumerator)**           |
| **issuer_person_type***                    | string    | Defines whether the issuer is an individual (natural person) or a legal entity (corporation/business)     | **[Person Type Enumerator](#person-type-enumerator)**           |
| **monthly_interest_rate***                 | float   |The percentage charged on a principal balance over a one-month period    | 10,6           |
| **number_of_installments***                | integer    | Number of installments      | 3            |
| **principal_amortization_month_period***   | integer    | Period, in months, between installments      | 1            |

### Response Debt Simulation

STATUS 200

Response Body

```json
    {
        "disbursement_date": "2025-09-24",
        "issue_amount": 2821.32,
        "interest_type": "pre_price_days",
        "assignment_amount": 2829.78,
        "base_iof": 10.6,
        "total_iof": 21.32,
        "additional_iof": 10.72,
        "cet": 5.09,
        "annual_cet": 81.39,
        "first_due_date": "2025-10-24",
        "disbursed_amount": 2800,
        "prefixed_interest_rate": {
            "annual_rate": 0.6935459998,
            "daily_rate": 0.0014644728,
            "interest_base": "calendar_days",
            "monthly_rate": 0.04488
        },
        "tax_configuration": {
            "base_rate": 8.2e-05,
            "additional_rate": 0.0038
        },
        "fees": [
            {
                "amount": 0.3,
                "fee_amount": 8.46,
                "amount_type": "percentage",
                "fee_type": "spread",
                "type": "internal"
            }
        ],
        "installments": [
            {
                "due_date": "2025-10-24",
                "amount": 1507.4,
                "due_principal": 2821.32,
                "due_interest": 0,
                "has_interest": true,
                "period": 1,
                "period_workdays": 1.1,
                "calendar_days": 30,
                "workdays": 22,
                "installment_number": 1,
                "period_to_disbursement": 1,
                "prefixed_amount": 126.62083829,
                "period_workdays_to_disbursement": 1.1,
                "calendar_days_to_disbursement": 30,
                "workdays_to_disbursement": 22,
                "tax_amount": 3.39671674,
                "principal_amortization_amount": 1380.77916171
            },
            {
                "due_date": "2025-11-24",
                "amount": 1507.4,
                "due_principal": 1440.54083829,
                "due_interest": 0,
                "has_interest": true,
                "period": 1,
                "period_workdays": 1,
                "calendar_days": 31,
                "workdays": 20,
                "installment_number": 2,
                "period_to_disbursement": 2,
                "prefixed_amount": 66.85916171,
                "period_workdays_to_disbursement": 2.1,
                "calendar_days_to_disbursement": 61,
                "workdays_to_disbursement": 42,
                "tax_amount": 7.20558527,
                "principal_amortization_amount": 1440.54083829
            }
        ]
    }
```

### Response Body Details
| Field                                   | Type   | Description                                                                                                                     |
|-----------------------------------------|--------|-------------------------------------------------------------------------------------------------------------------------------|
| **annual_cet**                          | float  | Total effective cost expressed as a decimal per year                                                                                | -            |
| **assignment_amount**                   | float  | Acquisition value of the credit operation                                                                                     | -            |
| **cet**                                 | float  | Total effective cost expressed as a decimal per month                                                                                | -            |
| **fees**                                | object | **[Object Fees](#object-fees)** - List of QI Tech fees charged on the operation                            | -            |
| **disbursed_amount**                    | float  | Amount disbursed in the credit operation                                                                                     | -            |
| **disbursement_date**                   | string   | Disbursement date of the operation                                                                                                | -            |
| **installments**                        | array   | **[Object Installments](#object-installments)** - Installments of the operation                                                        | -            |
| **interest_type**                       | string   | **[Enumerator Interest Type](#enumerator-interest-type)** - Amortization method and interest calculation method                 | -            |
| **additional_iof**                      | float  |A fixed-rate tax applied to the transaction principal, independent of the duration of the credit operation                                                                               | -            |
| **base_iof**                            | float  |  The taxable amount or principal value used as the basis for calculating the Tax on Financial Operations  | -            |
| **total_iof**                           | float  | The total amount of Tax on Financial Operations applied to the transaction   | -            |
| **issue_amount**                        | float  | Issue/nominal value of the credit operation                                                                               | -            |
| **tax_configuration**                   | object | **[Object Tax Configuration](#object-tax-configuration)** - Rate iof values                                             | -            |
| **first_due_date**                      | string   | Due date of the first installment                                                                                        | -            |
| **prefixed_interest_rate**              | object | **[Object Interest Rate](#object-interest-rate)** - Nominal interest rate                              | -            |

## 4. Debt issuance for natural persons

This endpoint issues the debt and processes the contract signature via opt-in. Disbursement occurs automatically immediately after issuance. Pre-registration is not required; simply provide the borrower's details during the debt request.

### Request

ENDPOINT /signed_debt
METHOD POST

Testar no Playground

Request Body

```json
{
   "additional_data":{
      "contract":{
         "contract_number":"TIK11267101100",
         "signed":true,
         "signatures":[
            {
               "signer":{
                  "name":"Alan Mathison Turing",
                  "phone":{
                     "number":"912345678",
                     "area_code":"11",
                     "country_code":"055"
                  },
                  "email":"alan.turing@email.com",
                  "document_number":"96969879003"
               },
               "signature":{
                  "ip_address":"168.211.22.84",
                  "timestamp":"27-10-2025 11:07:15",
                  "signature_file":{
                     "file_url":"http://qitech.com.br/signature.pdf",
                     "file_type":"pdf"
                  },
                  "geolocation":{
                     "long":"-46.63611",
                     "lat":"-23.5475"
                  },
                  "fingerprint_device":{
                     "device":"Web",
                     "model":"iPhone 11",
                     "os_version":"iOS 15.2",
                     "browser":"Chrome",
                     "browser_version":"120.0.0.0",
                     "language":"pt-BR",
                     "timezone":"America/Sao_Paulo",
                     "gpu_renderer":"Apple GPU"
                  }
               }
            }
         ]
      }
   },
   "financial":{
      "number_of_installments":2,
      "credit_operation_type":"ccb",
      "interest_type":"pre_price_days",
      "monthly_interest_rate":0.07,
      "disbursed_amount":200,
      "fine_configuration":{
         "contract_fine_rate":0.02,
         "monthly_rate":0.15,
         "interest_base":"calendar_days"
      },
      "interest_grace_period":0,
      "disbursement_date":"2026-02-06",
      "first_due_date":"2026-03-06",
      "principal_grace_period":0
   },
   "disbursement_bank_accounts":[
      {
         "account_digit":"5",
         "document_number":"32402502000135",
         "bank_code":"329",
         "account_number":"00002",
         "percentage_receivable":100,
         "branch_number":"0001",
         "name":"Accout Name"
      }
   ],
   "requester_identifier_key":"6b558426-6b6c-4c9e-bfb3-5734fe45a651",
   "purchaser_document_number":"32402502000135",
   "borrower":{
      "email":"alan.turing@email.com",
      "document_identification":"494598fd-c226-4332-a500-591ae3884673",
      "document_identification_back":"494598fd-c226-4332-a500-591ae3884673",
      "birth_date":"1990-11-20",
      "person_type":"natural",
      "is_pep":false,
      "profession":"Public server",
      "individual_document_number":"96969879003",
      "address":{
         "city":"São Paulo",
         "neighborhood":"CENTRO",
         "street":"Avenida Feliz",
         "complement":"AP 801",
         "postal_code":"49026100",
         "state":"SP",
         "number":"1000"
      },
      "phone":{
         "country_code":"055",
         "number":"912345678",
         "area_code":"11"
      },
      "mother_name":"MARIA TURING",
      "document_identification_number":"96969879003",
      "name":"Alan Mathison Turing"
   }
}
```

### Request Body Details

| Field  | Type   | Description | Max. Char. |
|---|--- |---|---|
| **borrower** *                  | object | Borrower Object - The debtor of the credit operation         | **[Borrower Object](#borrower-object)** |
| **disbursement_bank_account** * | object |  Technical details of the bank account where the operation funds will be deposited.                                                                                 | **[Disbursement Bank Account Object](#disbursement-bank-account-object)**          |
| **financial** *                 | object | Contains all financial details and calculation parameters for the operation. | **[ Financial Object](#financial-object)**            |
| **purchaser_document_number** * | string | Assignee's Tax ID – The buyer of the credit operation (FIDC/Receivables Investment Fund).   | 14           |
| **additional_data** * | object | Assignee's Tax ID – The buyer of the credit operation (FIDC/Receivables Investment Fund).   | **[ Additional Data Object](#additional-data-object)**          |

### Borrower Object 

|Field|Type|Description|Max. Char.|
|---|--- |---|---|
|name *|string|Full name of the borrower|100|
|email|string|Borrower's electronic mail address|254|
|phone|object| Borrower's contact telephone details| **[Phone Object](#phone-object)**|
|is_pep *|boolean|Politically Exposed Person (PEP) indicator|5|
|address *|object| Borrower's residential address details| **[Address Object](#address-object)** |
|role_type *|enum|The role of the person in the operation. Default: issuer|-|
|birth_date *|date|Borrower's date of birth (Format: "YYYY-MM-DD")|10|
|mother_name *|string|Borrower's mother's full name|100|
|nationality|string|Borrower's nationality|50|
|person_type *|string|Person classification|7|
|individual_document_number *|string|Borrower's Tax ID (CPF) - numbers only|11|
|document_identification *|string|DOCUMENT_KEY of the uploaded identification document (RG or CNH)|36|
|document_identification_back|string|DOCUMENT_KEY of the uploaded back side of the identification document|36|

### Address Object

|Field|Type|Description|Max. Char.|
|---|--- |---|---|
|city *|string|City name of the address|100|
|state *|string|State abbreviation (two uppercase characters)|2|
|number *|string|Street number|10|
|street *|string|Street name|100|
|complement *|string|Address complement (free text)|100|
|postal_code *|string|Postal code (CEP) - numbers only|8|
|neighborhood *|string|Neighborhood or district name|100|

### Phone Object 

|Field|Type|Description|Max. Char.|
|---|--- |---|---|
|number *|string|Subscriber's phone number|9|
|area_code *|string|Two-digit regional area code (e.g., "11")|2|
|country_code *|string|International dialing code (e.g., "055")|3|

### Disbursement Bank Account Object
|Field|Type|Description|Max. Char.|
|---|--- |---|---|
|name|string|Account holder's full name|50|
|document_number|string|Account holder's Tax ID (CPF)|11|
|bank_code *|string|Financial institution's COMPE code|3|
|branch_number *|string|Branch number (do not include the branch check digit!)|4|
|account_number *|string|Account number (do not include the account check digit!)|10|
|account_digit *|string|Account check digit (use zero instead of letters)|1|
|account_type|enum|Account Type Enumerator - Type of the bank account| **[Account Type Object](#account-type-object)**|

### Additional Data Object 

|Field|Type|Description|Max. Char.|
|---|--- |---|---|
|contract_number *|string|The unique identifier or reference number of the contract|12|
|signed *|boolean|Indicates if the contract has been successfully signed|5|
|signatures *|array|List of digital signature evidence objects (Opt-in)|-|
|name *|string|Full name of the signer|255|
|document_number *|string|Signer's tax identification number (CPF)|11|
|email *|string|Electronic mail address of the signer|100|
|area_code *|string|Two-digit regional area code (e.g., "11")|2|
|number *|string|Subscriber's phone number|9|
|country_code *|string|International dialing code (e.g., "055")|3|
|ip_address *|string|The IP address used during the signature process|45|
|timestamp *|string|Date and time of the signature (DD-MM-YYYY HH:mm:ss)|19|
|file_url *|string|Direct link to the signed contract document (PDF)|2048|
|file_type *|string|Format of the signature file (e.g., "pdf")|4|
|long *|string|Geographic longitude coordinate of the signature location|20|
|lat *|string|Geographic latitude coordinate of the signature location|20|
|fingerprint_device|string|Unique digital identifier of the device used|-|

### Response

The response to this debt request will return the payment plan as well as a **DEBT-KEY**, which is the identifier of the debt in QI SCD.

STATUS 201

Response Body

```json
{
    "webhook_type": "debt",
    "key": "a6dbf441-31b0-44df-9bb8-593553de2c45",
    "status": "issued",
    "event_datetime": "2026-02-10 00:01:20",
    "data": {
        "borrower": {
            "name": "Alan Mathison Turing",
            "document_number": "96969879003",
            "related_party_key": "6995ff6e-27c2-47e9-b4bf-640934b56b23"
        },
        "contract": {
            "document_key": null,
            "number": "TIK11267101100",
            "urls": [],
            "signature_information": [
                {
                    "signer_name": "Alan Mathison Turing",
                    "signer_document_number": "96969879003",
                    "signer_role": "issuer",
                    "signer_email": "alan.turing@email.com",
                    "signer_external_key": null,
                    "signature_url": null
                }
            ]
        },
        "requester_identifier_key": "6b558426-6b6c-4c9e-bfb3-5734fe45a651",
        "iof_charge_method": "financed",
        "collaterals": [],
        "contract_fees": [
            {
                "fee_type": "spread",
                "fee_amount": 0.6
            }
        ],
        "external_contract_fees": [],
        "external_contract_fee_amount": 0,
        "net_external_contract_fee_amount": 0,
        "contract_fee_amount": 0.6,
        "issue_amount": 201.49,
        "assignment_amount": 202.09,
        "cet": "7,6600%",
        "annual_cet": "142,5744%",
        "number_of_installments": 2,
        "base_iof": 0.73,
        "additional_iof": 0.76,
        "total_iof": 1.49,
        "ipoc_code": "324025020203196969879003TIK11267101100",
        "prefixed_interest_rate": {
            "annual_rate": 1.252191589,
            "created_at": "2026-02-10T00:01:18",
            "daily_rate": 0.0022578334,
            "interest_base": "calendar_days",
            "monthly_rate": 0.07
        },
        "installments": [
            {
                "accrual_reference_date": null,
                "additional_costs": [],
                "advanced_paid_amount": 0,
                "bank_slip_key": null,
                "business_due_date": "2026-03-06",
                "calendar_days": 28,
                "digitable_line": null,
                "due_date": "2026-03-06",
                "due_interest": 0,
                "due_principal": 201.49,
                "fine_amount": null,
                "has_interest": true,
                "installment_history": [],
                "installment_key": "5c121fac-20f8-4481-b7b6-d0647a0ce524",
                "installment_number": 1,
                "installment_payment": [],
                "installment_status": "created",
                "installment_type": "principal",
                "original_due_principal": 201.49,
                "original_pre_fixed_amount": 13.13403553,
                "original_principal_amortization_amount": 97.92596447,
                "original_total_amount": 111.06,
                "paid_amount": 0,
                "paid_at": null,
                "post_fixed_amount": 0,
                "pre_fixed_amount": 13.13403553,
                "principal_amortization_amount": 97.92596447,
                "qr_code_key": null,
                "qr_code_url": null,
                "renegotiation_proposal_key": null,
                "tax_amount": 0.22483801,
                "total_accrual_amount": null,
                "total_amount": 111.06,
                "total_paid_amount": 0,
                "workdays": 18
            },
            {
                "accrual_reference_date": null,
                "additional_costs": [],
                "advanced_paid_amount": 0,
                "bank_slip_key": null,
                "business_due_date": "2026-04-06",
                "calendar_days": 31,
                "digitable_line": null,
                "due_date": "2026-04-06",
                "due_interest": 0,
                "due_principal": 103.56403553,
                "fine_amount": null,
                "has_interest": true,
                "installment_history": [],
                "installment_key": "a8a21d7a-481e-43ba-b115-fd89253bcde9",
                "installment_number": 2,
                "installment_payment": [],
                "installment_status": "created",
                "installment_type": "principal",
                "original_due_principal": 103.56403553,
                "original_pre_fixed_amount": 7.49596447,
                "original_principal_amortization_amount": 103.56403553,
                "original_total_amount": 111.06,
                "paid_amount": 0,
                "paid_at": null,
                "post_fixed_amount": 0,
                "pre_fixed_amount": 7.49596447,
                "principal_amortization_amount": 103.56403553,
                "qr_code_key": null,
                "qr_code_url": null,
                "renegotiation_proposal_key": null,
                "tax_amount": 0.5010428,
                "total_accrual_amount": null,
                "total_amount": 111.06,
                "total_paid_amount": 0,
                "workdays": 20
            }
        ],
        "total_pre_fixed_amount": 20.63
    }
}
```

## 5. Webhooks

After the successful response, you will receive webhooks for the CCB and for disbursement success or failure. How the CCB and signature are notified depends on whether generation is **synchronous** or **asynchronous**:

- **Synchronous CCB generation:** the Signature webhook (`signature_finished`) is sent during this flow, with the signed CCB URL.
- **Asynchronous CCB generation:** two debt webhooks may be sent instead: one with status `issued` (full debt data after issuance) and one with status `generated_document` (CCB URL and signed document). **If these asynchronous webhooks are triggered, the Signature finished (`signature_finished`) webhook is not sent.**

You will still receive a webhook indicating the disbursement’s success or failure (or cancellation), as described below.

### Signature webhook (synchronous)

In synchronous CCB mode generation, the Signature webhook is delivered in this flow.

Response Body

```json
{
    "key": "1ebd4a90-2721-4c39-a399-427fa16bca65",
    "status": "signature_finished",
    "webhook_type": "debt",
    "event_datetime": "2025-10-27 17:09:33",
    "contract_document_key":"9f9ab7e4-3605-4f92-89ca-0d9c2a17fba4",
    "requester_identifier_key":"7349e218-0646-483b-b75b-3300f7212176",
    "signed_contract_url": "https://storage.googleapis.com/sandbox-doc-api/documents/c8b191cb-7b90-4e37-9280-397a597babc1/RAFAELAEBENJAMINFINANCEIRALTDA-ALAN_MATHISON_TURING-CCB-TIK11267101212-20251027170925_signed.pdf"
}

```

### Issued webhook (asynchronous)

When CCB generation runs asynchronously, this webhook notifies issuance with the full debt payload (`status`: `issued`). It replaces the synchronous Signature webhook in that flow; see the introduction at the top of this section.

Response Body

```json
{
    "key": "1e90d231-e569-49cb-9bf0-3409bb45a43a",
    "data": {
      "cet": "33,6800%",
      "base_iof": 0.19,
      "borrower": {
        "name": "teste",
        "document_number": "68752867005",
        "related_party_key": "186e58d3-1e82-400c-88b5-fd9c087f80bb"
      },
      "contract": {
        "urls": [],
        "number": "MSCT6YJ3MO51",
        "document_key": null,
        "signature_information": [
          {
            "signer_name": "teste",
            "signer_role": "issuer",
            "signer_email": "teste@gmail.com",
            "signature_url": null,
            "signer_external_key": null,
            "signer_document_number": "06160405390"
          }
        ]
      },
      "ipoc_code": "324025020203106160405390MSCT6YJ3MO51",
      "total_iof": 0.38,
      "annual_cet": "3.156,5450%",
      "collaterals": [],
      "installments": [
        {
          "paid_at": null,
          "due_date": "2026-05-27",
          "workdays": 31,
          "tax_amount": 0.1859022,
          "fine_amount": null,
          "paid_amount": 0.0,
          "qr_code_key": null,
          "qr_code_url": null,
          "due_interest": 0.0,
          "has_interest": true,
          "total_amount": 76.82,
          "bank_slip_key": null,
          "calendar_days": 45,
          "due_principal": 50.38,
          "digitable_line": null,
          "installment_key": "4a940fc6-45d8-43a4-9f62-1b8cf36bf5d9",
          "additional_costs": [],
          "installment_type": "principal",
          "pre_fixed_amount": 26.44,
          "business_due_date": "2026-05-27",
          "post_fixed_amount": 0,
          "total_paid_amount": 0.0,
          "installment_number": 1,
          "installment_status": "created",
          "installment_history": [],
          "installment_payment": [],
          "advanced_paid_amount": 0.0,
          "total_accrual_amount": null,
          "original_total_amount": 76.82,
          "accrual_reference_date": null,
          "original_due_principal": 50.38,
          "original_pre_fixed_amount": 26.44,
          "renegotiation_proposal_key": null,
          "principal_amortization_amount": 50.38,
          "original_principal_amortization_amount": 50.38
        }
      ],
      "issue_amount": 50.38,
      "contract_fees": [
        {
          "fee_type": "spread",
          "fee_amount": 0.19
        },
        {
          "fee_type": "spread_ted_fee",
          "fee_amount": 1.0
        }
      ],
      "additional_iof": 0.19,
      "assignment_amount": 51.57,
      "iof_charge_method": "financed",
      "contract_fee_amount": 1.19,
      "external_contract_fees": [],
      "number_of_installments": 1,
      "prefixed_interest_rate": {
        "created_at": "2026-04-12T21:37:53",
        "daily_rate": 0.009419836,
        "annual_rate": 29.6351274611,
        "monthly_rate": 0.33,
        "interest_base": "calendar_days_365"
      },
      "total_pre_fixed_amount": 26.44,
      "requester_identifier_key": "ccdbb93a-89cf-47bc-bd69-87671019d2ae",
      "external_contract_fee_amount": 0,
      "net_external_contract_fee_amount": 0
    },
    "status": "issued",
    "webhook_type": "debt",
    "event_datetime": "2026-04-12 21:37:53"
}
```

### Generated document webhook (asynchronous)

Sent asynchronously with the CCB document URL and the signed PDF. In the asynchronous flow, use this together with the Issued webhook; the Signature finished webhook is not sent. See the introduction at the top of this section.

Response Body

```json
{
    "key": "1e90d231-e569-49cb-9bf0-3409bb45a43a",
    "data": {
      "contract": {
        "urls": [
          "https://storage.googleapis.com/live-doc-api/documents/ddc85f4c-7079-44c5-b8cc-1fa630406551-signed.pdf"
        ]
      },
      "document_key": "ddc85f4c-7079-44c5-b8cc-1fa630406551",
      "signed_contract_url": "https://storage.googleapis.com/live-doc-api/documents/ddc85f4c-7079-44c5-b8cc-1fa630406551-signed.pdf"
    },
    "status": "generated_document",
    "webhook_type": "debt",
    "event_datetime": "2026-04-12 21:38:02"
}
```

### Disbursement webhook

Response Body

```json
{
    "key": "1ebd4a90-2721-4c39-a399-427fa16bca65",
    "data": {
      "installments": [
        {
          "due_date": "2025-11-27",
          "total_amount": 87.43,
          "installment_key": "e25fb146-0a61-4319-a722-d01b2213d0f9",
          "pre_fixed_amount": 29.26477451,
          "installment_number": 1,
          "principal_amortization_amount": 58.16522549
        },
        {
          "due_date": "2025-12-27",
          "total_amount": 87.43,
          "installment_key": "2557de2b-6df1-4a8a-b46a-59206ece157f",
          "pre_fixed_amount": 20.11446867,
          "installment_number": 2,
          "principal_amortization_amount": 67.31553133
        },
        {
          "due_date": "2026-01-27",
          "total_amount": 87.43,
          "installment_key": "cc503d1d-6387-4a1f-bd78-62b248d02ec8",
          "pre_fixed_amount": 11.07075682,
          "installment_number": 3,
          "principal_amortization_amount": 76.35924318
        }
      ],
      "ted_receipt_list": [],
      "requester_identifier_key": "24b5deae-304e-4773-9b25-e42dbd450241",
    },
    "status": "disbursed",
    "webhook_type": "debt",
    "event_datetime": "2025-10-27 17:10:21"
}

```

If the debt fails to disburse, or is returned, you will receive a cancellation webhook.

### Cancelation webhook

Response Body

```json
{
     "webhook_type": "debt",
     "key":"1ebd4a90-2721-4c39-a399-427fa16bca65",
     "event_datetime": "2025-10-27 16:38:59",
    "data": {
        "cancel_reason": "Operacao cancelada manualmente",
        "cancel_reason_enumerator": "manual"
    },
     "status":"canceled"
  }

```

****Cancelation reasons****

| cancel_reason_enumerator | Description |  
|---|---|  
|disbursing_error|Operation canceled due to an error during disbursement.  
|waiting_signature |Operation canceled due to missing signature. 
|pix_max_retry|Operation canceled because the receiving bank could not process the disbursement.  
|manual|Operation canceled manually.  
|agencia_conta_invalida|Invalid agency or recipient account number.  
|invalid_account|The destination account number is nonexistent or invalid.  
|invalid_document_number|The CPF/CNPJ of the destination account is incorrect.  
|unsupported_transaction|The destination account does not support this type of transaction.  
|invalid_ispb|The ISPB number is invalid or nonexistent.  
|rejected_payment|Payment order was rejected by the receiving bank.  
| refund_after_payee_request | Refund requested by the payee                                                |
| invalid_account            | The destination account number is nonexistent or invalid.                    |
| invalid_document_number    | The CPF/CNPJ of the destination account is incorrect.                        |
| rejected_payment           | Payment rejected by the receiving bank.                                      |
| blocked_account            | The destination account is blocked.                                          |
| unsupported_transaction    | The destination account does not support this type of transaction.           |
| amount_too_great           | Payment/refund amount exceeds the limit for the credited destination account. |
| invalid_ispb               | The ISPB number is invalid or nonexistent.                                   |
| receiver_error             | Transaction interrupted due to error on the receiver's PSP.                  |
| closed_account             | The destination account is closed.                                           |
| disbursing_hour_closed     | Disbursement occurred outside of the allowed time frame.                     |
| unregistered_pix_key       | The Pix key is not being used.                                               |
| manual                     | Operation manually canceled.                                                 |
| spi_timeout                | Timeout control in SPI.                                                     |

## 6. Cancellation

### Cancel debt before disbursement

### Request Body

ENDPOINT /debt/ DEBT-KEY /cancel
MÉTODO PATCH

Testar no Playground

### Path params

| Field  | Type   | Description | Max. Char. |
|---|---| ---| ---|
| `debt_key` * | string | Debt unique identifier key returned at the moment of the credit operation creation. | 32 |  

### Response Body

STATUS 200

Response Body

```json
{
  "data": [
    {
      "borrower": {
        "document_number": "68394265057",
        "name": "Xuxa Meneguel"
      },
      "contract_fee_amount": 5.56,
      "installments": [
        {
          "bank_slip_key": null,
          "calendar_days": 57,
          "due_date": "2020-09-30",
          "due_principal": -0.00217819,
          "fine_amount": null,
          "has_interest": true,
          "installment_key": "28eb5907-ed25-4a86-bb9d-b6dc944f13df",
          "installment_number": 1,
          "installment_status": "opened",
          "installment_type": "principal",
          "paid_amount": 0,
          "post_fixed_amount": 0,
          "pre_fixed_amount": 268.75782181,
          "principal_amortization_amount": 1111.9,
          "tax_amount": 0,
          "total_amount": 1380.66,
          "workdays": 40
        }
      ],
      "operation_key": "7986dcc7-4331-478f-af47-adfbdf7f4a36",
      "status": "opened"
    }
  ],
  "pagination": {
    "current_page": 1,
    "next_page": null,
    "rows_per_page": 100,
    "total_pages": 1,
    "total_rows": 55
  }
}

```

### Debt cancellation within seven days after disbursement — Via Pix refund

Used when the partner requests the borrower to return the funds via Pix. The system generates a copy-paste Pix code for the borrower to complete the refund. Once payment is confirmed, the operation is automatically canceled.

:::info When to use
Use this endpoint when the reversal must be completed by the **borrower**, who will receive a Pix refund code to pay.
:::

###  Request Body

ENDPOINT /debt/CREDIT-OPERATION-KEY/reversal
MÉTODO POST

Testar no Playground

Request Body

```json
{}

```

---

### Debt cancellation within seven days after disbursement — Via QI internal account

Used when the refund is processed directly through **QI Tech's internal account**, without requiring any action from the borrower. Suitable for the `internal` method, where the amount is debited internally without generating a Pix.

:::info When to use
Use this endpoint when the reversal is operated by the **partner via QI Tech's internal account**, without involving the borrower in the refund process.
:::

###  Request Body

ENDPOINT /credit_operation/ CREDIT-OPERATION-KEY /reversal
MÉTODO PUT

:::info Required Header
Send the `SELECTED-AGENT` header with your `requester_key` value.
:::

### Path Params

| Field | Type | Description | Max. Char. |
|---|---|---|---|
| `credit_operation_key`* | string | Credit operation key (DEBT-KEY) | UUID |

Request Body (optional)

```json
{
    "cancel_reason": "reversed_manually"
}

```

### Body Params

| Field | Type | Description | Max. Char. |
|---|---|---|---|
| `cancel_reason` | string | Reason for the reversal. If not provided, the system will use the default. | - |

###  Response Body

STATUS 200

Response Body

```json
{
  "disbursed_issue_amount": 1500,
  "issue_amount": 2000,
  "assignment_amount": 1850,
  "assigned": true,
  "assigned_at": "2023-10-01T12:00:00",
  "purchaser_document_number": "12345678000199",
  "reversal_key": "a353c543-2ac7-437c-ac6a-eb4e8d6ce250"
}

```

## 7. Debt inquiry

You can query the debt later to retrieve information or track its current status:

ENDPOINT /v2/credit_operation/ CREDIT-OPERATION-KEY
METHOD GET

Testar no Playground

### Path params

| Field  | Type   | Description | Max. Char. |
|---|---|---|---|   
| `credit_operation_key` * | string |  Key of the credit operation | UUID |

### Response

STATUS 200

Response Body

```json
{
   "credit_operation_key":"31381158-e138-4aaa-99b7-f78356e71004",
   "issue_amount":201,
   "origin_key":"31381158-e138-4aaa-99b7-f78356e71004",
   "total_iof":1,
   "assigned_at":null,
   "disbursement_start_date":"2026-02-23",
   "disbursement_end_date":"2026-02-23",
   "issue_date":"2026-02-23",
   "requester_identifier_key":"12313asdjasdx998",
   "installments":[
      {
         "business_due_date":"2026-02-24",
         "due_date":"2026-02-24",
         "calendar_days":1,
         "due_interest":0,
         "due_principal":201,
         "fine_amount":0,
         "has_interest":true,
         "post_fixed_amount":0,
         "pre_fixed_amount":0.46,
         "principal_amortization_amount":103.45,
         "tax_amount":0.01,
         "total_amount":103.91,
         "workdays":1,
         "accrual_reference_date":null,
         "advanced_paid_amount":0,
         "bank_slip_key":null,
         "digitable_line":null,
         "installment_key":"cfd67eb8-cd1e-438b-8636-44cb94176515",
         "installment_status":"created",
         "installment_type":"principal",
         "original_due_principal":201,
         "original_pre_fixed_amount":0.46,
         "original_principal_amortization_amount":103.45,
         "paid_amount":0,
         "original_total_amount":103.91,
         "qr_code_key":null,
         "qr_code_url":null,
         "renegotiation_proposal_key":null,
         "total_accrual_amount":0,
         "total_paid_amount":0,
         "installment_number":1,
         "paid_at":null,
         "updated_at":null,
         "principal_amortization_payment_amount":0,
         "prefixed_interest_payment_amount":0
      },
      {
         "business_due_date":"2026-03-24",
         "due_date":"2026-03-24",
         "calendar_days":28,
         "due_interest":0,
         "due_principal":97.54761348,
         "fine_amount":0,
         "has_interest":true,
         "post_fixed_amount":0,
         "pre_fixed_amount":6.36,
         "principal_amortization_amount":97.55,
         "tax_amount":0.23,
         "total_amount":103.91,
         "workdays":20,
         "accrual_reference_date":null,
         "advanced_paid_amount":0,
         "bank_slip_key":null,
         "digitable_line":null,
         "installment_key":"445f1c2d-3967-4b23-9290-e19a0a5fb956",
         "installment_status":"created",
         "installment_type":"principal",
         "original_due_principal":97.55,
         "original_pre_fixed_amount":6.36,
         "original_principal_amortization_amount":97.55,
         "paid_amount":0,
         "original_total_amount":103.91,
         "qr_code_key":null,
         "qr_code_url":null,
         "renegotiation_proposal_key":null,
         "total_accrual_amount":0,
         "total_paid_amount":0,
         "installment_number":2,
         "paid_at":null,
         "updated_at":null,
         "principal_amortization_payment_amount":0,
         "prefixed_interest_payment_amount":0
      }
   ],
   "first_due_date":"2026-02-24",
   "requester_key":"3e69b448-9afb-4aef-9c0d-0a3059350d80",
   "original_total_iof":null,
   "contract_number":"TIK122710117",
   "credit_operation_status_enumerator":"issued",
   "operation_type_enumerator":"structured_operation",
   "disbursement_date":"2026-02-23",
   "issuer_name":"Alan Mathison Turing",
   "issuer_document_number":"46843213049",
   "external_contract_fees":[
      
   ],
   "cet":8.23,
   "annual_cet":158.43,
   "final_disbursement_amount":200,
   "number_of_installments":2,
   "disbursement_issue_amount":200,
   "prefixed_interest_rate":{
      "annual_rate":1.252191589,
      "daily_rate":0.0022578334,
      "interest_base":{
         "enumerator":"calendar_days",
         "year_days":360
      },
      "monthly_rate":0.07
   },
   "fine_configuration":{
      "contract_fine_rate":0.02,
      "fine_delay_rate":{
         "annual_rate":4.35025011,
         "daily_rate":0.0046696,
         "interest_base":{
            "enumerator":"calendar_days",
            "year_days":360
         },
         "monthly_rate":0.15
      }
   },
   "attached_documents":[
      {
         "document_key":"494598fd-c226-4332-a500-591ae3884673",
         "document_url":"https://storage.googleapis.com/sandbox-doc-api/documents/494598fd-c226-4332-a500-591ae3884673/3d684e68e7df4e557d0480d98e2692.jpg",
         "signature_url":null,
         "document_type":"document_identification",
         "signature_required":false,
         "signed":false
      },
      {
         "document_key":"494598fd-c226-4332-a500-591ae3884673",
         "document_url":"https://storage.googleapis.com/sandbox-doc-api/documents/494598fd-c226-4332-a500-591ae3884673/3d684e68e7df4e557d0480d98e2692.jpg",
         "signature_url":null,
         "document_type":"document_identification_back",
         "signature_required":false,
         "signed":false
      },
      {
         "document_key":"73584aa0-91d4-483b-a95c-1b0263c14126",
         "document_url":"https://storage.googleapis.com/sandbox-doc-api/documents/73584aa0-91d4-483b-a95c-1b0263c14126/CASTELLOBNPL-ALAN_MATHISON_TURING-CCB-TIK122710117-202602241151.pdf",
         "signature_url":"https://storage.googleapis.com/sandbox-doc-api/documents/73584aa0-91d4-483b-a95c-1b0263c14126/CASTELLOBNPL-ALAN_MATHISON_TURING-CCB-TIK122710117-202602241151_signed.pdf",
         "document_type":"ccb_pre_price_days",
         "signature_required":true,
         "signed":true
      }
   ],
   "related_parties":[
      {
         "related_party_key":"fe133e90-9ee6-401a-a5a4-7d415ecb04fd",
         "role_type":"issuer",
         "person_type":"natural",
         "name":"Alan Mathison Turing",
         "email":"weiwenqian.wayne@bytedance.com",
         "individual_document_number":"46843213049"
      }
   ],
   "base_iof":0.24,
   "additional_iof":0.76,
   "assignment_amount":201.6,
   "total_prefixed_amount":6.82
}
```

STATUS 400

Response Body

```json
{
  "data": "{\"title\": \"Bad Request\", \"description\": \"Invalid request body.\", \"translation\": \"Corpo da requisição inválido.\", \"extra_fields\": {}, \"code\": \"LEG000069\"}"
}
```

You can also query the debt later to retrieve the log of events status:

ENDPOINT /v2/credit_operation/ CREDIT-OPERATION-KEY /events
METHOD GET

CREDIT-OPERATION-KEY /events">Testar no Playground

### Path params

| Field  | Type   | Description | Max. Char. |
|---|---|---|---|   
| `credit_operation_key` * | string | Key of the credit operation | UUID |

### Response

STATUS 200

Response Body

```json
{
  "data": [
    {
      "status": "waiting_signature",
      "reason": null,
      "cancel_reason": null,
      "event_date": "2026-03-13T17:19:59Z"
    },
    {
      "status": "issued",
      "reason": null,
      "cancel_reason": null,
      "event_date": "2026-03-13T17:19:59Z"
    },
    {
      "status": "waiting_disbursement",
      "reason": null,
      "cancel_reason": null,
      "event_date": "2026-03-13T17:19:59Z"
    },
    {
      "status": "opened",
      "reason": null,
      "cancel_reason": null,
      "event_date": "2026-03-13T17:19:59Z"
    }
  ],
  "pagination": {
    "current_page": 1,
    "next_page": null,
    "rows_per_page": 10
  }
}
```

STATUS 400

Response Body

```json
{
  "data": "{\"title\": \"Bad Request\", \"description\": \"Invalid request body.\", \"translation\": \"Corpo da requisição inválido.\", \"extra_fields\": {}, \"code\": \"LEG000069\"}"
}
```

## 8. Assignment Inquiry

###  Assignment Confirmation Webhook
This webhook is triggered to notify the client that the assignment process has been initiated. It provides the essential metadata required to track the assignment.

Response Body

```json
{
      "key":"19e34186-847b-4dd7-9fc2-d14e28bc2f10",
      "data":{
         "status":"settled",
         "total_amount":1917.04,
         "assignment_key":"19e34186-847b-4dd7-9fc2-d14e28bc2f10",
         "reference_date":"2026-04-10",
         "number_of_items":8,
         "term_of_assignment_url":null
      },
      "webhook_type":"assignment.status_change",  
      "event_datetime":"2026-04-10T22:37:52"
}

```

|Field|Type|Description|Maximum lenght|
|---|---|---|---|
|assignment_key|string|Unique identifier for the assignment operation|36|
|term_of_assignment_url|string| URL to download the Term of Assignment (PDF)|2048|
|number_of_items|integer|Total number of credit operations (items) included in this assignment|5|
|total_amount|float|The sum of the present value of all items in the assignment|15,2|
|reference_date|string|The base date used for the assignment calculations (YYYY-MM-DD)|10|

To query a specific assignment, the client can perform a GET request on the endpoint using the assignment identifier key (assignment_key).

###  Request Body

ENDPOINT /v2/assignment/[assignment_key] METHOD GET

Testar no Playground

### Params

| Field            | Descrição                      |
| ---------------- | ------------------------------ |
| `assignment_key` | Assignment unique identifier key |

### Response

STATUS 200

Response Body

```json
{
"assignment_key": "77997168-5d61-430f-b5ae-08eb3d7b8c0e",
"creation_datetime": "2023-10-01T12:00:00",
"reference_date": "2023-10-01",
"total_amount": 120000,
"number_of_items": 5,
"term_of_assignment_url": "https://example.com/assignment.pdf",
"status": "settled",
"signable_term_url": "https://example.com/signable_term.pdf"
}
```

To query the contracts within an assignment, use a GET request on the endpoint with the same **assignment_key**.

### Request Body

ENDPOINT /v2/assignment/[ASSIGNMENT_KEY]/assignment_items?page=1&page_size=100 METHOD GET

Testar no Playground

### Path Params

| Field      | Type    | Description    | 
|-----------------|---------|----------------|
| `assignment_key` | string |Assignment unique identifier key |

### Query Params

| Field      | Type    | Description    | 
|-----------------|---------|----------------|
| `page` | string |Number of the page |
| `page_size` | string | Length of the page, limited by 100 |

The response is a paginated list containing information for each contract in the assignment (status 200):

### Response Body

STATUS 200

Response Body

```json
{
		"pagination": {
			"page": 1,
			"page_size": 10
		}
		"data": [
		{
				"assignment_date": date,
        "assignment_item_key": uuid,
        "contract_number": "TIK000012312",
        "control_number": "TIK000012312",
        "requester_identifier_key": uuid,  -> including this field
        "credit_operation_key": string,
        "disbursed_amount": 80.0,
        "disbursement_date": date,
        "endorsement_url": url,
        "issue_amount": 180.00,
        "issuer_document_number": string,
        "issuer_name": string,
        "number_of_installments": 10,
        "present_amount": 180.0,
        "contract_present_amount": 180.0,
        "purchaser_document_number": string,
        "status": "settled/canceled",
        "rejected_reasons": []
        "assignment_items": [
	        {
		        "installment_key": uuid,
		        "present_amount": 100,
		        "due_date": date,
		        "your_number": "TIK000012312001"
	        },
	        {
		        "installment_key": uuid,
		        "present_amount": 80,
		        "due_date": date,
		        "your_number": "TIK000012312002"
	        }
        ]
      }
	]
}
```

Query the assigment batchs by the **assignment_date**.

### Request Body

ENDPOINT /v2/assignment/assignments?reference_date=2026-05-15 METHOD GET

Testar no Playground

### Query Params

| Field                             | Type    | Description                                                                      | 
|-----------------------------------|---------|--------------------------------------------------------------------------------|
| `reference_date` |string| Date of assignment attempt |

### Response Body

STATUS 200

Response Body

```json
{"data": [{
      "assignment_key": "439b1257-82ac-4741-a416-a4428a9a7327",
      "number_of_items": 10000,
      "reference_date": "2025-01-01",
      "signable_term_url": "https://example.com/endorsement.pdf",
      "status": "settled",
      "term_of_assignment_url": "signed_url",
      "total_amount": 100.00,
  },
  {
      "assignment_key": "439b1257-82ac-4741-a416-a4428a9a7327",
      "number_of_items": 10000,
      "reference_date": "2025-01-01",
      "signable_term_url": "https://example.com/endorsement.pdf",
      "status": "settled",
      "term_of_assignment_url": "signed_url",
      "total_amount": 100.00,
  },
  {
      "assignment_key": "439b1257-82ac-4741-a416-a4428a9a7327",
      "number_of_items": 10000,
      "reference_date": "2025-01-01",
      "signable_term_url": "https://example.com/endorsement.pdf",
      "status": "canceled",
      "term_of_assignment_url": "signed_url",
      "total_amount": 100.00,
  }
  ]}
```

## 9. Technical Specifications and Enums

### Fees Object
| Field           | Type  | Description                                                                                           |
|-----------------|-------|-----------------------------------------------------------------------------------------------------|
| **amount**      | float | Fee amount (in percentage or absolute value, depending on the value provided in the amount_type field)| -            |
| **amount_type** | enum  | Fee value unit                   |  **[Amount Type Enumerator](#amount-type-enumerator)**             |
| **fee_amount**  | float | Absolute value of the fee charged in the operation                                                           | -            |
| **fee_type**    | string  | Type of fee charged in the operation                   | **[Fee Type Enumerator](#fee-type-enumerator)**          |
| **type**        | string  |  Source of the fee charged in the operation                         | **[Origin Type Enumerator](#origin-type-enumerator)**          |

### Installments Object
| Field                             | Type    | Description                                                                      | 
|-----------------------------------|---------|--------------------------------------------------------------------------------|
| **calendar_days**                 | integer    | Number of calendar days between installments                                | -            |
| **due_date**                      | string    | Installment due date in calendar days                                   | -            |
| **due_principal**                 | float   | Remaining principal on the installment due date before its payment | -            |
| **has_interest**                  | boolean | _true_ - If true, interest applies to the installment                           | -            |
| **installment_number**            | integer    | Installment number                                                              | -            |
| **prefixed_amount**               | float   | Fixed interest amount paid on the installment                                      | -            |
| **principal_amortization_amount** | float   | Principal amount paid on the installment                                           | -            |
| **tax_amount**                    | float   | Base IOF amount of installment                                                            | -            |
| **amount**                        | float   | Installment total value                                                         | -            |
| **due_interest**                  | float     | Remaining interest after the installment due date before its payment                                   | -            |
| **period**                        | float     | Installment period | -            |
| **period_workdays**               | float     | Installment period in business days | -            |
| **period_to_disbursement**        | float     | Period until disbursement | -            |
| **period_workdays_to_disbursement**| float     | Business days until disbursement | -            |
| **calendar_days_to_disbursement** | integer    | Calendar days to disbursement | -            |
| **workdays**                      | integer    | Business days between installments | -            |
| **workdays_to_disbursement**      | integer    | Business days until disbursement | -            |

### Interest Rate Object
| Field             | Description                                                                             | 
|-------------------|---------------------------------------------------------------------------------------|
| **annual_rate**   | Annual fixed/floating interest rate expressed as a decimal                                      | -            |
| **daily_rate**    | Daily fixed/floating interest rate expressed as a decimal                                      | -            |
| **interest_base** | **[Interest Base Enumerator](#interest-base-enumerator)** - Interest calculation basis  | -            |
| **monthly_rate**  | Monthly fixed/floating interest rate expressed as a decimal                                      | -            |

### Tax Configuration Object
| Field                 | Description                                                                             | 
|-----------------------|---------------------------------------------------------------------------------------|
| **base_rate**         | Base IOF rate value                                                                | -            |
| **additional_rate**   | Additional IOF rate value                                                           | -            |

### Enumeratores

### Person Type Enumerator
| Enumerator             | Description             |
|------------------------|-----------------------|
| **legal**              | Legal person       |
| **natural**            | Natural person          |

### Account Type Enumerator
| Enumerator             | Description             |
|------------------------|-----------------------|
| **checking_account**   | Checking account        |

### Amount Type Enumerator
| Enumerator             | Description             |
|------------------------|-----------------------|
| **absolute**           | Absolute value        |
| **percentage**         | Percentage value      |

###  Interest Type Enumerator
| Enumerator           | Description                                                                                                                                                                |
|----------------------|--------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
| **pre_price_days**   | Price amortization method (equal installments) with daily fixed-rate interest calculation                                                                                     |
| **pre_price**        | Price amortization method (equal installments) with fixed-rate interest calculation over 30-day periods                                                                |

### Credit Operation Type Enumerator 
| Enumerator    | Description                      |
|---------------|--------------------------------|
| **ccb**       | Bank Credit Note    |

### Interest Base Enumerator 
| Enumerator            | Description                                                                 |
|-----------------------|---------------------------------------------------------------------------|
| **workdays**          | Interest calculation basis in business days, assuming a 252-day year    |
| **calendar_days**     | Interest calculation basis in calendar days, assuming a 360-day year |
| **calendar_days_365** | Interest calculation basis in calendar days, assuming a 365-day year |

###  Fee Type Enumerator
Each fee type must be previously enabled and configured by QI Tech

| Enumerator            | Description                                                                  |
|-----------------------|----------------------------------------------------------------------------|
| **spread**            | Premium included in the credit operation's acquisition value                  |
| **spread_ted_fee**    | Premium on the TED transfer fee |

### Origin Type Enumerator
Each fee type must be previously enabled and configured by QI Tech

| Enumerator            | Description                                                                  |
|-----------------------|----------------------------------------------------------------------------|
| **internal**          | Internal fee                                                   |
| **external**          | External fee                                                   |

---

# Manual QI Sign

URL: /documentation/manual_qi_sign/

:::danger Atenção!
Os webhooks da QI Tech não devem ser mapeadas de forma restrita.
Campos adicionais podem ser incluídos aos payloads dos webhooks retornados em nossas APIs.
:::

## Introdução

Bem vindo à API de Assinaturas da QiTech! Esta API dá acesso ao serviço de assinatura eletrônica de documentos!

### Problemas?

Caso tenha algum problema entre em contato com o nosso suporte (suporte@qitech.com.br) e nós responderemos o mais rápido possível.

### Ambientes

Possuímos dois ambientes para os nossos clientes. As URLs base das APIs são:

- Produção - `https://api.sign.qitech.com.br/`
- Sandbox - `https://api.sandbox.sign.qitech.com.br/`

:::danger Aviso Importante!
Não devem ser usados dados reais de pessoas físicas e/ou jurídicas nos ambientes de Sandbox da QI Tech.  
:::

## Somente HTTPS

Por questão de segurança, toda a comunicação com as APIs da QI Tech deve ser realizada utilizando a comunicação HTTPS. Para evitar que, por desatenção ou outro motivo, sejam feitas chamadas HTTP, este servidor somente disponibiliza a porta 443 com comunicação TLS 1.2. Chamadas realizadas utilizando outros protocolos serão automaticamente negadas.

## Autenticação

> Para autenticar uma chamada, utilize o código seguinte:

```shell
# No shell, você somente precisa adicionar o header adequado em cada requisição
curl "api_endpoint_here"
  -H "Authorization: EXAMPLE_API_KEY"
```

> Substitua a API key 'EXAMPLE_API_KEY' com a sua chave adquirida com o nosso suporte.

Utilizamos uma API Key para permitir acesso a nossa API. Ela provavelmente já foi enviada por e-mail para você. Caso você ainda não tenha recebido a sua chave, envie um e-mail para suporte@qitech.com.br .

Nossa API espera receber a API Key em todas as requisições ao nosso servidor em um header como o abaixo:

`Authorization: EXAMPLE_API_KEY`

Você deve substituir EXAMPLE_API_KEY com a API Key recebida do suporte.

Envelopes são os objetos que contêm os documentos a serem assinados eletronicamente. Eles são criados a partir de um ou mais arquivos e podem ser enviados para assinatura por e-mail, SMS ou WhatsApp. Para criar um envelope, você deve enviar um arquivo ou um conjunto de arquivos para a API. O envelope será criado e você receberá um identificador único para ele.

## Criando um Envelope

Para criar um Envelope, realize uma chamada `POST` para o endpoint `/sign/envelope` com os dados do(s) assinante(s).

```bash
curl -X POST \
  https://api.sign.qitech.com.br/sign/envelope \
  -H 'Content-Type: application/json' \
  -H "Authorization: EXAMPLE_API_KEY" \
  -d '{
    "id": "814e7ed3-4080-4cae-a853-8e12812817ea",
    "subject": "CCB QiTech",
    "expiration_date": "2023-09-20",
    "signers": [
      {
        "id": "1",
        "name": "John Sample",
        "email": "johnsample@test.com",
        "birthdate": "1992-09-15",
        "document_number": "111.111.111-11",
        "phone": {
              "international_dial_code": "55",
              "area_code": "11",
              "number": "988878722"
          },
        "document_submission_method": "email",
        "authentication_submission_method": "sms"
      }
    ]
  }'

```

## Definição do Objeto Envelope

Todas as trocas de informação de um envelope utilizam a seguinte definição para este objeto. Em alguns casos, para facilitar a implementação e diminuir o fluxo de dados entre as partes, algumas informações poderão ser omitidas.

| Nome            | Tipo   | Descrição                                                                          |
| --------------- | ------ | ---------------------------------------------------------------------------------- |
| id              | string | Identificador único do envelope. <br /> **É essencial que este número seja único** |
| subject         | string | Título do envelope. Aparece no assunto do email.                                   |
| expiration_date | string | Data de expiração do envelope no formato `YYYY-MM-DD`.                             |
| signers         | list   | Lista de objetos do tipo Signer que descreve os assinantes do envelope.            |

### Definição do Objeto Signer

|               Nome               |  tipo  | descrição                                                                                                          |
| :------------------------------: | :----: | ------------------------------------------------------------------------------------------------------------------ |
|                id                | string | Identificador da transação do assinante. <br /> **É essencial que este número seja único por envelope**            |
|              email               | string | Endereço de e-mail do assinante.                                                                                   |
|               name               | string | Nome completo do assinante.                                                                                        |
|            birthdate             | string | Data de nascimento do assinante no formato `YYYY-MM-DD`.                                                           |
|         document_number          | string | Número do documento do assinante.                                                                                  |
|              phone               | object | Objeto que descreve o telefone do assinante.                                                                       |
|  phone.international_dial_code   | string | Código do país do telefone do assinante.                                                                           |
|         phone.area_code          | string | Código de área do telefone do assinante.                                                                           |
|           phone.number           | string | Número do telefone do assinante.                                                                                   |
|    document_submission_method    |  enum  | Método de envio dos documentos para assinatura. <br /> Métodos disponíveis: **_email, sms e whatsapp _**           |
| authentication_submission_method |  enum  | Método de envio do token de autenticação para assinatura. <br /> Métodos disponíveis: **_email, sms e whatsapp _** |

- Campo email e phone podem ser enviados juntos ou separados, mas ao menos um deles deve ser enviado.
- Todos os campos são obrigatórios.

### Resposta da criação do envelope

Após o sucesso na criação do envelope, a resposta será um JSON contendo o id e status do envelope, conforme o exemplo ao lado:

> Resposta exemplo

```json
{
  "id": "814e7ed3-4080-4cae-a853-8e12812817ea",
  "status": "created"
}
```

## Adicionando documentos de identificação ao assinante

Para adicionar documentos de identificação ao assinante, realize uma chamada `POST` para o endpoint `/sign/envelope/\{envelope_id\}/signer/\{signer_id\}/personal_document` para cada documento a ser adicionado. O arquivo deve ser enviado no corpo da requisição seguindo o seguinte formato:

```json
{
  "document_b64": "Q5YACgAAAABDlgAbAAAAAEOWAC0AAAAAQ5YAPwAAAABDlgdN...",
  "template": "cnh_front",
  "file_type": "jpeg"
}
```

### Templates disponíveis

Para cada tipo de documento de identificação, é necessário informar o template correspondente. Os templates disponíveis são:

| Template  | Descrição                                                                |
| --------- | ------------------------------------------------------------------------ |
| cnh_front | Carteira Nacional de Habilitação brasileira frente (Lado da foto).       |
| cnh_back  | Carteira Nacional de Habilitação brasileira frente (Lado da assinatura). |
| rg_front  | Carteira de Identidade brasileira frente (Lado da foto).                 |
| rg_back   | Carteira de Identidade brasileira verso (Lado dos dados).                |

### Descrição dos Atributos de Envio

| Atributo     | Descrição                                                                                          |
| ------------ | -------------------------------------------------------------------------------------------------- |
| document_b64 | Documento de identificação codificado em base64.                                                   |
| template     | Declara o template que deve ser aplicado para análise da imagem.                                   |
| file_type    | Identifica o formato do arquivo enviado, `jpeg`. Caso não seja enviado, o valor `jpeg` é assumido. |

- O tamanho máximo do documento de identificação deve ser de 10 MB
- Todos os campos são obrigatórios exceto o `file_type`.

### Resposta da adição de documentos de identificação

Após o sucesso na adição de documentos de identificação, a resposta será um JSON contendo o `created_at` conforme o exemplo ao lado:

> Resposta exemplo

```json
{
  "created_at": "2023-01-01T00:00:00.000Z"
}
```

### Coleta do documento de identificação

Caso não seja enviado um documento de identificação do assinante, o mesmo será solicitado para realizar a coleta no momento da assinatura.

## Adicionando documentos ao envelope

Para adicionar documentos para assinatura a um envelope, realize uma chamada `POST` para o endpoint `/sign/envelope/\{envelope_id\}/document` para cada documento a ser adicionado. O arquivo deve ser enviado no corpo da requisição seguindo o seguinte formato:

```json
{
  "id": "3dfc5526-ee47-4b63-ad97-ddaf5b1c9110",
  "document_b64": "Q5YACgAAAABDlgAbAAAAAEOWAC0AAAAAQ5YAPwAAAABDlgdN...",
  "name": "Laudo de vistoria de entrada",
  "document_type": "pdf"
}
```

- O tamanho máximo do documento deve ser de 10 MB

### Definição do Objeto Document

|     nome      |  tipo  | descrição                                                                                                                                                                                          |
| :-----------: | :----: | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
|      id       | string | Identificador do documento. <br /> **É essencial que este número seja único dentro do envelope** <br /> **Opcional** Caso não seja informado, geraremos uma GUID no padrão UUID4 de 36 caracteres. |
| document_b64  | string | Documento codificado em base64.                                                                                                                                                                    |
|     name      | string | Nome do documento.                                                                                                                                                                                 |
| document_type |  enum  | Tipo do documento. <br /> Tipo disponível: **_pdf_**                                                                                                                                               |

### Resposta da adição de documentos ao envelope

Após o sucesso na adição de documentos ao envelope, a resposta será um JSON contendo o identificador do documento e a data de criação, conforme o exemplo abaixo:

> Resposta exemplo

```json
{
  "id": "3dfc5526-ee47-4b63-ad97-ddaf5b1c9110",
  "created_at": "2023-01-01T00:00:00.000Z"
}
```

## Enviando o envelope para assinatura

Para enviar o envelope para assinatura, realize uma chamada `PATCH` para o endpoint `/sign/envelope/\{envelope_id\}`

```bash

  curl -X PATCH \
    https://api.sign.qitech.com.br/sign/envelope/\{envelope_id\} \
    -H "Authorization: EXAMPLE_API_KEY" \
    -d '{
      "status": "submitted"
    }'

```

### Resposta do envio do envelope para assinatura

Após o sucesso no envio do envelope para assinatura, a resposta será um JSON contendo o status do envelope, conforme o exemplo abaixo:

> Resposta exemplo

```json
{
  "status": "submitted"
}
```

Após o envio do envelope para assinatura, os assinantes receberão um e-mail ou uma mensagem com o link para assinar os documentos.

Ao acessar o link o assinante deverá preencher o CPF, assinar o documento e realizar o fluxo de validação facial e/ou documental a depender do fluxo do parceiro. Após a assinatura, o assinante será redirecionado para a página de sucesso.

## Consultando os dados do envelope

Para verificar os dados do envelope, como status e assinantes, realize uma chamada GET para o endpoint `/sign/envelope/\{envelope_id\}`

```bash

  curl -X GET \
    https://api.sign.qitech.com.br/sign/envelope/\{envelope_id\} \
    -H "Authorization: EXAMPLE_API_KEY"

```

Caso a requisição seja bem sucedida, a resposta será um JSON contendo o status do envelope e informações sobre os assinantes, conforme a exemplo abaixo:

> Resposta exemplo

```json
{
  "id": "814e7ed3-4080-4cae-a853-8e12812817ea",
  "subject": "Laudo de vistoria de entrada",
  "expiration_date": "2023-09-20T02:59:59Z",
  "status": "completed",
  "signers": [
    {
      "id": "1",
      "name": "John Sample",
      "email": "johnsample@test.com",
      "birthdate": "1992-09-15",
      "document_number": "111.111.111-11",
      "phone": {
        "international_dial_code": "55",
        "area_code": "11",
        "number": "988878722"
      },
      "document_submission_method": "email",
      "authentication_submission_method": "email",
      "status": "signed",
      "signed_at": "2023-03-21T15:30:00.000Z",
      "signature_url": "https://sign.qitech.com.br/s/s2S33dD",
      "documents": [
        {
          "id": "8d3c3f1a-1a1a-1a1a-1a1a-1a1a1a1a1a1a",
          "name": "Laudo de vistoria de entrada",
          "document_type": "pdf"
        }
      ]
    }
  ]
}
```

- O status do envelope pode ser `created`, `submitted`, `completed`, `canceled` ou `expired`.

| enumeradores | descrição                                                            |
| :----------: | -------------------------------------------------------------------- |
|   created    | Envelope criado                                                      |
|  submitted   | Envelope enviado para assinatura                                     |
|  completed   | Quando todas as assinaturas do envelope foram concluídas com sucesso |
|   canceled   | Envelope cancelado por solicitação do parceiro                       |
|   expired    | Envelope expirado por tempo de assinatura                            |

|      nome       |   tipo   | descrição                                                                 |
| :-------------: | :------: | ------------------------------------------------------------------------- |
|       id        |  string  | Identificador único do envelope.                                          |
|     status      |  string  | Status do envelope.                                                       |
| expiration_date |  string  | Data de expiração do envelope.                                            |
|     signers     |  Signer  | Lista de objetos do tipo Signer que descreve os assinantes do envelope.   |
|    documents    | Document | Lista de objetos do tipo Document que descreve os documentos do envelope. |

## Webhook

Ao final da assinatura por todos os assinantes e geração do dossiê, será disparada uma chamada por meio de Webhook.
Para tanto, é necessário, por meio da equipe do suporte (suporte@qitech.com.br), configurar um endereço do endpoint por onde vamos notificar as atualizações e também uma _signature_key_ que será utilizada para assinar a requisição.

O cliente pode, apesar de não recomendável, também utilizar a técnica de [polling]( ). Neste caso, basta não configurar o endpoint de webhook e utilizar os endpoints de recuperação de cadastro para proceder com o polling.

## Assinatura

> Exemplo de cálculo de assinatura em Python

```python
    hmac_obj = hmac.new(signature_key.encode('utf-8'), (endpoint + method + payload).encode('utf-8'), hashlib.sha1)
    return hmac_obj.hexdigest()
```

Para garantir que a requisição recebida no endpoint do webhook parte dos nossos servidores, uma assinatura HMAC é enviada no Header Signature, semelhante ao processo de autenticação.

Após realizar o cálculo do valor esperado da assinatura do lado do servidor, é necessário comparar a assinatura calculada com a enviada. Caso as assinaturas sejam compatíveis, isso significa que a requisição partiu dos nossos servidores e que é confiável.

Exemplo de chamada webhook:

```json
{
  "id": "479f8e5a-75e1-4a33-9d75-e0083e3c8e9c",
  "status": "completed",
  "webhook_type": "envelope_completed",
  "signers": [
    {
      "id": "c15392dd-7859-4eae-a2b6-bf0f760a6d9b",
      "biometry": {
        "face_validation_available": true,
        "fraud_base_flag": false,
        "face_validation_score": 90
      },
      "liveness": {
        "result": "live"
      },
      "document": {
        "face_match_score": 85
      }
    }
  ]
}
```

|                   nome                    |  tipo   | descrição                                                                        |
| :---------------------------------------: | :-----: | -------------------------------------------------------------------------------- |
|                    id                     | string  | Identificador único do envelope.                                                 |
|                  status                   | string  | Status do envelope.                                                              |
|                 signer.id                 | string  | Identificador único do assinante.                                                |
| signer.biometry.face_validation_available | boolean | Indica se o rosto foi encontrado e validado.                                     |
|      signer.biometry.fraud_base_flag      | boolean | Indica se o rosto do assinante foi encontrado na base de fraude.                 |
|   signer.biometry.face_validation_score   | integer | Indica o score da validação facial.                                              |
|          signer.liveness.result           | string  | Indica o resultado da validação de liveness. Valores possíveis `live` ou `spoof` |
|     signer.document.face_match_score      | integer | Indica o score da validação de face match.                                       |

## Baixando os dossiês assinados

Caso todos os assinantes tenham assinado todos os documentos do envelope, o status do envelope será `completed` e um dossiê para cada documento, com as assinaturas e dados dos assinantes estará disponível para download. Para isso, realize uma chamada `GET` para o endpoint `/sign/envelope/\{envelope_id\}/report`

```bash
  curl -X GET \
    https://api.sign.qitech.com.br/sign/envelope/\{envelope_id\}/report \
    -H "Authorization: EXAMPLE_API_KEY"

```

Caso a requisição seja bem sucedida, a resposta será um JSON contendo o id e status do envelope, além de uma lista com id do documento e a url do dossiê gerado, conforme o exemplo abaixo:

> Resposta exemplo

```json
{
  "id": "479f8e5a-75e1-4a33-9d75-e0083e3c8e9c",
  "status": "available",
  "documents_reports": [
    {
      "id": "a50ef632-842e-4622-8075-684b8c83a99e",
      "url": "https://qisign-dossiers.com/06abda52-5bd1-46a1-8fa2-f616ba44b395.pdf"
    }
  ]
}
```

- O link do relatório para cada documento terá validade de 24 horas.
- O status dos relatórios para o envelope pode ser `available` ou `unavailable`.
- A propriedade `documents_reports` contem a lista dos documentos do envelope, identificados pelo id do documento e o link do seu relatório.

## Baixando o dossiê por documento assinado

Caso todos os assinantes tenham assinado todos os documentos do envelope, o status do envelope será `completed` e um dossiê para cada documento assinado, com as assinaturas e dados dos assinantes estará disponível para download. Para isso, realize uma chamada `GET` para o endpoint `/sign/envelope/\{envelope_id\}/document/{document_id}/report`

```bash
  curl -X GET \
    https://api.sign.qitech.com.br/sign/envelope/\{envelope_id\}/document/{document_id}/report \
    -H "Authorization: EXAMPLE_API_KEY"

```

Caso a requisição seja bem sucedida, a resposta será um JSON contendo id, status, url e o base64 do dossiê do documento, conforme o exemplo abaixo:

> Resposta exemplo

```json
{
  "id": "5b930d3d-3713-4c42-85d5-f8e9e44e30ce",
  "status": "available",
  "document_report_url": "https://qisign-dossiers.com/7bcf5868-784a-4356-85fb-dd72fd53cd4a.pdf",
  "document_report": "vAsXDdsaGUsdIMIGxhIG1GU=..."
}
```

- O link para o relatório do documento terá validade de 24 horas.
- O status para o relatório do documento pode ser `available` ou `unavailable`.
- A propriedade `document_report` é o relatório do documento em PDF codificado em base64.

## Baixando as fotos do rosto dos assinantes

É possível recuperar as imagens do rosto dos assinantes. Para isso basta realizar um chamada `GET` para o endpoint `/sign/envelope/\{envelope_id\}/signer/\{signer_id\}/face`

```bash
  curl -X GET \
    https://api.sign.qitech.com.br/sign/envelope/\{envelope_id\}/signer/\{signer_id\}/face \
    -H "Authorization: EXAMPLE_API_KEY"

```

Caso a requisição seja bem sucedida, a resposta será um JSON contendo a imagem codificada em base64, conforme o exemplo abaixo:

> Resposta exemplo

```json
{
  "face_image_url": "https://qisign-face-image.com/4fd09dab-6f3e-4ff5-bfed-6f7debfcde71.jpeg"
}
```

## Cancelando um envelope

Para cancelar um envelope, realize uma chamada `PATCH` para o endpoint `/sign/envelope/\{envelope_id\}`

```bash

  curl -X PATCH \
    https://api.sign.qitech.com.br/sign/envelope/\{envelope_id\} \
    -H "Authorization: EXAMPLE_API_KEY" \
    -d '{
      "status": "canceled"
    }'

```

Caso a requisição seja bem sucedida, a resposta será um JSON contendo o status do envelope, conforme o exemplo abaixo:

> Resposta exemplo

```json
{
  "status": "canceled"
}
```

## Baixando as fotos do documento dos assinantes

É possível recuperar as imagens do documento dos assinantes. Para isso basta realizar um chamada `GET` para o endpoint `/sign/envelope/\{envelope_id\}/signer/\{signer_id\}/personal_document`

```bash
  curl -X GET \
    https://api.sign.qitech.com.br/sign/envelope/\{envelope_id\}/signer/\{signer_id\}/personal_document \
    -H "Authorization: EXAMPLE_API_KEY"

```

Caso a requisição seja bem sucedida, a resposta será um JSON contendo a imagem codificada em base64, conforme o exemplo abaixo:

> Resposta exemplo

```json
{
  "document_front_url": "https://qisign-personal-documents.com/bee17d70-b029-41e2-b76b-86f64a8f9213.jpeg",
  "document_back_url": "https://qisign-personal-documents.com/faf38378-daa2-47b2-9d87-0bbc1f7c744c.jpeg"
}
```

## Consultando o status de um assinante

Para verificar o status de um assinante, realize uma chamada GET para o endpoint /sign/envelope/\{envelope_id\}/signer/\{signer_id\}

```bash

  curl -X GET \
    https://api.sign.qitech.com.br/sign/envelope/\{envelope_id\}/signer/\{signer_id\} \
    -H "Authorization: EXAMPLE_API_KEY"

```

Caso a requisição seja bem sucedida, a resposta será um JSON contendo o status do assinante, conforme a exemplo abaixo:

> Resposta exemplo

```json
{
  "name": "John Sample",
  "email": "johnsample@test.com",
  "status": "signed",
  "signed_at": "2023-03-21T15:30:00.000Z"
}
```

|   nome    |  tipo  | descrição                                                               |
| :-------: | :----: | ----------------------------------------------------------------------- |
|   name    | string | Nome do assinante.                                                      |
|   email   | string | E-mail do assinante.                                                    |
|  status   | string | Status da assinatura assinante.                                         |
| signed_at | string | Data e hora da última assinatura no formato `YYYY-MM-DDTHH:MM:SS.000Z`. |

## Status HTTP

A API de assinatura utilizam a seguinte padronização nos status HTTP de retorno, de acordo com o RFC 7231 :

| Status HTTP | Significado           | Descrição                                                                                                                                                                       |
| ----------- | --------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| 400         | Bad Request           | A requisição enviada possui algum erro de formatação. Na maioria dos casos, retornamos no corpo da mensagem uma explicação de onde está o erro.                                 |
| 401         | Unauthorized          | Houve algum problema na autenticação, verifique se a API Key está correta e no header correto, de acordo com a seção <a href='#autenticacao'>Autenticação</a>.                  |
| 403         | Forbidden             | O endpoint acessado é de uso interno e não está disponível para esta API Key.                                                                                                   |
| 404         | Not Found             | O dado requisitado não foi encontrado usando a chave utilizada. Este status também é retornado quando um endpoint inválido é requisitado.                                       |
| 405         | Method Not Allowed    | O método HTTP utilizado não se aplica ao endpoint utilizado.                                                                                                                    |
| 406         | Not Acceptable        | Os dados enviados no corpo da requisição são inválidos. Em geral, isso significa que os dados enviados não são um JSON válido.                                                  |
| 409         | Conflict              | O id da requisição corresponde a um id já processado anteriormente. Este status é retornado no caso de requisições duplicadas enviadas ao servidor.                             |
| 500         | Internal Server Error | Tivemos um problema para processar esta requisição, ao encontrarmos esse erro nossos especialistas são automaticamente notificados e iniciam a análise e solução imediatamente. |
| 503         | Service Unavailable   | Você se deparou com uma indisponibilidade, planejada ou não, de infraestrutura dos nossos servidores.                                                                           |