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

# Python

<Card color="#3572A5" icon="python" iconType="brands" href="https://github.com/paybeehive/beehivehub-python-sdk" title="Python">
  SDK oficial para integração com a API do Beehive Hub. Aceite pagamentos de forma simples e rápida.
</Card>

## Requisitos

* Python 3.10 ou superior
* Dependências instaladas automaticamente: `httpx` e `pydantic`

## Instalação

```bash theme={null}
pip install beehivehub-python-sdk
```

## Autenticação

Inicialize o SDK com a sua `SECRET_KEY`:

```python theme={null}
import os
from beehivehub import create_beehivehub_client

beehive = create_beehivehub_client(os.environ["BEEHIVE_SECRET_KEY"])
```

## Ambiente Sandbox

Se quiser usar o ambiente de testes:

```python theme={null}
import os
from beehivehub import create_beehivehub_client

beehive = create_beehivehub_client(os.environ["BEEHIVE_SECRET_KEY"], environment="sandbox")
```

## Primeiro uso

Exemplo de criação de uma transação Pix:

```python theme={null}
import os
from beehivehub import create_beehivehub_client

beehive = create_beehivehub_client(os.environ["BEEHIVE_SECRET_KEY"])

transaction = beehive.transactions.create({
    "amount": 15990,
    "paymentMethod": "pix",
    "customer": {
        "name": "Ana Souza",
        "email": "ana.souza@email.com",
        "document": {
            "type": "cpf",
            "number": "00000000191",
        },
        "phone": "11999999999",
    },
    "items": [
        {
            "title": "Pedido #1001",
            "unitPrice": 15990,
            "quantity": 1,
            "tangible": True,
        },
    ],
    "postbackUrl": "https://seusite.com/webhook",
    "metadata": {
        "orderId": "1001",
    },
})
```

## Recursos disponíveis

O SDK possui métodos para os principais recursos da API:

* `transactions`
* `customers`
* `transfers`
* `balance`
* `recipients`
* `bank_accounts`
* `company`
* `payment_links`

***

## Transações

### Criar transação

```python theme={null}
transaction = beehive.transactions.create({
    "amount": 8900,
    "paymentMethod": "pix",
    "customer": {
        "name": "Carlos Lima",
        "email": "carlos@email.com",
        "document": {
            "type": "cpf",
            "number": "00000000191",
        },
        "phone": "11988888888",
    },
    "items": [
        {
            "title": "Produto teste",
            "unitPrice": 8900,
            "quantity": 1,
            "tangible": True,
        },
    ],
})
```

### Listar transações

```python theme={null}
transactions = beehive.transactions.list({
    "status": "paid",
    "paymentMethods": "pix",
})
```

### Buscar transação por ID

```python theme={null}
transaction = beehive.transactions.get(123456)
```

### Reembolsar transação

```python theme={null}
full_refund = beehive.transactions.refund(123456)

partial_refund = beehive.transactions.refund(123456, 3000)
```

### Atualizar status de entrega

```python theme={null}
delivery = beehive.transactions.update_delivery(123456, {
    "status": "in_transit",
    "trackingCode": "BR123456789",
})
```

***

## Clientes

### Criar cliente

```python theme={null}
customer = beehive.customers.create({
    "name": "Mariana Costa",
    "email": "mariana@email.com",
    "document": {
        "type": "cpf",
        "number": "98765432100",
    },
    "phone": "11977777777",
    "address": {
        "street": "Rua Exemplo",
        "streetNumber": "200",
        "complement": "Sala 3",
        "neighborhood": "Centro",
        "zipCode": "01001000",
        "city": "São Paulo",
        "state": "SP",
        "country": "br",
    },
})
```

### Listar clientes

> O parâmetro `email` é obrigatório nessa listagem. A API não utiliza paginação convencional para este recurso.

```python theme={null}
customers = beehive.customers.list({
    "email": "cliente@example.com",
})
```

### Buscar cliente por ID

```python theme={null}
customer = beehive.customers.get(123456)
```

***

## Transferências

### Criar transferência

```python theme={null}
transfer = beehive.transfers.create({
    "amount": 50000,
    "recipientId": 916,
})
```

### Criar transferência com conta bancária

```python theme={null}
transfer = beehive.transfers.create({
    "amount": 50000,
    "recipientId": 916,
    "bankAccount": {
        "bankCode": "001",
        "agencyNumber": "1234",
        "accountNumber": "12345",
        "accountDigit": "6",
        "type": "conta_corrente",
        "legalName": "Destinatário Teste",
        "documentNumber": "12345678900",
        "documentType": "cpf",
    },
})
```

### Buscar transferência por ID

```python theme={null}
transfer = beehive.transfers.get(123456)
```

***

## Saldo

### Consultar saldo

```python theme={null}
balance = beehive.balance.get()

print(f"Available: BRL {balance['amount'] / 100}")
print(f"Recipient ID: {balance['recipientId']}")
```

***

## Recebedores

### Criar recebedor

```python theme={null}
recipient = beehive.recipients.create({
    "legalName": "Recebedor Teste Ltda",
    "document": {
        "type": "cnpj",
        "number": "58593776000142",
    },
    "transferSettings": {
        "transferEnabled": True,
        "automaticAnticipationEnabled": False,
        "anticipatableVolumePercentage": 100,
    },
    "bankAccount": {
        "bankCode": "001",
        "agencyNumber": "1234",
        "accountNumber": "12345",
        "accountDigit": "6",
        "type": "conta_corrente",
        "legalName": "Recebedor Teste Ltda",
        "documentNumber": "58593776000142",
        "documentType": "cnpj",
    },
})
```

### Listar recebedores

```python theme={null}
recipients = beehive.recipients.list()
```

