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

# PHP

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

## Requisitos

* PHP 8.2 ou superior
* Extensão `curl`
* Extensão `json`
* Composer

## Instalação

```bash theme={null}
composer require paybeehive/beehivehub-php-sdk
```

## Autenticação

Inicialize o SDK com a sua `SECRET_KEY`:

```php theme={null}
use BeehiveHub\SDK\BeehiveHubClient;

$beehive = new BeehiveHubClient($_ENV['BEEHIVE_SECRET_KEY']);
```

## Ambiente Sandbox

Se quiser usar o ambiente de testes:

```php theme={null}
use BeehiveHub\SDK\BeehiveHubClient;

$beehive = new BeehiveHubClient($_ENV['BEEHIVE_SECRET_KEY'], [
    'environment' => 'sandbox',
]);
```

## Primeiro uso

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

```php theme={null}
use BeehiveHub\SDK\BeehiveHubClient;

$beehive = new BeehiveHubClient($_ENV['BEEHIVE_SECRET_KEY']);

$response = $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`
* `bankAccounts`
* `company`
* `paymentLinks`

***

## Transações

### Criar transação

```php 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

```php theme={null}
$transactions = $beehive->transactions->list([
    'limit' => 50,
    'offset' => 0,
    'createdFrom' => '2026-01-01T00:00:00',
]);
```

### Buscar transação por ID

```php theme={null}
$transaction = $beehive->transactions->get(123456);
```

### Reembolsar transação

```php theme={null}
// Reembolso total
$fullRefund = $beehive->transactions->refund(123456);

// Reembolso parcial
$partialRefund = $beehive->transactions->refund(123456, 3000);
```

### Atualizar status de entrega

```php theme={null}
$delivery = $beehive->transactions->updateDelivery(123456, [
    'status' => 'in_transit',
    'trackingCode' => 'BR123456789',
]);
```

***

## Clientes

### Criar cliente

```php 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.

```php theme={null}
$customers = $beehive->customers->list([
    'email' => 'cliente@example.com',
]);
```

### Buscar cliente por ID

```php theme={null}
$customer = $beehive->customers->get(123456);
```

***

## Transferências

### Criar transferência

```php theme={null}
$transfer = $beehive->transfers->create([
    'amount' => 50000,
    'recipientId' => 916,
]);
```

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

```php 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

```php theme={null}
$transfer = $beehive->transfers->get(123456);
```

***

## Saldo

### Consultar saldo

```php theme={null}
$balance = $beehive->balance->get();

echo 'Available: BRL ' . ($balance['amount'] / 100) . PHP_EOL;
echo 'Recipient ID: ' . $balance['recipientId'] . PHP_EOL;
```

***

## Recebedores

### Criar recebedor

```php 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

```php theme={null}
$recipients = $beehive->recipients->list();
```

### Buscar recebedor por ID

```php theme={null}
$recipient = $beehive->recipients->get(916);
```

### Atualizar recebedor

```php theme={null}
$updated = $beehive->recipients->update(916, [
    'legalName' => 'Beehive Sandbox',
]);
```

***

## Contas bancárias

### Adicionar conta bancária a um recebedor

```php theme={null}
$bankAccount = $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

```php theme={null}
$accounts = $beehive->bankAccounts->list(916);
```

***

## Empresa

### Consultar dados da empresa

```php theme={null}
$company = $beehive->company->get();
```

### Atualizar dados da empresa

```php 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

```php theme={null}
$paymentLink = $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.

```php theme={null}
$paymentLinks = $beehive->paymentLinks->list();
```

### Buscar link de pagamento por ID

```php theme={null}
$paymentLink = $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.

```php theme={null}
$updated = $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

```php theme={null}
$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:

```php theme={null}
use BeehiveHub\SDK\BeehiveHubClient;
use BeehiveHub\SDK\Exceptions\BeehiveHubAPIError;
use BeehiveHub\SDK\Exceptions\BeehiveHubAuthenticationError;
use BeehiveHub\SDK\Exceptions\BeehiveHubValidationError;

$beehive = new BeehiveHubClient($_ENV['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',
        ],
    ]);

    echo 'Transaction created: ' . $transaction['id'];
} catch (BeehiveHubAuthenticationError $e) {
    echo 'Invalid API key: ' . $e->getMessage();
} catch (BeehiveHubValidationError $e) {
    echo 'Validation error: ' . $e->getMessage();
} catch (BeehiveHubAPIError $e) {
    echo 'API error: ' . $e->getMessage();
} catch (\Exception $e) {
    echo 'Unexpected error: ' . $e->getMessage();
}
```

***

## Valores em centavos

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

```php theme={null}
// R$ 100,00
'amount' => 10000

// R$ 1,50
'amount' => 150

// Convertendo reais para centavos
$reais = 100.0;
$centavos = (int) round($reais * 100);
```

***

## Boas práticas de segurança

* Nunca exponha sua `SECRET_KEY`
* 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
```

```php theme={null}
// bootstrap.php
use BeehiveHub\SDK\BeehiveHubClient;

$dotenv = Dotenv\Dotenv::createImmutable(__DIR__);
$dotenv->load();

$beehive = new BeehiveHubClient($_ENV['BEEHIVE_SECRET_KEY']);
```

***
