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

# SDK JavaScript

> SDK oficial da RivooPay para JavaScript e TypeScript. Integre pagamentos PIX, gestão de clientes, produtos, webhooks e saques.

SDK oficial da **RivooPay** para JavaScript e TypeScript.

Integre pagamentos PIX, gestão de clientes, produtos, webhooks e saques em qualquer ambiente JS — Node.js, NestJS, Next.js, browser e mais.

## Instalação

<CodeGroup>
  ```bash npm theme={null}
  npm install @rivoo/sdk
  ```

  ```bash yarn theme={null}
  yarn add @rivoo/sdk
  ```

  ```bash pnpm theme={null}
  pnpm add @rivoo/sdk
  ```
</CodeGroup>

## Início Rápido e Simples

```ts theme={null}
import { RivooPay, WebhookEvent } from '@rivoo/sdk';

const rivoopay = new RivooPay({
  apiKey: 'cpk_sandbox_sua_chave_aqui',
});
```

## Cobranças

### Criar Link de Pagamento

```ts theme={null}
const charge = await rivoopay.charges.createPaymentLink({
  total: 5000, // R$ 50,00 (em centavos)
  customer: {
    taxId: '12345678900',
    name: 'João Silva',
    email: 'joao@email.com',
    phone: '11999999999',
  },
  successUrl: 'https://meusite.com/sucesso',
  failedUrl: 'https://meusite.com/falha',
  items: [
    { productId: 'prod_abc123', quantity: 2 },
  ],
});

console.log(charge.data?.url); // URL da página de pagamento
```

### Criar Cobrança PIX Direta

```ts theme={null}
const pix = await rivoopay.charges.createPixCharge({
  amount: 1500, // R$ 15,00
  customer: {
    taxId: '12345678900',
    name: 'Maria Santos',
    email: 'maria@email.com',
    phone: '11988888888',
  },
  expiresIn: 900, // 15 minutos em segundos
});

console.log(pix.data?.brCode);       // PIX copia-e-cola
console.log(pix.data?.brCodeBase64); // QR Code em base64
```

### Consultar Cobrança

```ts theme={null}
const charge = await rivoopay.charges.getById('charge_id_aqui');

console.log(charge.data?.status);        // OPEN | COMPLETED | EXPIRED
console.log(charge.data?.paymentStatus); // PENDING | PROCESSING | PAID | EXPIRED
```

### Gerar PIX para Link de Pagamento Existente

```ts theme={null}
const pixPayment = await rivoopay.charges.generatePixForCharge('charge_id', {
  customer: {
    taxId: '12345678900',
    name: 'João Silva',
    email: 'joao@email.com',
    phone: '11999999999',
  },
});
```

### Simular Pagamento (Sandbox)

<Note>
  Funciona apenas com cobranças criadas com `devMode: true`.
</Note>

```ts theme={null}
await rivoopay.charges.simulatePayment('charge_id');
```

### Idempotência

As operações de criação de cobrança suportam chave de idempotência (UUID v4, TTL 24h):

```ts theme={null}
const charge = await rivoopay.charges.createPixCharge(
  {
    amount: 5000,
    customer: {
      taxId: '12345678900',
      name: 'João Silva',
      email: 'joao@email.com',
      phone: '11999999999',
    },
  },
  { idempotencyKey: 'f47ac10b-58cc-4372-a567-0e02b2c3d479' },
);
```

## Clientes

```ts theme={null}
import { DefaultStatus } from '@rivoo/sdk';

// Listar todos
const customers = await rivoopay.customers.list();

// Buscar por ID
const customer = await rivoopay.customers.getById('cust_abc123');

// Criar cliente
const newCustomer = await rivoopay.customers.create({
  name: 'João Silva',
  taxId: '12345678900',
  email: 'joao@email.com',
  phone: '11999999999',
  status: DefaultStatus.ACTIVE,
  postalCode: '01001000',
  address: 'Praça da Sé',
  number: '1',
  district: 'Sé',
});

// Atualizar cliente
await rivoopay.customers.update({
  id: 'cust_abc123',
  phone: '11977777777',
  status: DefaultStatus.INACTIVE,
});
```

## Produtos

```ts theme={null}
import { DefaultStatus } from '@rivoo/sdk';

// Listar produtos
const products = await rivoopay.products.list({ status: DefaultStatus.ACTIVE });

// Buscar por ID
const product = await rivoopay.products.getById('prod_abc123');

// Buscar por SKU
const productBySku = await rivoopay.products.getBySku('PLAN-MONTHLY');

// Criar produto
const newProduct = await rivoopay.products.create({
  name: 'Plano Mensal',
  description: 'Assinatura mensal do serviço',
  price: 4990, // R$ 49,90 (em centavos)
  sku: 'PLAN-MONTHLY',
});

// Atualizar produto
await rivoopay.products.update({
  id: 'prod_abc123',
  price: 5990,
});
```

## Webhooks

```ts theme={null}
import { WebhookEvent } from '@rivoo/sdk';

// Listar webhooks
const webhooks = await rivoopay.webhooks.list();

// Criar webhook
const webhook = await rivoopay.webhooks.create({
  name: 'Meu Webhook',
  url: 'https://meusite.com/webhooks/rivoopay',
  events: [WebhookEvent.CHARGE_PAID, WebhookEvent.CHARGE_EXPIRED],
});

// Atualizar webhook
await rivoopay.webhooks.update({
  id: 'wh_abc123',
  events: [WebhookEvent.CHARGE_PAID],
});

// Deletar webhook
await rivoopay.webhooks.delete('wh_abc123');

// Listar eventos disponíveis
const events = await rivoopay.webhooks.listEvents();

// Estatísticas da fila
const stats = await rivoopay.webhooks.getQueueStats();
```