### Buscar recebedor por ID

```python theme={null}
recipient = beehive.recipients.get(916)
```

### Atualizar recebedor

```python theme={null}
updated = beehive.recipients.update(916, {
    "legalName": "Beehive Sandbox",
})
```

***

## Contas bancárias

### Adicionar conta bancária a um recebedor

```python theme={null}
bank_account = beehive.bank_accounts.create(916, {
    "bankCode": "341",
    "agencyNumber": "9876",
    "accountNumber": "54321",
    "accountDigit": "0",
    "type": "conta_poupanca",
    "legalName": "Empresa Teste Ltda",
    "documentNumber": "60572883000136",
    "documentType": "cnpj",
})
```

### Listar contas bancárias

```python theme={null}
accounts = beehive.bank_accounts.list(916)
```

***

## Empresa

### Consultar dados da empresa

```python theme={null}
company = beehive.company.get()
```

### Atualizar dados da empresa

```python theme={null}
updated = beehive.company.update({
    "invoiceDescriptor": "Beehive Hub",
    "details": {
        "averageRevenue": 10000,
        "averageTicket": 100.5,
        "physicalProducts": True,
        "productsDescription": "Produtos físicos",
        "siteUrl": "https://www.meusite.com.br",
        "phone": "11999999999",
        "email": "contato@meusite.com.br",
    },
})
```

***

## Links de pagamento

O SDK adiciona a propriedade `url` nas respostas de criação, consulta, listagem e atualização quando existe um `alias`.

* Produção: `https://link.conta.paybeehive.com.br/{alias}`
* Sandbox: `https://link.sandbox.hopysplit.com.br/{alias}`

Se `alias` não for enviado, o SDK gera automaticamente um código alfanumérico de 10 caracteres.

### Criar link de pagamento

```python theme={null}
payment_link = beehive.payment_links.create({
    "title": "novo link alterado",
    "alias": "alias_alterado",
    "amount": 1000,
    "settings": {
        "defaultPaymentMethod": "credit_card",
        "requestAddress": True,
        "requestPhone": True,
        "traceable": True,
        "boleto": {
            "enabled": True,
            "expiresInDays": 0,
        },
        "pix": {
            "enabled": False,
            "expiresInDays": 0,
        },
        "card": {
            "enabled": False,
            "freeInstallments": 1,
            "maxInstallments": 12,
        },
    },
})

# payment_link["url"] já vem montada
```

### Listar links de pagamento

> A API não aceita filtros por query parameters nesse recurso. A listagem retorna todos os links da empresa.

```python theme={null}
payment_links = beehive.payment_links.list()
```

### Buscar link de pagamento por ID

```python theme={null}
payment_link = beehive.payment_links.get(247)
```

### Atualizar link de pagamento

> A atualização aceita payload parcial, ou seja, você pode enviar apenas os campos que deseja alterar.

```python theme={null}
updated = beehive.payment_links.update(247, {
    "title": "novo link alterado",
    "alias": "alias_alterado",
    "amount": 1000,
    "settings": {
        "defaultPaymentMethod": "credit_card",
        "requestAddress": True,
        "requestPhone": True,
        "traceable": True,
        "boleto": {
            "enabled": True,
            "expiresInDays": 0,
        },
        "pix": {
            "enabled": False,
            "expiresInDays": 0,
        },
        "card": {
            "enabled": False,
            "freeInstallments": 1,
            "maxInstallments": 12,
        },
    },
})
```

### Excluir link de pagamento

```python theme={null}
beehive.payment_links.delete(247)
```

***

## Tratamento de erros

O SDK expõe classes específicas para tratamento de erro:

* `BeehiveHubAPIError`
* `BeehiveHubAuthenticationError`
* `BeehiveHubValidationError`
* `BeehiveHubNotFoundError`
* `BeehiveHubRateLimitError`
* `BeehiveHubNetworkError`

Exemplo:

```python theme={null}
import os
from beehivehub import (
    create_beehivehub_client,
    BeehiveHubAPIError,
    BeehiveHubAuthenticationError,
    BeehiveHubValidationError,
)

beehive = create_beehivehub_client(os.environ["BEEHIVE_SECRET_KEY"])

try:
    transaction = beehive.transactions.create({
        "amount": 10000,
        "paymentMethod": "pix",
        "customer": {
            "name": "João Silva",
            "email": "joao@example.com",
            "document": {
                "type": "cpf",
                "number": "12345678900",
            },
            "phone": "11999999999",
        },
    })
    print("Transaction created:", transaction)
except BeehiveHubAuthenticationError as e:
    print(f"Invalid API key: {e}")
except BeehiveHubValidationError as e:
    print(f"Validation error: {e}")
except BeehiveHubAPIError as e:
    print(f"API error: {e}")
except Exception as e:
    print(f"Unexpected error: {e}")
```

***

## Valores em centavos

Todos os valores monetários enviados para a API devem ser informados em centavos.

```python theme={null}
# R$ 100,00
amount = 10000

# R$ 1,50
amount = 150

# Convertendo reais para centavos
reais = 100.0
cents = round(reais * 100)
```

***

## Boas práticas de segurança

* Nunca exponha sua `SECRET_KEY`
* Não gere `card_hash` no backend
* Valide os dados antes de enviar para a API
* Use HTTPS
* Implemente webhooks para acompanhar mudanças de status

```text theme={null}
# .env
BEEHIVE_SECRET_KEY=your_secret_key_here
```

```python theme={null}
# app.py
import os
from dotenv import load_dotenv
from beehivehub import create_beehivehub_client

load_dotenv()

beehive = create_beehivehub_client(os.environ["BEEHIVE_SECRET_KEY"])
```

***
