### Implement Basic Authentication for Banco Babylon API Source: https://bancobabylon.readme.io/reference/index Demonstrates how to create the Base64‑encoded Authorization header and make a POST request to the transactions endpoint. Includes examples for Node.js (TypeScript), PHP, and cURL. These snippets require the secret key as username and the company ID as password. ```Node.js (TypeScript) const secretKey = "sua_secret_key_aqui"; const companyId = "seu_company_id_aqui"; const credentials = Buffer.from(`${secretKey}:${companyId}`).toString("base64"); const options = { method: "POST", url: "https://api.bancobabylon.com/functions/v1/transactions", headers: { "Authorization": `Basic ${credentials}`, "Content-Type": "application/json" }, }; ``` ```PHP "example" ]); $curl = curl_init(); curl_setopt_array($curl, [ CURLOPT_URL => "https://api.bancobabylon.com/functions/v1/transactions", CURLOPT_RETURNTRANSFER => true, CURLOPT_POST => true, CURLOPT_POSTFIELDS => $data, CURLOPT_HTTPHEADER => $headers ]); $response = curl_exec($curl); $httpCode = curl_getinfo($curl, CURLINFO_HTTP_CODE); curl_close($curl); if ($httpCode === 200) { $result = json_decode($response, true); // Processar resposta } else { // Tratar erro echo "Erro na requisição: " . $httpCode; } ?> ``` ```cURL (Bash) curl -X POST \ https://api.bancobabylon.com/functions/v1/transactions \ -H "Authorization: Basic $(echo -n 'SECRET_KEY:COMPANY_ID' | base64)" \ -H "Content-Type: application/json" \ -d '{"data": "example"}' ``` -------------------------------- ### GET /websites/bancobabylon_readme_io_reference/withdraw/{id} Source: https://bancobabylon.readme.io/reference/createwithdrawal Obtém o status de uma solicitação de saque específica pelo seu ID. Utiliza o header `Idempotency-Key` para garantir a integridade da requisição. ```APIDOC ## GET /withdraw/{id} ### Description Recupera o status de uma solicitação de saque existente. O header `Idempotency-Key` é necessário para a requisição. ### Method GET ### Endpoint /withdraw/{id} ### Parameters #### Path Parameters - **id** (string) - Obrigatório - O ID único da solicitação de saque. #### Header Parameters - **Idempotency-Key** (string) - Obrigatório - Chave para garantir a idempotência da requisição. ### Response #### Success Response (200 OK) - **id** (string) - ID único da solicitação de saque. - **status** (string) - Status atual do saque (`pending`, `approved`, `failed`, `cancelled`). - **amount** (number) - Valor total do saque. #### Response Example ```json { "id": "sac-12345abc", "status": "approved", "amount": 100.50 } ``` #### Error Response (404 Not Found) - **error** (string) - Mensagem de erro indicando que o saque não foi encontrado. #### Error Response Example ```json { "error": "Solicitação de saque não encontrada." } ``` ``` -------------------------------- ### Create Payment using Python Source: https://bancobabylon.readme.io/reference/payments Demonstrates creating a payment with Python using the 'requests' library. This example shows how to construct the POST request with the appropriate URL, headers, and JSON payload. ```python import requests import json url = "https://api.bancobabylon.com/functions/v1/transactions" payload = { "paymentMethod": "PIX" } headers = { 'accept': 'application/json', 'content-type': 'application/json' } response = requests.post(url, data=json.dumps(payload), headers=headers) if response.status_code == 200: print(response.json()) else: print(f"Error: {response.status_code} - {response.text}") ``` -------------------------------- ### Include Tokenization Library via HTML Script Source: https://bancobabylon.readme.io/reference/tokeniza%C3%A7%C3%A3o-de-cart%C3%A3o-de-cr%C3%A9dito Adds the Banco Babylon tokenization library to the web page by inserting a script tag in the HTML head. This enables front‑end token generation. No additional dependencies are required. ```HTML ``` -------------------------------- ### Handle Webhook Responses in JavaScript to Prevent Retries Source: https://bancobabylon.readme.io/reference/webhooks-3 This example shows the correct way to always respond with 200 OK to webhook requests, even on errors, to avoid triggering retries, contrasted with an incorrect approach that returns 500 and causes retries. It uses a Node.js/Express-like setup to process the request body asynchronously. Dependencies include a web framework like Express; inputs are POST request bodies; outputs are HTTP status responses; limitations include no actual webhook processing logic, focusing only on response handling for idempotency. ```javascript // ✅ CORRETO - Sempre responder 200 app.post('/webhook', (req, res) => { try { processWebhook(req.body); res.status(200).send('OK'); } catch (error) { console.error('Erro:', error); res.status(200).send('OK'); // Ainda assim responder 200 } }); // ❌ INCORRETO - Causará retry app.post('/webhook', (req, res) => { try { processWebhook(req.body); res.status(200).send('OK'); } catch (error) { res.status(500).send('Erro interno'); // Causará retry! } }); ``` -------------------------------- ### Create Payment using Ruby Source: https://bancobabylon.readme.io/reference/payments Provides a Ruby example for creating a payment. This snippet utilizes the 'httparty' gem to make the POST request to the Banco Babylon API, including necessary headers and data payload. ```ruby require 'httparty' url = 'https://api.bancobabylon.com/functions/v1/transactions' options = { body: { paymentMethod: 'PIX' }.to_json, headers: { 'accept' => 'application/json', 'content-type' => 'application/json' } } response = HTTParty.post(url, options) if response.success? puts response.parsed_response else puts "Error: #{response.code} - #{response.message}" end ``` -------------------------------- ### Create Payment using cURL Source: https://bancobabylon.readme.io/reference/payments Example of creating a payment using cURL, demonstrating the POST request to the transactions endpoint with JSON payload. This covers basic authentication and request body construction. ```shell curl --request POST \ --url https://api.bancobabylon.com/functions/v1/transactions \ --header 'accept: application/json' \ --header 'content-type: application/json' \ --data '{ "paymentMethod": "PIX" }' ``` -------------------------------- ### Generate Credit Card Token using JavaScript/TypeScript Source: https://bancobabylon.readme.io/reference/tokeniza%C3%A7%C3%A3o-de-cart%C3%A3o-de-cr%C3%A9dito Initializes the public key and encrypts card details to produce a token_id. The token can then be sent to the API for processing. Requires the previously loaded Banco Babylon library and async support. ```TypeScript BancoBabylon.setPublicKey(\"publicKey\"); var token_id = await BancoBabylon.encrypt({ number: \"4111111111111111\", holderName: \"João Silva\", expMonth: 1, expYear: 2026, cvv: \"456\" }); ``` -------------------------------- ### Error Response Schema Source: https://bancobabylon.readme.io/reference/post_transactions Schema and example for error responses returned by the API. ```APIDOC ## Error Response ### Description Schema and example for error responses returned by the API. ### Response Example { "error": { "code": "INTERNAL_ERROR", "message": "Ocorreu um erro interno. Tente novamente em alguns instantes." } } ``` -------------------------------- ### Error Response - Bad Request Source: https://bancobabylon.readme.io/reference/get_transactions Details the structure and example of a 400 Bad Request error response from the API. ```APIDOC ## Error Response - Bad Request (400) ### Description Returned when the request contains invalid parameters. ### Response Body - **code** (string) - Error code identifier - **message** (string) - Human-readable error message - **details** (array) - Additional details about the error ### Response Example ```json { "error": { "code": "BAD_REQUEST", "message": "A requisição contém parâmetros inválidos", "details": [ "O campo 'amount' deve ser um número inteiro" ] } } ``` ``` -------------------------------- ### POST /functions/v1/transactions Source: https://bancobabylon.readme.io/reference/index Creates a new transaction in the Banco BABYLON Payments system. Requires Basic Authentication in the header. The request body should contain transaction details. ```APIDOC ## POST /functions/v1/transactions ### Description Endpoint for initiating a new payment transaction. All requests must include Basic Authentication and Content-Type: application/json. ### Method POST ### Endpoint https://api.bancobabylon.com/functions/v1/transactions ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **data** (string) - Required - Transaction data or payload. ### Request Example { "data": "example" } ### Response #### Success Response (200) - **result** (object) - Processed transaction details. #### Response Example { "result": "success" } ### Authentication Use Authorization: Basic {base64(Secret Key:Company ID)} ``` -------------------------------- ### Error Response - Unauthorized Source: https://bancobabylon.readme.io/reference/get_transactions Details the structure and example of a 401 Unauthorized error response from the API. ```APIDOC ## Error Response - Unauthorized (401) ### Description Returned when authentication credentials are invalid. ### Response Body - **code** (string) - Error code identifier - **message** (string) - Human-readable error message ### Response Example ```json { "error": { "code": "UNAUTHORIZED", "message": "Credenciais de autenticação inválidas" } } ``` ``` -------------------------------- ### OpenAPI Definition for Withdrawals API in JSON Source: https://bancobabylon.readme.io/reference/createwithdrawal This JSON snippet defines the OpenAPI 3.1.0 specification for the Banco BABYLON Withdrawals API, detailing the /withdrawals/cashout endpoint for creating PIX and card withdrawals. It includes security schemes, request/response schemas, and examples. No runtime dependencies; it's a static API specification file used for generating documentation and client SDKs. ```json { "openapi": "3.1.0", "info": { "title": "Banco BABYLON Withdrawals API", "description": "API para processamento de saques PIX e cartão da plataforma BABYLON.\n\n## Funcionalidades\n\n- ✅ Criação de saques via API com autenticação por API Key\n- ✅ Suporte a chaves PIX (CPF, CNPJ, Email, Telefone, EVP)\n- ✅ Processamento automático ou manual de saques\n- ✅ Webhooks para notificação de eventos\n- ✅ Idempotência para evitar transações duplicadas\n- ✅ Validação de saldo e limites\n- ✅ Auditoria completa de operações\n\n## Autenticação\n\nA API utiliza autenticação Basic Auth com formato `apikey:company_id` codificado em Base64.\n\nConsulte a [documentação de autenticação](./authentication.md) para mais detalhes.\n\n## Rate Limits\n\n- 100 requisições/minuto por API Key\n- 500 requisições/minuto por Company\n- 1000 requisições/minuto por IP\n\n## Suporte\n\n- Email: dev@bancobabylon.com\n- Slack: #api-support\n- Documentação: https://docs.bancobabylon.com", "version": "1.0.0", "contact": { "name": "BABYLON API Support", "email": "dev@bancobabylon.com", "url": "https://docs.bancobabylon.com" }, "license": { "name": "Proprietary", "url": "https://bancobabylon.com/terms" } }, "servers": [ { "url": "https://api.bancobabylon.com/functions/v1", "description": "Produção" } ], "tags": [ { "name": "Withdrawals", "description": "Operações de saque (PIX e cartão)" } ], "paths": { "/withdrawals/cashout": { "post": { "tags": [ "Withdrawals" ], "summary": "Criar um novo saque", "description": "Cria uma nova solicitação de saque PIX ou cartão.\n \n## Idempotência\n\nUse o header `Idempotency-Key` para evitar duplicatas (obrigatório).\n\n## Status do Saque\n\n- `pending`: Aguardando aprovação manual\n- `approved`: Aprovado e processado\n- `failed`: Falhou durante processamento \n- `cancelled`: Cancelado manualmente\n", "operationId": "createWithdrawal", "security": [ { "ApiKeyAuth": [] } ], "parameters": [ { "name": "Idempotency-Key", "in": "header", "description": "Chave única para garantir idempotência da requisição", "required": true, "schema": { "type": "string", "format": "string", "examples": [ "f47ac10b-58cc-4372-a567-0e02b2c3d479" ] } } ], "requestBody": { "required": true, "content": { "application/json": { "schema": { "$ref": "#/components/schemas/WithdrawalRequest" }, "examples": { "pix_cpf": { "summary": "Saque PIX com CPF", "value": { "pixkeytype": "cpf", "pixkey": "12345678901", "requestedamount": 5000, "description": "Saque via API - Cliente ABC", "isPix": true, "postbackUrl": "https://minha-api.com/webhook/withdrawals" } }, "pix_email": { "summary": "Saque PIX com Email", "value": { "pixkeytype": "email", "pixkey": "usuario@example.com", "requestedamount": 10000, "description": "Pagamento de comissão", "isPix": true, "postbackUrl": "https://minha-api.com/webhook/withdrawals" } }, "card_withdrawal": { "summary": "Saque para cartão", "value": { "pixkeytype": "cpf", "pixkey": "98765432100", "requestedamount": 7500, "description": "Saque cartão - Pagamento fornecedor", "isPix": false, "postbackUrl": "https://minha-api.com/webhook/withdrawals" } }, "minimal_request": { "summary": "Requisição mínima", "value": { "pixkeytype": "cpf", "pixkey": "11122233344", "requestedamount": 1000, "description": "Saque teste", "isPix": true } } } } } }, "responses": { "200": { "description": "Saque criado com sucesso", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/WithdrawalResponse" }, "examples": { ``` -------------------------------- ### Define webhook payloads and withdrawal objects in JSON Source: https://bancobabylon.readme.io/reference/webhooks-3 These JSON snippets illustrate how to configure the postback URL when creating a withdrawal, the base webhook payload structure, the detailed withdrawal object, and an example of a withdrawal.created event. They are used by the webhook endpoint to receive and process withdrawal notifications via HTTPS POST. ```JSON { "pixkeytype": "CPF", "pixkey": "99999999999", "requestedamount": 254, "description": "Saque via API", "isPix": true, "postbackUrl": "https://seu-dominio.com/webhook/withdrawals" } ``` ```JSON { "event": "withdrawal.created", "timestamp": "2025-07-10T17:40:27.373Z", "withdrawal": { // Dados completos do saque }, "metadata": { "source": "withdrawals_service", "version": "1.0.0" } } ``` ```JSON { "id": "756d4eec-9a22-44b0-a514-a27c366c5433", "company_id": "5e1ce642-b9f1-433c-a350-5f9cd3d16bf6", "requested_amount": 2.54, "currency": "BRL", "status": "pending", "created_at": "2025-07-10T14:40:26.270543", "updated_at": "2025-07-10T14:40:26.270543", "paid_at": null, "pix": { "key_type": "CPF", "key_value": "99999999999", "end_to_end_id": null }, "fee": 0, "net_amount": 2.54, "error_message": null } ``` ```JSON { "event": "withdrawal.created", "timestamp": "2025-07-10T17:40:27.373Z", "withdrawal": { "id": "756d4eec-9a22-44b0-a514-a27c366c5433", "company_id": "5e1ce642-b9f1-433c-a350-5f9cd3d16bf6", "requested_amount": 2.54, "currency": "BRL", "status": "pending", "created_at": "2025-07-10T14:40:26.270543", "updated_at": "2025-07-10T14:40:26.270543", "paid_at": null, "pix": { "key_type": "CPF", "key_value": "99999999999", "end_to_end_id": null }, "fee": 0, "net_amount": 2.54, "error_message": null }, "metadata": { "source": "withdrawals_service", "version": "1.0.0" } } ``` -------------------------------- ### Authenticate API Requests with Basic Auth in Node.js, PHP, and cURL Source: https://bancobabylon.readme.io/reference/introdu%C3%A7%C3%A3o Demonstrates how to implement Basic Authentication for accessing the Banco BABYLON API endpoints. Requires a Secret Key (username) and Company ID (password) obtained from the gateway panel. The examples show encoding credentials in Base64, setting Authorization headers, and making POST requests to transaction endpoints. Limitations include ensuring HTTPS usage and never exposing credentials in client-side code. ```typescript const secretKey = "sua_secret_key_aqui"; const companyId = "seu_company_id_aqui"; const credentials = Buffer.from(`${secretKey}:${companyId}`).toString("base64"); const options = { method: "POST", url: "https://api.bancobabylon.com/functions/v1/transactions", headers: { "Authorization": `Basic ${credentials}`, "Content-Type": "application/json" }, }; ``` ```php "example" ]); $curl = curl_init(); curl_setopt_array($curl, [ CURLOPT_URL => "https://api.bancobabylon.com/functions/v1/transactions", CURLOPT_RETURNTRANSFER => true, CURLOPT_POST => true, CURLOPT_POSTFIELDS => $data, CURLOPT_HTTPHEADER => $headers ]); $response = curl_exec($curl); $httpCode = curl_getinfo($curl, CURLINFO_HTTP_CODE); curl_close($curl); if ($httpCode === 200) { $result = json_decode($response, true); // Processar resposta } else { // Tratar erro echo "Erro na requisição: " . $httpCode; } ?> ``` ```bash curl -X POST \ https://api.bancobabylon.com/functions/v1/transactions \ -H "Authorization: Basic $(echo -n 'SECRET_KEY:COMPANY_ID' | base64)" \ -H "Content-Type: application/json" \ -d '{"data": "example"}' ``` -------------------------------- ### Listar Transações API Request (cURL) Source: https://bancobabylon.readme.io/reference/transactions This snippet demonstrates how to make a GET request to the 'Listar Transações' API endpoint using cURL. It includes the base URL and common headers like 'accept'. ```shell curl --request GET \ --url https://api.bancobabylon.com/functions/v1/transactions \ --header 'accept: application/json' ``` -------------------------------- ### POST /websites/bancobabylon_readme_io_reference/pix/withdraw Source: https://bancobabylon.readme.io/reference/createwithdrawal Cria uma nova solicitação de saque PIX. É necessário fornecer um `Idempotency-Key` para garantir que a requisição não seja duplicada. ```APIDOC ## POST /pix/withdraw ### Description Cria uma nova solicitação de saque PIX. Garante que a requisição não seja duplicada através do header `Idempotency-Key`. ### Method POST ### Endpoint /pix/withdraw ### Parameters #### Header Parameters - **Idempotency-Key** (string) - Obrigatório - Chave para garantir a idempotência da requisição. #### Request Body - **amount** (number) - Obrigatório - Valor a ser sacado. - **recipient_account** (string) - Obrigatório - Conta do destinatário. - **recipient_bank** (string) - Obrigatório - Banco do destinatário. - **recipient_name** (string) - Obrigatório - Nome do destinatário. ### Request Example ```json { "amount": 100.50, "recipient_account": "1234567890", "recipient_bank": "001", "recipient_name": "Nome Sobrenome" } ``` ### Response #### Success Response (201 Created) - **id** (string) - ID único da solicitação de saque. - **status** (string) - Status atual do saque (`pending`, `approved`, `failed`, `cancelled`). #### Response Example ```json { "id": "sac-12345abc", "status": "pending" } ``` #### Error Response (400 Bad Request) - **error** (string) - Mensagem de erro descrevendo o problema. #### Error Response Example ```json { "error": "Idempotency-Key é obrigatório." } ``` ``` -------------------------------- ### Create Payment using Node.js Source: https://bancobabylon.readme.io/reference/payments Illustrates how to create a payment via the API using Node.js. It shows the necessary imports, request configuration, and how to send the payment details in the request body. ```javascript const axios = require('axios'); const createPayment = async (paymentMethod) => { try { const response = await axios.post('https://api.bancobabylon.com/functions/v1/transactions', { paymentMethod: paymentMethod }, { headers: { 'accept': 'application/json', 'content-type': 'application/json' } }); return response.data; } catch (error) { console.error('Error creating payment:', error); throw error; } }; // Example usage: // createPayment('PIX').then(data => console.log(data)).catch(err => console.error(err)); ``` -------------------------------- ### Error Response - Internal Error Source: https://bancobabylon.readme.io/reference/get_transactions Details the structure and example of a 500 Internal Server Error response from the API. ```APIDOC ## Error Response - Internal Error (500) ### Description Returned when an internal server error occurs. ### Response Body - **code** (string) - Error code identifier - **message** (string) - Human-readable error message ### Response Example ```json { "error": { "code": "INTERNAL_ERROR", "message": "Ocorreu um erro interno. Tente novamente em alguns instantes." } } ``` ``` -------------------------------- ### GET /transactions Source: https://bancobabylon.readme.io/reference/get_transactions Retrieves a paginated list of transactions with optional filters for status, payment method, and date range. Allows for efficient querying of transaction history. ```APIDOC ## GET /transactions ### Description Retorna uma lista paginada de transações com filtros opcionais por status, método de pagamento e período. ### Method GET ### Endpoint /transactions ### Parameters #### Query Parameters - **page** (integer) - Optional - Número da página (inicia em 1). Default: 1. Minimum: 1. - **limit** (integer) - Optional - Quantidade de registros por página (máximo 100). Default: 10. Minimum: 1. Maximum: 100. - **status** (string) - Optional - Filtrar por status da transação. Enum: ["pending", "paid", "failed", "refunded", "expired"] - **paymentMethod** (string) - Optional - Filtrar por método de pagamento. Enum: ["PIX", "CARD", "BOLETO"] - **startDate** (string) - Optional - Data inicial (formato: YYYY-MM-DD). - **endDate** (string) - Optional - Data final (formato: YYYY-MM-DD). ### Request Example ```json { "example": "No request body for GET request" } ``` ### Response #### Success Response (200) - **transactions** (array) - Lista de objetos de transação. - **pagination** (object) - Informações de paginação. - **currentPage** (integer) - Página atual. - **totalPages** (integer) - Total de páginas. - **totalItems** (integer) - Total de itens. - **itemsPerPage** (integer) - Itens por página. #### Response Example ```json { "transactions": [ { "id": "txn_12345abcde", "status": "paid", "amount": 10000, "currency": "BRL", "paymentMethod": "PIX", "createdAt": "2023-10-27T10:00:00Z", "updatedAt": "2023-10-27T10:05:00Z" } ], "pagination": { "currentPage": 1, "totalPages": 5, "totalItems": 50, "itemsPerPage": 10 } } ``` ``` -------------------------------- ### GET /functions/v1/transactions Source: https://bancobabylon.readme.io/reference/transactions Returns a paginated list of transactions with optional filters by status, payment method, and date range. Supports pagination through page and limit parameters. ```APIDOC ## GET /functions/v1/transactions ### Description Returns a paginated list of transactions with optional filters by status, payment method, and period. ### Method GET ### Endpoint https://api.bancobabylon.com/functions/v1/transactions ### Parameters #### Path Parameters None #### Query Parameters - **page** (integer) - Optional - Número da página (inicia em 1). Defaults to 1 - **limit** (integer) - Optional - Quantidade de registros por página (máximo 100). Defaults to 10 - **status** (string) - Optional - Filtrar por status da transação. Allowed values: `pending`, `paid`, `failed`, `refunded`, `expired` - **paymentMethod** (string) - Optional - Filtrar por método de pagamento. Allowed values: `PIX`, `CARD`, `BOLETO` - **startDate** (date) - Optional - Data inicial (formato: YYYY-MM-DD) - **endDate** (date) - Optional - Data final (formato: YYYY-MM-DD) #### Request Body None ### Request Example ``` curl --request GET \ --url https://api.bancobabylon.com/functions/v1/transactions \ --header 'accept: application/json' ``` ### Response #### Success Response (200) - **data** (array) - Array of transaction objects (PixPaymentResponse, CardPaymentResponse, or BoletoPaymentResponse) - **pagination** (object) - Pagination information - **currentPage** (integer) - Current page number - **totalPages** (integer) - Total number of pages - **totalItems** (integer) - Total number of items - **itemsPerPage** (integer) - Number of items per page #### Response Example ``` { "data": [ { "id": "transaction_123", "status": "paid", "paymentMethod": "PIX", "amount": 100.00, "createdAt": "2023-01-15T10:30:00Z" } ], "pagination": { "currentPage": 1, "totalPages": 5, "totalItems": 50, "itemsPerPage": 10 } } ``` #### Error Response (400) - **error** (object) - Error information - **code** (string) - Código identificador do erro - **message** (string) - Mensagem descritiva do erro - **details** (array of strings) - Detalhes específicos do erro #### Error Response (401) - **error** (object) - Error information - **code** (string) - Código identificador do erro - **message** (string) - Mensagem descritiva do erro - **details** (array of strings) - Detalhes específicos do erro #### Error Response (500) - **error** (object) - Error information - **code** (string) - Código identificador do erro - **message** (string) - Mensagem descritiva do erro - **details** (array of strings) - Detalhes específicos do erro ``` -------------------------------- ### POST Create Payment Source: https://bancobabylon.readme.io/reference/post_transactions Cria uma nova transação de pagamento. Requer corpo JSON com dados do cliente, itens, valor total e método de pagamento. Suporta Basic Auth e retorna respostas para sucesso, erro de validação, autenticação e erros internos. ```APIDOC ## POST Create Payment ### Description Cria uma nova transação de pagamento. O corpo da requisição deve seguir o schema CreatePaymentRequest. ### Method POST ### Endpoint /path/to/payments (ex.: /payments) ### Parameters #### Path Parameters - N/A #### Query Parameters - N/A #### Request Body - **customer** (Customer) - Required - Dados do cliente - **shipping** (ShippingAddress) - Optional - Endereço de entrega - **paymentMethod** (string) - Required - Método de pagamento: PIX, CARD, BOLETO - **card** (Card) - Optional - Dados do cartão (se paymentMethod = CARD) - **boleto** (BoletoConfig) - Optional - Configuração de boleto (se paymentMethod = BOLETO) - **pix** (PixConfig) - Optional - Configuração de PIX (se paymentMethod = PIX) - **installments** (integer) - Optional - Número de parcelas (1-12, padrão 1; apenas para cartão) - **items** (array) - Required - Lista de itens da transação (mín. 1) - **split** (array) - Optional - Regras de divisão da transação entre múltiplos recebedores - **amount** (integer) - Required - Valor total em centavos (mínimo 100) - **postbackUrl** (string, uri) - Optional - URL para receber notificações de mudança de status - **metadata** (object) - Optional - Dados adicionais em formato JSON - **ip** (string, ipv4) - Optional - Endereço IP do cliente (para análise antifraude) - **description** (string) - Optional - Descrição da transação (máx. 500 caracteres) ### Request Example { "customer": { "name": "João da Silva Santos", "email": "joao.silva@example.com", "phone": "11987654321", "document": { "number": "12345678901", "type": "CPF" } }, "paymentMethod": "CARD", "items": [ { "id": "sku_123", "title": "Produto Digital", "unitPrice": 2500, "quantity": 2, "tangible": false } ], "amount": 5000, "installments": 1, "postbackUrl": "https://webhook.site/your-endpoint", "metadata": { "campaign": "summer_sale" }, "ip": "192.168.1.1", "description": "Compra de produto digital" } ### Response #### Success Response (200) - **status** (string) - Status atual da transação - **paymentMethod** (string) - Método de pagamento utilizado - **customer** (Customer) - Dados do cliente - **items** (array) - Itens processados - **amount** (integer) - Valor total em centavos - **postbackUrl** (string, uri) - URL de notificação configurada - **metadata** (object) - Dados adicionais - **installments** (integer) - Número de parcelas (apenas para cartão) #### Response Example { "status": "authorized", "paymentMethod": "CARD", "customer": { "name": "João da Silva Santos", "email": "joao.silva@example.com", "phone": "11987654321", "document": { "number": "12345678901", "type": "CPF" } }, "items": [ { "id": "sku_123", "title": "Produto Digital", "unitPrice": 2500, "quantity": 2, "tangible": false } ], "amount": 5000, "installments": 1, "postbackUrl": "https://webhook.site/your-endpoint", "metadata": { "campaign": "summer_sale" } } #### Error Responses - **400** - BadRequest - **401** - Unauthorized - **422** - ValidationError - **500** - InternalError #### Security - **basicAuth** - Requer autenticação Basic Auth ``` -------------------------------- ### POST /websites/bancobabylon_readme_io_reference/card/withdraw Source: https://bancobabylon.readme.io/reference/createwithdrawal Cria uma nova solicitação de saque via cartão. É necessário fornecer um `Idempotency-Key` para evitar duplicatas. ```APIDOC ## POST /card/withdraw ### Description Cria uma nova solicitação de saque via cartão. O header `Idempotency-Key` é obrigatório para evitar requisições duplicadas. ### Method POST ### Endpoint /card/withdraw ### Parameters #### Header Parameters - **Idempotency-Key** (string) - Obrigatório - Chave para garantir a idempotência da requisição. #### Request Body - **amount** (number) - Obrigatório - Valor a ser sacado. - **card_number** (string) - Obrigatório - Número do cartão para o saque. - **card_expiration** (string) - Obrigatório - Data de expiração do cartão (MM/AA). - **card_cvv** (string) - Obrigatório - Código de segurança do cartão. ### Request Example ```json { "amount": 150.75, "card_number": "1111222233334444", "card_expiration": "12/25", "card_cvv": "123" } ``` ### Response #### Success Response (201 Created) - **id** (string) - ID único da solicitação de saque. - **status** (string) - Status atual do saque (`pending`, `approved`, `failed`, `cancelled`). #### Response Example ```json { "id": "sac-56789def", "status": "pending" } ``` #### Error Response (400 Bad Request) - **error** (string) - Mensagem de erro descrevendo o problema. #### Error Response Example ```json { "error": "Informações do cartão inválidas." } ``` ``` -------------------------------- ### Basic Authentication Source: https://bancobabylon.readme.io/reference/post_transactions Details for HTTP Basic authentication using API Key as username and empty password. ```APIDOC ## Basic Authentication ### Description Autenticação HTTP Basic usando API Key como username e deixando password vazio. ### Security Scheme - **type**: http - **scheme**: basic ``` -------------------------------- ### Define API Error Responses Source: https://bancobabylon.readme.io/reference/put_transactions-id-delivery This snippet defines standard error responses for the API, such as BadRequest, NotFound, ValidationError, and InternalError. Each response includes a schema reference and example structures. Used to ensure consistent error messaging. ```json { "responses": { "BadRequest": { "description": "Requisição inválida - parâmetros malformados", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/ErrorResponse" }, "example": { "error": { "code": "BAD_REQUEST", "message": "A requisição contém parâmetros inválidos", "details": [ "O campo 'amount' deve ser um número inteiro" ] } } } } }, "NotFound": { "description": "Recurso não encontrado", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/ErrorResponse" }, "example": { "error": { "code": "NOT_FOUND", "message": "Transação não encontrada" } } } } }, "ValidationError": { "description": "Erro de validação - dados não atendem aos requisitos", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/ErrorResponse" }, "example": { "error": { "code": "VALIDATION_ERROR", "message": "Dados de entrada inválidos", "details": [ "O e-mail deve ter um formato válido", "O valor mínimo é R$ 1,00" ] } } } } }, "InternalError": { "description": "Erro interno do servidor", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/ErrorResponse" }, "example": { "error": { "code": "INTERNAL_ERROR", "message": "Ocorreu um erro interno. Tente novamente em alguns instantes." } } } } } } } ``` -------------------------------- ### Webhook Handler Implementation (Node.js/Express) Source: https://bancobabylon.readme.io/reference/webhooks-3 Basic Express server implementation for handling Banco Babylon withdrawal webhooks. Routes events to appropriate handlers and always responds with 200 OK to prevent retries. Requires express dependency. ```javascript const express = require('express'); const app = express(); app.use(express.json()); app.post('/webhook/withdrawals', (req, res) => { const { event, withdrawal, timestamp } = req.body; console.log(`[${timestamp}] Evento recebido: ${event}`); console.log(`Saque ID: ${withdrawal.id}, Status: ${withdrawal.status}`); try { switch (event) { case 'withdrawal.created': handleWithdrawalCreated(withdrawal); break; case 'withdrawal.status_changed': handleStatusChanged(withdrawal); break; case 'withdrawal.completed': handleWithdrawalCompleted(withdrawal); break; case 'withdrawal.failed': handleWithdrawalFailed(withdrawal); break; default: console.log(`Evento desconhecido: ${event}`); } // IMPORTANTE: Sempre responder com 200 res.status(200).send('OK'); } catch (error) { console.error('Erro ao processar webhook:', error); res.status(200).send('OK'); // Ainda assim responder 200 para evitar retry } }); function handleWithdrawalCreated(withdrawal) { console.log('Novo saque criado:', withdrawal.id); // Salvar no banco, enviar notificação, etc. } function handleStatusChanged(withdrawal) { console.log(`Status alterado para: ${withdrawal.status}`); // Atualizar status no seu sistema } function handleWithdrawalCompleted(withdrawal) { console.log('Saque concluído!', withdrawal.id); // Confirmar pagamento, atualizar saldo, etc. } function handleWithdrawalFailed(withdrawal) { console.log('Saque falhou:', withdrawal.error_message); // Tratar erro, reverter operações, notificar usuário } app.listen(3000, () => { console.log('Servidor webhook rodando na porta 3000'); }); ``` -------------------------------- ### Item Data Model Source: https://bancobabylon.readme.io/reference/post_transactions Represents an item with a title, unit price, and quantity. ```APIDOC ## Item Data Model ### Description Represents an item with a title, unit price, and quantity. ### Type object ### Properties #### title (string) Required - Nome/descrição do item. MinLength: 1, MaxLength: 100. Example: `Produto Digital Premium` #### unitPrice (integer) Required - Preço unitário em centavos. Minimum: 1. Example: `2500` #### quantity (integer) ``` -------------------------------- ### GET /transactions/{id} Source: https://bancobabylon.readme.io/reference/get_transactions-id Este endpoint permite consultar os detalhes completos de uma transação específica utilizando seu ID único. É útil para verificar o status e informações de pagamentos processados via PIX, cartão de crédito ou boleto. Requer autenticação básica e retorna dados em formato JSON baseados no tipo de pagamento. ```APIDOC ## GET /transactions/{id} ### Description Obtém os detalhes completos de uma transação específica pelo ID. Suporta respostas para diferentes tipos de pagamento (PIX, cartão ou boleto). ### Method GET ### Endpoint /transactions/{id} ### Parameters #### Path Parameters - **id** (string, format: uuid) - Required - ID único da transação #### Query Parameters None #### Request Body None ### Request Example N/A (GET request with path parameter) ### Response #### Success Response (200) - **transactionDetails** (object) - Detalhes da transação, variando por tipo de pagamento (PIX, cartão ou boleto) #### Response Example { "oneOf": [ { "$ref": "#/components/schemas/PixPaymentResponse" }, { "$ref": "#/components/schemas/CardPaymentResponse" }, { "$ref": "#/components/schemas/BoletoPaymentResponse" } ] } #### Error Responses - **401** - Unauthorized (referência a componentes/responses/Unauthorized) - **404** - Not Found (referência a componentes/responses/NotFound) - **500** - Internal Server Error (referência a componentes/responses/InternalError) ```