## Conta

```ts theme={null}
// Consultar saldo
const balance = await rivoopay.account.getBalance();

// Criar saque (transferência PIX)
const withdraw = await rivoopay.account.withdraw({
  value: 10000, // R$ 100,00
});

// Listar histórico de saques
const withdrawals = await rivoopay.account.listWithdrawals();
```

## Configuração Avançada

### Opções do Cliente

```ts theme={null}
const rivoopay = new RivooPay({
  // Autenticação (obrigatório)
  apiKey: 'cpk_sandbox_sua_chave_aqui',

  // URL customizada (padrão: https://api.rivopay.com)
  baseUrl: 'https://minha-api.com',

  // Ambiente sandbox
  sandbox: true,

  // Timeout em ms (padrão: 30000)
  timeout: 15000,

  // Retentativas automáticas em 429/5xx (padrão: 2)
  maxRetries: 3,

  // Headers extras
  headers: {
    'X-Custom-Header': 'valor',
  },

  // fetch customizado (Node.js < 18)
  fetch: customFetchImplementation,
});
```

| Opção        | Tipo       | Padrão                    | Descrição                                        |
| ------------ | ---------- | ------------------------- | ------------------------------------------------ |
| `apiKey`     | `string`   | —                         | Chave de API para autenticação **(obrigatório)** |
| `baseUrl`    | `string`   | `https://api.rivopay.com` | URL base da API                                  |
| `sandbox`    | `boolean`  | `false`                   | Habilita ambiente sandbox                        |
| `timeout`    | `number`   | `30000`                   | Timeout das requisições em milissegundos         |
| `maxRetries` | `number`   | `2`                       | Número máximo de retentativas em erros 429/5xx   |
| `headers`    | `object`   | `{}`                      | Headers HTTP adicionais                          |
| `fetch`      | `function` | `globalThis.fetch`        | Implementação customizada de fetch               |

### Tratamento de Erros

```ts theme={null}
import {
  RivooPay,
  RivooPayApiError,
  RivooPayRateLimitError,
  RivooPayIdempotencyError,
  RivooPayTimeoutError,
  RivooPayNetworkError,
} from '@rivoo/sdk';

try {
  await rivoopay.charges.createPixCharge({ /* ... */ });
} catch (error) {
  if (error instanceof RivooPayRateLimitError) {
    console.log(`Rate limited. Tente novamente em ${error.retryAfter}s`);
  } else if (error instanceof RivooPayIdempotencyError) {
    console.log('Conflito de chave de idempotência');
  } else if (error instanceof RivooPayTimeoutError) {
    console.log('Timeout na requisição');
  } else if (error instanceof RivooPayNetworkError) {
    console.log('Erro de rede:', error.message);
  } else if (error instanceof RivooPayApiError) {
    console.log(`Erro da API ${error.statusCode}: ${error.message}`);
    console.log('Corpo da resposta:', error.body);
  }
}
```

| Classe de Erro             | Descrição                            |
| -------------------------- | ------------------------------------ |
| `RivooPayApiError`         | Erro genérico da API (classe base)   |
| `RivooPayRateLimitError`   | Limite de requisições excedido (429) |
| `RivooPayIdempotencyError` | Conflito de chave de idempotência    |
| `RivooPayTimeoutError`     | Timeout na requisição                |
| `RivooPayNetworkError`     | Erro de conexão/rede                 |

## Valores Monetários

Todos os valores monetários na SDK são representados em **centavos** (inteiros):

| Valor Real | Valor na SDK |
| ---------- | ------------ |
| R\$ 5,00   | `500`        |
| R\$ 49,90  | `4990`       |
| R\$ 100,00 | `10000`      |

<Warning>
  O valor mínimo para cobranças é **500** (R\$ 5,00).
</Warning>

## Tipos e Enums

Todos os tipos TypeScript são exportados para uso direto:

```ts theme={null}
import type {
  Customer,
  CreateCustomerInput,
  ChargeDetail,
  CreatePixChargeInput,
  Product,
  Webhook,
  RivooPayResponse,
} from '@rivoo/sdk';

import {
  DefaultStatus,    // ACTIVE | INACTIVE
  ChargeStatus,     // OPEN | COMPLETED | EXPIRED
  PaymentStatus,    // PENDING | PROCESSING | PAID | EXPIRED
  WebhookEvent,     // CHARGE_PAID | CHARGE_EXPIRED | ...
  WithdrawStatus,   // Status de saques
} from '@rivoo/sdk';
```

## Uso com NestJS

```ts theme={null}
import { Module, Injectable } from '@nestjs/common';
import { RivooPay } from '@rivoo/sdk';

@Module({
  providers: [
    {
      provide: RivooPay,
      useFactory: () =>
        new RivooPay({ apiKey: process.env.RIVOOPAY_API_KEY }),
    },
  ],
  exports: [RivooPay],
})
export class RivooPayModule {}

// No service:
@Injectable()
export class PaymentService {
  constructor(private readonly rivoopay: RivooPay) {}

  async createCharge(amount: number) {
    return this.rivoopay.charges.createPixCharge({
      amount,
      customer: { /* ... */ },
    });
  }
}
```

## Compatibilidade

| Ambiente      | Suportado |
| ------------- | --------- |
| Node.js >= 18 | ✅         |
| Bun           | ✅         |
| Deno          | ✅         |
| Browser (ESM) | ✅         |
| NestJS        | ✅         |
| Next.js       | ✅         |
| React Native  | ✅         |

<Note>
  Para Node.js \< 18, passe uma implementação de `fetch` via a opção `fetch` (ex: `node-fetch` ou `undici`).
</Note>
