> ## 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.

# Node.js

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

## Instalação

```bash theme={null}
npm install @paybeehive/beehivehub-nodejs-sdk
```

## Autenticação

Inicialize o SDK com a sua `SECRET_KEY`:

```typescript theme={null}
import BeehiveHub from "@paybeehive/beehivehub-nodejs-sdk";

const beehive = BeehiveHub(process.env.BEEHIVE_SECRET_KEY!);
```

## Ambiente Sandbox

Se quiser usar o ambiente de testes:

```typescript theme={null}
import BeehiveHub from "@paybeehive/beehivehub-nodejs-sdk";

const beehive = BeehiveHub(process.env.BEEHIVE_SECRET_KEY!, {
  environment: "sandbox",
});
```

## Primeiro uso

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

```typescript theme={null}
import BeehiveHub from "@paybeehive/beehivehub-nodejs-sdk";

const beehive = BeehiveHub(process.env.BEEHIVE_SECRET_KEY!);

async function criarTransacao() {
  const response = await 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",
    },
  });

  return response;
}
```

## Recursos disponíveis

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

* `transactions`
* `customers`
* `transfers`
* `balance`
* `recipients`
* `bankAccounts`
* `company`
* `paymentLinks`

***

## Transações

### Criar transação

```typescript theme={null}
const transaction = await 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

```typescript theme={null}
const transactions = await beehive.transactions.list({
  limit: 50,
  offset: 0,
  createdFrom: "2026-01-01T00:00:00",
})
```

### Buscar transação por ID

```typescript theme={null}
const transaction = await beehive.transactions.get(123456);
```

### Reembolsar transação

```typescript theme={null}
const fullRefund = await beehive.transactions.refund(123456);

const partialRefund = await beehive.transactions.refund(123456, 3000);
```

### Atualizar status de entrega

```typescript theme={null}
const delivery = await beehive.transactions.updateDelivery(123456, {
  status: "in_transit",
  trackingCode: "BR123456789",
});
```

***

## Clientes

### Criar cliente

```typescript theme={null}
const customer = await 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.

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

### Buscar cliente por ID

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

***

## Transferências

### Criar transferência

```typescript theme={null}
const transfer = await beehive.transfers.create({
  amount: 50000,
  recipientId: 916,
});
```

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

```typescript theme={null}
const transferWithAccount = await 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

```typescript theme={null}
const transfer = await beehive.transfers.get(123456);
```

***

## Saldo

### Consultar saldo

```typescript theme={null}
const balance = await beehive.balance.get();

console.log(`Available: BRL ${balance.amount / 100}`);
console.log(`Recipient ID: ${balance.recipientId}`);
```

***

## Recebedores

### Criar recebedor

```typescript theme={null}
const recipient = await 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

```typescript theme={null}
const recipients = await beehive.recipients.list();
```

### Buscar recebedor por ID

```typescript theme={null}
const recipient = await beehive.recipients.get(916);
```

### Atualizar recebedor

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

***

## Contas bancárias

### Adicionar conta bancária a um recebedor

```typescript theme={null}
const bankAccount = await beehive.bankAccounts.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

```typescript theme={null}
const accounts = await beehive.bankAccounts.list(916);
```

***

## Empresa

### Consultar dados da empresa

```typescript theme={null}
const company = await beehive.company.get();
```

### Atualizar dados da empresa

```typescript theme={null}
const updated = await 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

```typescript theme={null}
const paymentLink = await beehive.paymentLinks.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,
    },
  },
});

// paymentLink.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.

```typescript theme={null}
const paymentLinks = await beehive.paymentLinks.list();
```

### Buscar link de pagamento por ID

```typescript theme={null}
const paymentLink = await beehive.paymentLinks.get(247);
```

### Atualizar link de pagamento

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

```typescript theme={null}
const updated = await beehive.paymentLinks.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

```text theme={null}
await beehive.paymentLinks.delete(247);
```

***

## Tratamento de erros

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

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

Exemplo:

```typescript theme={null}
import BeehiveHub, {
  BeehiveHubAPIError,
  BeehiveHubAuthenticationError,
  BeehiveHubValidationError,
} from "@paybeehive/beehivehub-nodejs-sdk";

const beehive = BeehiveHub(process.env.BEEHIVE_SECRET_KEY!);

try {
  const transaction = await beehive.transactions.create({
    amount: 10000,
    paymentMethod: "pix",
    customer: {
      name: "João Silva",
      email: "joao@example.com",
      document: {
        type: "cpf",
        number: "12345678900",
      },
      phone: "11999999999",
    },
  });

  console.log("Transaction created:", transaction);
} catch (error) {
  if (error instanceof BeehiveHubAuthenticationError) {
    console.error("Invalid API key:", error.message);
  } else if (error instanceof BeehiveHubValidationError) {
    console.error("Validation error:", error.message);
  } else if (error instanceof BeehiveHubAPIError) {
    console.error("API error:", error.message);
  } else {
    console.error("Unexpected error:", error);
  }
}
```

***

## Valores em centavos

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

```typescript theme={null}
// R$ 100,00
amount: 10000;

// R$ 1,50
amount: 150;

// Convertendo reais para centavos
const reais = 100.0;
const cents = Math.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
```

```typescript theme={null}
// app.ts
import BeehiveHub from "@paybeehive/beehivehub-nodejs-sdk";
import dotenv from "dotenv";

dotenv.config();

const beehive = BeehiveHub(process.env.BEEHIVE_SECRET_KEY!);
```

***
